three.cjs 1.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. 'use strict';
  7. const REVISION = '180dev';
  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} FLAT_FIRST - Flat interpolation using the first vertex.
  1478. * @property {string} FLAT_EITHER - Flat interpolation using either vertex.
  1479. */
  1480. /**
  1481. * This modules allows to dispatch event objects on custom JavaScript objects.
  1482. *
  1483. * Main repository: [eventdispatcher.js]{@link https://github.com/mrdoob/eventdispatcher.js/}
  1484. *
  1485. * Code Example:
  1486. * ```js
  1487. * class Car extends EventDispatcher {
  1488. * start() {
  1489. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  1490. * }
  1491. *};
  1492. *
  1493. * // Using events with the custom object
  1494. * const car = new Car();
  1495. * car.addEventListener( 'start', function ( event ) {
  1496. * alert( event.message );
  1497. * } );
  1498. *
  1499. * car.start();
  1500. * ```
  1501. */
  1502. class EventDispatcher {
  1503. /**
  1504. * Adds the given event listener to the given event type.
  1505. *
  1506. * @param {string} type - The type of event to listen to.
  1507. * @param {Function} listener - The function that gets called when the event is fired.
  1508. */
  1509. addEventListener( type, listener ) {
  1510. if ( this._listeners === undefined ) this._listeners = {};
  1511. const listeners = this._listeners;
  1512. if ( listeners[ type ] === undefined ) {
  1513. listeners[ type ] = [];
  1514. }
  1515. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  1516. listeners[ type ].push( listener );
  1517. }
  1518. }
  1519. /**
  1520. * Returns `true` if the given event listener has been added to the given event type.
  1521. *
  1522. * @param {string} type - The type of event.
  1523. * @param {Function} listener - The listener to check.
  1524. * @return {boolean} Whether the given event listener has been added to the given event type.
  1525. */
  1526. hasEventListener( type, listener ) {
  1527. const listeners = this._listeners;
  1528. if ( listeners === undefined ) return false;
  1529. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  1530. }
  1531. /**
  1532. * Removes the given event listener from the given event type.
  1533. *
  1534. * @param {string} type - The type of event.
  1535. * @param {Function} listener - The listener to remove.
  1536. */
  1537. removeEventListener( type, listener ) {
  1538. const listeners = this._listeners;
  1539. if ( listeners === undefined ) return;
  1540. const listenerArray = listeners[ type ];
  1541. if ( listenerArray !== undefined ) {
  1542. const index = listenerArray.indexOf( listener );
  1543. if ( index !== -1 ) {
  1544. listenerArray.splice( index, 1 );
  1545. }
  1546. }
  1547. }
  1548. /**
  1549. * Dispatches an event object.
  1550. *
  1551. * @param {Object} event - The event that gets fired.
  1552. */
  1553. dispatchEvent( event ) {
  1554. const listeners = this._listeners;
  1555. if ( listeners === undefined ) return;
  1556. const listenerArray = listeners[ event.type ];
  1557. if ( listenerArray !== undefined ) {
  1558. event.target = this;
  1559. // Make a copy, in case listeners are removed while iterating.
  1560. const array = listenerArray.slice( 0 );
  1561. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1562. array[ i ].call( this, event );
  1563. }
  1564. event.target = null;
  1565. }
  1566. }
  1567. }
  1568. 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' ];
  1569. let _seed = 1234567;
  1570. const DEG2RAD = Math.PI / 180;
  1571. const RAD2DEG = 180 / Math.PI;
  1572. /**
  1573. * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
  1574. * (universally unique identifier).
  1575. *
  1576. * @return {string} The UUID.
  1577. */
  1578. function generateUUID() {
  1579. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1580. const d0 = Math.random() * 0xffffffff | 0;
  1581. const d1 = Math.random() * 0xffffffff | 0;
  1582. const d2 = Math.random() * 0xffffffff | 0;
  1583. const d3 = Math.random() * 0xffffffff | 0;
  1584. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1585. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1586. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1587. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1588. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  1589. return uuid.toLowerCase();
  1590. }
  1591. /**
  1592. * Clamps the given value between min and max.
  1593. *
  1594. * @param {number} value - The value to clamp.
  1595. * @param {number} min - The min value.
  1596. * @param {number} max - The max value.
  1597. * @return {number} The clamped value.
  1598. */
  1599. function clamp( value, min, max ) {
  1600. return Math.max( min, Math.min( max, value ) );
  1601. }
  1602. /**
  1603. * Computes the Euclidean modulo of the given parameters that
  1604. * is `( ( n % m ) + m ) % m`.
  1605. *
  1606. * @param {number} n - The first parameter.
  1607. * @param {number} m - The second parameter.
  1608. * @return {number} The Euclidean modulo.
  1609. */
  1610. function euclideanModulo( n, m ) {
  1611. // https://en.wikipedia.org/wiki/Modulo_operation
  1612. return ( ( n % m ) + m ) % m;
  1613. }
  1614. /**
  1615. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1616. * for the given value.
  1617. *
  1618. * @param {number} x - The value to be mapped.
  1619. * @param {number} a1 - Minimum value for range A.
  1620. * @param {number} a2 - Maximum value for range A.
  1621. * @param {number} b1 - Minimum value for range B.
  1622. * @param {number} b2 - Maximum value for range B.
  1623. * @return {number} The mapped value.
  1624. */
  1625. function mapLinear( x, a1, a2, b1, b2 ) {
  1626. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1627. }
  1628. /**
  1629. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1630. * between the start and end point.
  1631. *
  1632. * @param {number} x - The start point
  1633. * @param {number} y - The end point.
  1634. * @param {number} value - A value between start and end.
  1635. * @return {number} The interpolation factor.
  1636. */
  1637. function inverseLerp( x, y, value ) {
  1638. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1639. if ( x !== y ) {
  1640. return ( value - x ) / ( y - x );
  1641. } else {
  1642. return 0;
  1643. }
  1644. }
  1645. /**
  1646. * Returns a value linearly interpolated from two known points based on the given interval -
  1647. * `t = 0` will return `x` and `t = 1` will return `y`.
  1648. *
  1649. * @param {number} x - The start point
  1650. * @param {number} y - The end point.
  1651. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1652. * @return {number} The interpolated value.
  1653. */
  1654. function lerp( x, y, t ) {
  1655. return ( 1 - t ) * x + t * y;
  1656. }
  1657. /**
  1658. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1659. * time to maintain frame rate independent movement. For details, see
  1660. * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
  1661. *
  1662. * @param {number} x - The current point.
  1663. * @param {number} y - The target point.
  1664. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1665. * and a lower value will make the movement more gradual.
  1666. * @param {number} dt - Delta time in seconds.
  1667. * @return {number} The interpolated value.
  1668. */
  1669. function damp( x, y, lambda, dt ) {
  1670. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  1671. }
  1672. /**
  1673. * Returns a value that alternates between `0` and the given `length` parameter.
  1674. *
  1675. * @param {number} x - The value to pingpong.
  1676. * @param {number} [length=1] - The positive value the function will pingpong to.
  1677. * @return {number} The alternated value.
  1678. */
  1679. function pingpong( x, length = 1 ) {
  1680. // https://www.desmos.com/calculator/vcsjnyz7x4
  1681. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  1682. }
  1683. /**
  1684. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  1685. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  1686. * the `min` and `max`.
  1687. *
  1688. * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
  1689. *
  1690. * @param {number} x - The value to evaluate based on its position between min and max.
  1691. * @param {number} min - The min value. Any x value below min will be `0`.
  1692. * @param {number} max - The max value. Any x value above max will be `1`.
  1693. * @return {number} The alternated value.
  1694. */
  1695. function smoothstep( x, min, max ) {
  1696. if ( x <= min ) return 0;
  1697. if ( x >= max ) return 1;
  1698. x = ( x - min ) / ( max - min );
  1699. return x * x * ( 3 - 2 * x );
  1700. }
  1701. /**
  1702. * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
  1703. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  1704. *
  1705. * @param {number} x - The value to evaluate based on its position between min and max.
  1706. * @param {number} min - The min value. Any x value below min will be `0`.
  1707. * @param {number} max - The max value. Any x value above max will be `1`.
  1708. * @return {number} The alternated value.
  1709. */
  1710. function smootherstep( x, min, max ) {
  1711. if ( x <= min ) return 0;
  1712. if ( x >= max ) return 1;
  1713. x = ( x - min ) / ( max - min );
  1714. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  1715. }
  1716. /**
  1717. * Returns a random integer from `<low, high>` interval.
  1718. *
  1719. * @param {number} low - The lower value boundary.
  1720. * @param {number} high - The upper value boundary
  1721. * @return {number} A random integer.
  1722. */
  1723. function randInt( low, high ) {
  1724. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  1725. }
  1726. /**
  1727. * Returns a random float from `<low, high>` interval.
  1728. *
  1729. * @param {number} low - The lower value boundary.
  1730. * @param {number} high - The upper value boundary
  1731. * @return {number} A random float.
  1732. */
  1733. function randFloat( low, high ) {
  1734. return low + Math.random() * ( high - low );
  1735. }
  1736. /**
  1737. * Returns a random integer from `<-range/2, range/2>` interval.
  1738. *
  1739. * @param {number} range - Defines the value range.
  1740. * @return {number} A random float.
  1741. */
  1742. function randFloatSpread( range ) {
  1743. return range * ( 0.5 - Math.random() );
  1744. }
  1745. /**
  1746. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  1747. *
  1748. * @param {number} [s] - The integer seed.
  1749. * @return {number} A random float.
  1750. */
  1751. function seededRandom( s ) {
  1752. if ( s !== undefined ) _seed = s;
  1753. // Mulberry32 generator
  1754. let t = _seed += 0x6D2B79F5;
  1755. t = Math.imul( t ^ t >>> 15, t | 1 );
  1756. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  1757. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  1758. }
  1759. /**
  1760. * Converts degrees to radians.
  1761. *
  1762. * @param {number} degrees - A value in degrees.
  1763. * @return {number} The converted value in radians.
  1764. */
  1765. function degToRad( degrees ) {
  1766. return degrees * DEG2RAD;
  1767. }
  1768. /**
  1769. * Converts radians to degrees.
  1770. *
  1771. * @param {number} radians - A value in radians.
  1772. * @return {number} The converted value in degrees.
  1773. */
  1774. function radToDeg( radians ) {
  1775. return radians * RAD2DEG;
  1776. }
  1777. /**
  1778. * Returns `true` if the given number is a power of two.
  1779. *
  1780. * @param {number} value - The value to check.
  1781. * @return {boolean} Whether the given number is a power of two or not.
  1782. */
  1783. function isPowerOfTwo( value ) {
  1784. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  1785. }
  1786. /**
  1787. * Returns the smallest power of two that is greater than or equal to the given number.
  1788. *
  1789. * @param {number} value - The value to find a POT for.
  1790. * @return {number} The smallest power of two that is greater than or equal to the given number.
  1791. */
  1792. function ceilPowerOfTwo( value ) {
  1793. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  1794. }
  1795. /**
  1796. * Returns the largest power of two that is less than or equal to the given number.
  1797. *
  1798. * @param {number} value - The value to find a POT for.
  1799. * @return {number} The largest power of two that is less than or equal to the given number.
  1800. */
  1801. function floorPowerOfTwo( value ) {
  1802. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  1803. }
  1804. /**
  1805. * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
  1806. * defined by the given angles and order.
  1807. *
  1808. * Rotations are applied to the axes in the order specified by order:
  1809. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  1810. *
  1811. * @param {Quaternion} q - The quaternion to set.
  1812. * @param {number} a - The rotation applied to the first axis, in radians.
  1813. * @param {number} b - The rotation applied to the second axis, in radians.
  1814. * @param {number} c - The rotation applied to the third axis, in radians.
  1815. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  1816. */
  1817. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  1818. const cos = Math.cos;
  1819. const sin = Math.sin;
  1820. const c2 = cos( b / 2 );
  1821. const s2 = sin( b / 2 );
  1822. const c13 = cos( ( a + c ) / 2 );
  1823. const s13 = sin( ( a + c ) / 2 );
  1824. const c1_3 = cos( ( a - c ) / 2 );
  1825. const s1_3 = sin( ( a - c ) / 2 );
  1826. const c3_1 = cos( ( c - a ) / 2 );
  1827. const s3_1 = sin( ( c - a ) / 2 );
  1828. switch ( order ) {
  1829. case 'XYX':
  1830. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  1831. break;
  1832. case 'YZY':
  1833. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  1834. break;
  1835. case 'ZXZ':
  1836. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  1837. break;
  1838. case 'XZX':
  1839. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  1840. break;
  1841. case 'YXY':
  1842. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  1843. break;
  1844. case 'ZYZ':
  1845. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  1846. break;
  1847. default:
  1848. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  1849. }
  1850. }
  1851. /**
  1852. * Denormalizes the given value according to the given typed array.
  1853. *
  1854. * @param {number} value - The value to denormalize.
  1855. * @param {TypedArray} array - The typed array that defines the data type of the value.
  1856. * @return {number} The denormalize (float) value in the range `[0,1]`.
  1857. */
  1858. function denormalize( value, array ) {
  1859. switch ( array.constructor ) {
  1860. case Float32Array:
  1861. return value;
  1862. case Uint32Array:
  1863. return value / 4294967295.0;
  1864. case Uint16Array:
  1865. return value / 65535.0;
  1866. case Uint8Array:
  1867. return value / 255.0;
  1868. case Int32Array:
  1869. return Math.max( value / 2147483647.0, -1 );
  1870. case Int16Array:
  1871. return Math.max( value / 32767.0, -1 );
  1872. case Int8Array:
  1873. return Math.max( value / 127.0, -1 );
  1874. default:
  1875. throw new Error( 'Invalid component type.' );
  1876. }
  1877. }
  1878. /**
  1879. * Normalizes the given value according to the given typed array.
  1880. *
  1881. * @param {number} value - The float value in the range `[0,1]` to normalize.
  1882. * @param {TypedArray} array - The typed array that defines the data type of the value.
  1883. * @return {number} The normalize value.
  1884. */
  1885. function normalize( value, array ) {
  1886. switch ( array.constructor ) {
  1887. case Float32Array:
  1888. return value;
  1889. case Uint32Array:
  1890. return Math.round( value * 4294967295.0 );
  1891. case Uint16Array:
  1892. return Math.round( value * 65535.0 );
  1893. case Uint8Array:
  1894. return Math.round( value * 255.0 );
  1895. case Int32Array:
  1896. return Math.round( value * 2147483647.0 );
  1897. case Int16Array:
  1898. return Math.round( value * 32767.0 );
  1899. case Int8Array:
  1900. return Math.round( value * 127.0 );
  1901. default:
  1902. throw new Error( 'Invalid component type.' );
  1903. }
  1904. }
  1905. /**
  1906. * @class
  1907. * @classdesc A collection of math utility functions.
  1908. * @hideconstructor
  1909. */
  1910. const MathUtils = {
  1911. DEG2RAD: DEG2RAD,
  1912. RAD2DEG: RAD2DEG,
  1913. /**
  1914. * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
  1915. * (universally unique identifier).
  1916. *
  1917. * @static
  1918. * @method
  1919. * @return {string} The UUID.
  1920. */
  1921. generateUUID: generateUUID,
  1922. /**
  1923. * Clamps the given value between min and max.
  1924. *
  1925. * @static
  1926. * @method
  1927. * @param {number} value - The value to clamp.
  1928. * @param {number} min - The min value.
  1929. * @param {number} max - The max value.
  1930. * @return {number} The clamped value.
  1931. */
  1932. clamp: clamp,
  1933. /**
  1934. * Computes the Euclidean modulo of the given parameters that
  1935. * is `( ( n % m ) + m ) % m`.
  1936. *
  1937. * @static
  1938. * @method
  1939. * @param {number} n - The first parameter.
  1940. * @param {number} m - The second parameter.
  1941. * @return {number} The Euclidean modulo.
  1942. */
  1943. euclideanModulo: euclideanModulo,
  1944. /**
  1945. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1946. * for the given value.
  1947. *
  1948. * @static
  1949. * @method
  1950. * @param {number} x - The value to be mapped.
  1951. * @param {number} a1 - Minimum value for range A.
  1952. * @param {number} a2 - Maximum value for range A.
  1953. * @param {number} b1 - Minimum value for range B.
  1954. * @param {number} b2 - Maximum value for range B.
  1955. * @return {number} The mapped value.
  1956. */
  1957. mapLinear: mapLinear,
  1958. /**
  1959. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1960. * between the start and end point.
  1961. *
  1962. * @static
  1963. * @method
  1964. * @param {number} x - The start point
  1965. * @param {number} y - The end point.
  1966. * @param {number} value - A value between start and end.
  1967. * @return {number} The interpolation factor.
  1968. */
  1969. inverseLerp: inverseLerp,
  1970. /**
  1971. * Returns a value linearly interpolated from two known points based on the given interval -
  1972. * `t = 0` will return `x` and `t = 1` will return `y`.
  1973. *
  1974. * @static
  1975. * @method
  1976. * @param {number} x - The start point
  1977. * @param {number} y - The end point.
  1978. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1979. * @return {number} The interpolated value.
  1980. */
  1981. lerp: lerp,
  1982. /**
  1983. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1984. * time to maintain frame rate independent movement. For details, see
  1985. * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
  1986. *
  1987. * @static
  1988. * @method
  1989. * @param {number} x - The current point.
  1990. * @param {number} y - The target point.
  1991. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1992. * and a lower value will make the movement more gradual.
  1993. * @param {number} dt - Delta time in seconds.
  1994. * @return {number} The interpolated value.
  1995. */
  1996. damp: damp,
  1997. /**
  1998. * Returns a value that alternates between `0` and the given `length` parameter.
  1999. *
  2000. * @static
  2001. * @method
  2002. * @param {number} x - The value to pingpong.
  2003. * @param {number} [length=1] - The positive value the function will pingpong to.
  2004. * @return {number} The alternated value.
  2005. */
  2006. pingpong: pingpong,
  2007. /**
  2008. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2009. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2010. * the `min` and `max`.
  2011. *
  2012. * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
  2013. *
  2014. * @static
  2015. * @method
  2016. * @param {number} x - The value to evaluate based on its position between min and max.
  2017. * @param {number} min - The min value. Any x value below min will be `0`.
  2018. * @param {number} max - The max value. Any x value above max will be `1`.
  2019. * @return {number} The alternated value.
  2020. */
  2021. smoothstep: smoothstep,
  2022. /**
  2023. * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
  2024. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  2025. *
  2026. * @static
  2027. * @method
  2028. * @param {number} x - The value to evaluate based on its position between min and max.
  2029. * @param {number} min - The min value. Any x value below min will be `0`.
  2030. * @param {number} max - The max value. Any x value above max will be `1`.
  2031. * @return {number} The alternated value.
  2032. */
  2033. smootherstep: smootherstep,
  2034. /**
  2035. * Returns a random integer from `<low, high>` interval.
  2036. *
  2037. * @static
  2038. * @method
  2039. * @param {number} low - The lower value boundary.
  2040. * @param {number} high - The upper value boundary
  2041. * @return {number} A random integer.
  2042. */
  2043. randInt: randInt,
  2044. /**
  2045. * Returns a random float from `<low, high>` interval.
  2046. *
  2047. * @static
  2048. * @method
  2049. * @param {number} low - The lower value boundary.
  2050. * @param {number} high - The upper value boundary
  2051. * @return {number} A random float.
  2052. */
  2053. randFloat: randFloat,
  2054. /**
  2055. * Returns a random integer from `<-range/2, range/2>` interval.
  2056. *
  2057. * @static
  2058. * @method
  2059. * @param {number} range - Defines the value range.
  2060. * @return {number} A random float.
  2061. */
  2062. randFloatSpread: randFloatSpread,
  2063. /**
  2064. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2065. *
  2066. * @static
  2067. * @method
  2068. * @param {number} [s] - The integer seed.
  2069. * @return {number} A random float.
  2070. */
  2071. seededRandom: seededRandom,
  2072. /**
  2073. * Converts degrees to radians.
  2074. *
  2075. * @static
  2076. * @method
  2077. * @param {number} degrees - A value in degrees.
  2078. * @return {number} The converted value in radians.
  2079. */
  2080. degToRad: degToRad,
  2081. /**
  2082. * Converts radians to degrees.
  2083. *
  2084. * @static
  2085. * @method
  2086. * @param {number} radians - A value in radians.
  2087. * @return {number} The converted value in degrees.
  2088. */
  2089. radToDeg: radToDeg,
  2090. /**
  2091. * Returns `true` if the given number is a power of two.
  2092. *
  2093. * @static
  2094. * @method
  2095. * @param {number} value - The value to check.
  2096. * @return {boolean} Whether the given number is a power of two or not.
  2097. */
  2098. isPowerOfTwo: isPowerOfTwo,
  2099. /**
  2100. * Returns the smallest power of two that is greater than or equal to the given number.
  2101. *
  2102. * @static
  2103. * @method
  2104. * @param {number} value - The value to find a POT for.
  2105. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2106. */
  2107. ceilPowerOfTwo: ceilPowerOfTwo,
  2108. /**
  2109. * Returns the largest power of two that is less than or equal to the given number.
  2110. *
  2111. * @static
  2112. * @method
  2113. * @param {number} value - The value to find a POT for.
  2114. * @return {number} The largest power of two that is less than or equal to the given number.
  2115. */
  2116. floorPowerOfTwo: floorPowerOfTwo,
  2117. /**
  2118. * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
  2119. * defined by the given angles and order.
  2120. *
  2121. * Rotations are applied to the axes in the order specified by order:
  2122. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2123. *
  2124. * @static
  2125. * @method
  2126. * @param {Quaternion} q - The quaternion to set.
  2127. * @param {number} a - The rotation applied to the first axis, in radians.
  2128. * @param {number} b - The rotation applied to the second axis, in radians.
  2129. * @param {number} c - The rotation applied to the third axis, in radians.
  2130. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2131. */
  2132. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  2133. /**
  2134. * Normalizes the given value according to the given typed array.
  2135. *
  2136. * @static
  2137. * @method
  2138. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2139. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2140. * @return {number} The normalize value.
  2141. */
  2142. normalize: normalize,
  2143. /**
  2144. * Denormalizes the given value according to the given typed array.
  2145. *
  2146. * @static
  2147. * @method
  2148. * @param {number} value - The value to denormalize.
  2149. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2150. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2151. */
  2152. denormalize: denormalize
  2153. };
  2154. /**
  2155. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  2156. * (labeled x and y), which can be used to represent a number of things, such as:
  2157. *
  2158. * - A point in 2D space (i.e. a position on a plane).
  2159. * - A direction and length across a plane. In three.js the length will
  2160. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  2161. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  2162. * - Any arbitrary ordered pair of numbers.
  2163. *
  2164. * There are other things a 2D vector can be used to represent, such as
  2165. * momentum vectors, complex numbers and so on, however these are the most
  2166. * common uses in three.js.
  2167. *
  2168. * Iterating through a vector instance will yield its components `(x, y)` in
  2169. * the corresponding order.
  2170. * ```js
  2171. * const a = new THREE.Vector2( 0, 1 );
  2172. *
  2173. * //no arguments; will be initialised to (0, 0)
  2174. * const b = new THREE.Vector2( );
  2175. *
  2176. * const d = a.distanceTo( b );
  2177. * ```
  2178. */
  2179. class Vector2 {
  2180. /**
  2181. * Constructs a new 2D vector.
  2182. *
  2183. * @param {number} [x=0] - The x value of this vector.
  2184. * @param {number} [y=0] - The y value of this vector.
  2185. */
  2186. constructor( x = 0, y = 0 ) {
  2187. /**
  2188. * This flag can be used for type testing.
  2189. *
  2190. * @type {boolean}
  2191. * @readonly
  2192. * @default true
  2193. */
  2194. Vector2.prototype.isVector2 = true;
  2195. /**
  2196. * The x value of this vector.
  2197. *
  2198. * @type {number}
  2199. */
  2200. this.x = x;
  2201. /**
  2202. * The y value of this vector.
  2203. *
  2204. * @type {number}
  2205. */
  2206. this.y = y;
  2207. }
  2208. /**
  2209. * Alias for {@link Vector2#x}.
  2210. *
  2211. * @type {number}
  2212. */
  2213. get width() {
  2214. return this.x;
  2215. }
  2216. set width( value ) {
  2217. this.x = value;
  2218. }
  2219. /**
  2220. * Alias for {@link Vector2#y}.
  2221. *
  2222. * @type {number}
  2223. */
  2224. get height() {
  2225. return this.y;
  2226. }
  2227. set height( value ) {
  2228. this.y = value;
  2229. }
  2230. /**
  2231. * Sets the vector components.
  2232. *
  2233. * @param {number} x - The value of the x component.
  2234. * @param {number} y - The value of the y component.
  2235. * @return {Vector2} A reference to this vector.
  2236. */
  2237. set( x, y ) {
  2238. this.x = x;
  2239. this.y = y;
  2240. return this;
  2241. }
  2242. /**
  2243. * Sets the vector components to the same value.
  2244. *
  2245. * @param {number} scalar - The value to set for all vector components.
  2246. * @return {Vector2} A reference to this vector.
  2247. */
  2248. setScalar( scalar ) {
  2249. this.x = scalar;
  2250. this.y = scalar;
  2251. return this;
  2252. }
  2253. /**
  2254. * Sets the vector's x component to the given value
  2255. *
  2256. * @param {number} x - The value to set.
  2257. * @return {Vector2} A reference to this vector.
  2258. */
  2259. setX( x ) {
  2260. this.x = x;
  2261. return this;
  2262. }
  2263. /**
  2264. * Sets the vector's y component to the given value
  2265. *
  2266. * @param {number} y - The value to set.
  2267. * @return {Vector2} A reference to this vector.
  2268. */
  2269. setY( y ) {
  2270. this.y = y;
  2271. return this;
  2272. }
  2273. /**
  2274. * Allows to set a vector component with an index.
  2275. *
  2276. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2277. * @param {number} value - The value to set.
  2278. * @return {Vector2} A reference to this vector.
  2279. */
  2280. setComponent( index, value ) {
  2281. switch ( index ) {
  2282. case 0: this.x = value; break;
  2283. case 1: this.y = value; break;
  2284. default: throw new Error( 'index is out of range: ' + index );
  2285. }
  2286. return this;
  2287. }
  2288. /**
  2289. * Returns the value of the vector component which matches the given index.
  2290. *
  2291. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2292. * @return {number} A vector component value.
  2293. */
  2294. getComponent( index ) {
  2295. switch ( index ) {
  2296. case 0: return this.x;
  2297. case 1: return this.y;
  2298. default: throw new Error( 'index is out of range: ' + index );
  2299. }
  2300. }
  2301. /**
  2302. * Returns a new vector with copied values from this instance.
  2303. *
  2304. * @return {Vector2} A clone of this instance.
  2305. */
  2306. clone() {
  2307. return new this.constructor( this.x, this.y );
  2308. }
  2309. /**
  2310. * Copies the values of the given vector to this instance.
  2311. *
  2312. * @param {Vector2} v - The vector to copy.
  2313. * @return {Vector2} A reference to this vector.
  2314. */
  2315. copy( v ) {
  2316. this.x = v.x;
  2317. this.y = v.y;
  2318. return this;
  2319. }
  2320. /**
  2321. * Adds the given vector to this instance.
  2322. *
  2323. * @param {Vector2} v - The vector to add.
  2324. * @return {Vector2} A reference to this vector.
  2325. */
  2326. add( v ) {
  2327. this.x += v.x;
  2328. this.y += v.y;
  2329. return this;
  2330. }
  2331. /**
  2332. * Adds the given scalar value to all components of this instance.
  2333. *
  2334. * @param {number} s - The scalar to add.
  2335. * @return {Vector2} A reference to this vector.
  2336. */
  2337. addScalar( s ) {
  2338. this.x += s;
  2339. this.y += s;
  2340. return this;
  2341. }
  2342. /**
  2343. * Adds the given vectors and stores the result in this instance.
  2344. *
  2345. * @param {Vector2} a - The first vector.
  2346. * @param {Vector2} b - The second vector.
  2347. * @return {Vector2} A reference to this vector.
  2348. */
  2349. addVectors( a, b ) {
  2350. this.x = a.x + b.x;
  2351. this.y = a.y + b.y;
  2352. return this;
  2353. }
  2354. /**
  2355. * Adds the given vector scaled by the given factor to this instance.
  2356. *
  2357. * @param {Vector2} v - The vector.
  2358. * @param {number} s - The factor that scales `v`.
  2359. * @return {Vector2} A reference to this vector.
  2360. */
  2361. addScaledVector( v, s ) {
  2362. this.x += v.x * s;
  2363. this.y += v.y * s;
  2364. return this;
  2365. }
  2366. /**
  2367. * Subtracts the given vector from this instance.
  2368. *
  2369. * @param {Vector2} v - The vector to subtract.
  2370. * @return {Vector2} A reference to this vector.
  2371. */
  2372. sub( v ) {
  2373. this.x -= v.x;
  2374. this.y -= v.y;
  2375. return this;
  2376. }
  2377. /**
  2378. * Subtracts the given scalar value from all components of this instance.
  2379. *
  2380. * @param {number} s - The scalar to subtract.
  2381. * @return {Vector2} A reference to this vector.
  2382. */
  2383. subScalar( s ) {
  2384. this.x -= s;
  2385. this.y -= s;
  2386. return this;
  2387. }
  2388. /**
  2389. * Subtracts the given vectors and stores the result in this instance.
  2390. *
  2391. * @param {Vector2} a - The first vector.
  2392. * @param {Vector2} b - The second vector.
  2393. * @return {Vector2} A reference to this vector.
  2394. */
  2395. subVectors( a, b ) {
  2396. this.x = a.x - b.x;
  2397. this.y = a.y - b.y;
  2398. return this;
  2399. }
  2400. /**
  2401. * Multiplies the given vector with this instance.
  2402. *
  2403. * @param {Vector2} v - The vector to multiply.
  2404. * @return {Vector2} A reference to this vector.
  2405. */
  2406. multiply( v ) {
  2407. this.x *= v.x;
  2408. this.y *= v.y;
  2409. return this;
  2410. }
  2411. /**
  2412. * Multiplies the given scalar value with all components of this instance.
  2413. *
  2414. * @param {number} scalar - The scalar to multiply.
  2415. * @return {Vector2} A reference to this vector.
  2416. */
  2417. multiplyScalar( scalar ) {
  2418. this.x *= scalar;
  2419. this.y *= scalar;
  2420. return this;
  2421. }
  2422. /**
  2423. * Divides this instance by the given vector.
  2424. *
  2425. * @param {Vector2} v - The vector to divide.
  2426. * @return {Vector2} A reference to this vector.
  2427. */
  2428. divide( v ) {
  2429. this.x /= v.x;
  2430. this.y /= v.y;
  2431. return this;
  2432. }
  2433. /**
  2434. * Divides this vector by the given scalar.
  2435. *
  2436. * @param {number} scalar - The scalar to divide.
  2437. * @return {Vector2} A reference to this vector.
  2438. */
  2439. divideScalar( scalar ) {
  2440. return this.multiplyScalar( 1 / scalar );
  2441. }
  2442. /**
  2443. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  2444. * the given 3x3 matrix.
  2445. *
  2446. * @param {Matrix3} m - The matrix to apply.
  2447. * @return {Vector2} A reference to this vector.
  2448. */
  2449. applyMatrix3( m ) {
  2450. const x = this.x, y = this.y;
  2451. const e = m.elements;
  2452. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  2453. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  2454. return this;
  2455. }
  2456. /**
  2457. * If this vector's x or y value is greater than the given vector's x or y
  2458. * value, replace that value with the corresponding min value.
  2459. *
  2460. * @param {Vector2} v - The vector.
  2461. * @return {Vector2} A reference to this vector.
  2462. */
  2463. min( v ) {
  2464. this.x = Math.min( this.x, v.x );
  2465. this.y = Math.min( this.y, v.y );
  2466. return this;
  2467. }
  2468. /**
  2469. * If this vector's x or y value is less than the given vector's x or y
  2470. * value, replace that value with the corresponding max value.
  2471. *
  2472. * @param {Vector2} v - The vector.
  2473. * @return {Vector2} A reference to this vector.
  2474. */
  2475. max( v ) {
  2476. this.x = Math.max( this.x, v.x );
  2477. this.y = Math.max( this.y, v.y );
  2478. return this;
  2479. }
  2480. /**
  2481. * If this vector's x or y value is greater than the max vector's x or y
  2482. * value, it is replaced by the corresponding value.
  2483. * If this vector's x or y value is less than the min vector's x or y value,
  2484. * it is replaced by the corresponding value.
  2485. *
  2486. * @param {Vector2} min - The minimum x and y values.
  2487. * @param {Vector2} max - The maximum x and y values in the desired range.
  2488. * @return {Vector2} A reference to this vector.
  2489. */
  2490. clamp( min, max ) {
  2491. // assumes min < max, componentwise
  2492. this.x = clamp( this.x, min.x, max.x );
  2493. this.y = clamp( this.y, min.y, max.y );
  2494. return this;
  2495. }
  2496. /**
  2497. * If this vector's x or y values are greater than the max value, they are
  2498. * replaced by the max value.
  2499. * If this vector's x or y values are less than the min value, they are
  2500. * replaced by the min value.
  2501. *
  2502. * @param {number} minVal - The minimum value the components will be clamped to.
  2503. * @param {number} maxVal - The maximum value the components will be clamped to.
  2504. * @return {Vector2} A reference to this vector.
  2505. */
  2506. clampScalar( minVal, maxVal ) {
  2507. this.x = clamp( this.x, minVal, maxVal );
  2508. this.y = clamp( this.y, minVal, maxVal );
  2509. return this;
  2510. }
  2511. /**
  2512. * If this vector's length is greater than the max value, it is replaced by
  2513. * the max value.
  2514. * If this vector's length is less than the min value, it is replaced by the
  2515. * min value.
  2516. *
  2517. * @param {number} min - The minimum value the vector length will be clamped to.
  2518. * @param {number} max - The maximum value the vector length will be clamped to.
  2519. * @return {Vector2} A reference to this vector.
  2520. */
  2521. clampLength( min, max ) {
  2522. const length = this.length();
  2523. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2524. }
  2525. /**
  2526. * The components of this vector are rounded down to the nearest integer value.
  2527. *
  2528. * @return {Vector2} A reference to this vector.
  2529. */
  2530. floor() {
  2531. this.x = Math.floor( this.x );
  2532. this.y = Math.floor( this.y );
  2533. return this;
  2534. }
  2535. /**
  2536. * The components of this vector are rounded up to the nearest integer value.
  2537. *
  2538. * @return {Vector2} A reference to this vector.
  2539. */
  2540. ceil() {
  2541. this.x = Math.ceil( this.x );
  2542. this.y = Math.ceil( this.y );
  2543. return this;
  2544. }
  2545. /**
  2546. * The components of this vector are rounded to the nearest integer value
  2547. *
  2548. * @return {Vector2} A reference to this vector.
  2549. */
  2550. round() {
  2551. this.x = Math.round( this.x );
  2552. this.y = Math.round( this.y );
  2553. return this;
  2554. }
  2555. /**
  2556. * The components of this vector are rounded towards zero (up if negative,
  2557. * down if positive) to an integer value.
  2558. *
  2559. * @return {Vector2} A reference to this vector.
  2560. */
  2561. roundToZero() {
  2562. this.x = Math.trunc( this.x );
  2563. this.y = Math.trunc( this.y );
  2564. return this;
  2565. }
  2566. /**
  2567. * Inverts this vector - i.e. sets x = -x and y = -y.
  2568. *
  2569. * @return {Vector2} A reference to this vector.
  2570. */
  2571. negate() {
  2572. this.x = - this.x;
  2573. this.y = - this.y;
  2574. return this;
  2575. }
  2576. /**
  2577. * Calculates the dot product of the given vector with this instance.
  2578. *
  2579. * @param {Vector2} v - The vector to compute the dot product with.
  2580. * @return {number} The result of the dot product.
  2581. */
  2582. dot( v ) {
  2583. return this.x * v.x + this.y * v.y;
  2584. }
  2585. /**
  2586. * Calculates the cross product of the given vector with this instance.
  2587. *
  2588. * @param {Vector2} v - The vector to compute the cross product with.
  2589. * @return {number} The result of the cross product.
  2590. */
  2591. cross( v ) {
  2592. return this.x * v.y - this.y * v.x;
  2593. }
  2594. /**
  2595. * Computes the square of the Euclidean length (straight-line length) from
  2596. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  2597. * compare the length squared instead as it is slightly more efficient to calculate.
  2598. *
  2599. * @return {number} The square length of this vector.
  2600. */
  2601. lengthSq() {
  2602. return this.x * this.x + this.y * this.y;
  2603. }
  2604. /**
  2605. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  2606. *
  2607. * @return {number} The length of this vector.
  2608. */
  2609. length() {
  2610. return Math.sqrt( this.x * this.x + this.y * this.y );
  2611. }
  2612. /**
  2613. * Computes the Manhattan length of this vector.
  2614. *
  2615. * @return {number} The length of this vector.
  2616. */
  2617. manhattanLength() {
  2618. return Math.abs( this.x ) + Math.abs( this.y );
  2619. }
  2620. /**
  2621. * Converts this vector to a unit vector - that is, sets it equal to a vector
  2622. * with the same direction as this one, but with a vector length of `1`.
  2623. *
  2624. * @return {Vector2} A reference to this vector.
  2625. */
  2626. normalize() {
  2627. return this.divideScalar( this.length() || 1 );
  2628. }
  2629. /**
  2630. * Computes the angle in radians of this vector with respect to the positive x-axis.
  2631. *
  2632. * @return {number} The angle in radians.
  2633. */
  2634. angle() {
  2635. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  2636. return angle;
  2637. }
  2638. /**
  2639. * Returns the angle between the given vector and this instance in radians.
  2640. *
  2641. * @param {Vector2} v - The vector to compute the angle with.
  2642. * @return {number} The angle in radians.
  2643. */
  2644. angleTo( v ) {
  2645. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2646. if ( denominator === 0 ) return Math.PI / 2;
  2647. const theta = this.dot( v ) / denominator;
  2648. // clamp, to handle numerical problems
  2649. return Math.acos( clamp( theta, -1, 1 ) );
  2650. }
  2651. /**
  2652. * Computes the distance from the given vector to this instance.
  2653. *
  2654. * @param {Vector2} v - The vector to compute the distance to.
  2655. * @return {number} The distance.
  2656. */
  2657. distanceTo( v ) {
  2658. return Math.sqrt( this.distanceToSquared( v ) );
  2659. }
  2660. /**
  2661. * Computes the squared distance from the given vector to this instance.
  2662. * If you are just comparing the distance with another distance, you should compare
  2663. * the distance squared instead as it is slightly more efficient to calculate.
  2664. *
  2665. * @param {Vector2} v - The vector to compute the squared distance to.
  2666. * @return {number} The squared distance.
  2667. */
  2668. distanceToSquared( v ) {
  2669. const dx = this.x - v.x, dy = this.y - v.y;
  2670. return dx * dx + dy * dy;
  2671. }
  2672. /**
  2673. * Computes the Manhattan distance from the given vector to this instance.
  2674. *
  2675. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  2676. * @return {number} The Manhattan distance.
  2677. */
  2678. manhattanDistanceTo( v ) {
  2679. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  2680. }
  2681. /**
  2682. * Sets this vector to a vector with the same direction as this one, but
  2683. * with the specified length.
  2684. *
  2685. * @param {number} length - The new length of this vector.
  2686. * @return {Vector2} A reference to this vector.
  2687. */
  2688. setLength( length ) {
  2689. return this.normalize().multiplyScalar( length );
  2690. }
  2691. /**
  2692. * Linearly interpolates between the given vector and this instance, where
  2693. * alpha is the percent distance along the line - alpha = 0 will be this
  2694. * vector, and alpha = 1 will be the given one.
  2695. *
  2696. * @param {Vector2} v - The vector to interpolate towards.
  2697. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2698. * @return {Vector2} A reference to this vector.
  2699. */
  2700. lerp( v, alpha ) {
  2701. this.x += ( v.x - this.x ) * alpha;
  2702. this.y += ( v.y - this.y ) * alpha;
  2703. return this;
  2704. }
  2705. /**
  2706. * Linearly interpolates between the given vectors, where alpha is the percent
  2707. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  2708. * be the second one. The result is stored in this instance.
  2709. *
  2710. * @param {Vector2} v1 - The first vector.
  2711. * @param {Vector2} v2 - The second vector.
  2712. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2713. * @return {Vector2} A reference to this vector.
  2714. */
  2715. lerpVectors( v1, v2, alpha ) {
  2716. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2717. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2718. return this;
  2719. }
  2720. /**
  2721. * Returns `true` if this vector is equal with the given one.
  2722. *
  2723. * @param {Vector2} v - The vector to test for equality.
  2724. * @return {boolean} Whether this vector is equal with the given one.
  2725. */
  2726. equals( v ) {
  2727. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  2728. }
  2729. /**
  2730. * Sets this vector's x value to be `array[ offset ]` and y
  2731. * value to be `array[ offset + 1 ]`.
  2732. *
  2733. * @param {Array<number>} array - An array holding the vector component values.
  2734. * @param {number} [offset=0] - The offset into the array.
  2735. * @return {Vector2} A reference to this vector.
  2736. */
  2737. fromArray( array, offset = 0 ) {
  2738. this.x = array[ offset ];
  2739. this.y = array[ offset + 1 ];
  2740. return this;
  2741. }
  2742. /**
  2743. * Writes the components of this vector to the given array. If no array is provided,
  2744. * the method returns a new instance.
  2745. *
  2746. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  2747. * @param {number} [offset=0] - Index of the first element in the array.
  2748. * @return {Array<number>} The vector components.
  2749. */
  2750. toArray( array = [], offset = 0 ) {
  2751. array[ offset ] = this.x;
  2752. array[ offset + 1 ] = this.y;
  2753. return array;
  2754. }
  2755. /**
  2756. * Sets the components of this vector from the given buffer attribute.
  2757. *
  2758. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  2759. * @param {number} index - The index into the attribute.
  2760. * @return {Vector2} A reference to this vector.
  2761. */
  2762. fromBufferAttribute( attribute, index ) {
  2763. this.x = attribute.getX( index );
  2764. this.y = attribute.getY( index );
  2765. return this;
  2766. }
  2767. /**
  2768. * Rotates this vector around the given center by the given angle.
  2769. *
  2770. * @param {Vector2} center - The point around which to rotate.
  2771. * @param {number} angle - The angle to rotate, in radians.
  2772. * @return {Vector2} A reference to this vector.
  2773. */
  2774. rotateAround( center, angle ) {
  2775. const c = Math.cos( angle ), s = Math.sin( angle );
  2776. const x = this.x - center.x;
  2777. const y = this.y - center.y;
  2778. this.x = x * c - y * s + center.x;
  2779. this.y = x * s + y * c + center.y;
  2780. return this;
  2781. }
  2782. /**
  2783. * Sets each component of this vector to a pseudo-random value between `0` and
  2784. * `1`, excluding `1`.
  2785. *
  2786. * @return {Vector2} A reference to this vector.
  2787. */
  2788. random() {
  2789. this.x = Math.random();
  2790. this.y = Math.random();
  2791. return this;
  2792. }
  2793. *[ Symbol.iterator ]() {
  2794. yield this.x;
  2795. yield this.y;
  2796. }
  2797. }
  2798. /**
  2799. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  2800. *
  2801. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  2802. * the corresponding order.
  2803. *
  2804. * Note that three.js expects Quaternions to be normalized.
  2805. * ```js
  2806. * const quaternion = new THREE.Quaternion();
  2807. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  2808. *
  2809. * const vector = new THREE.Vector3( 1, 0, 0 );
  2810. * vector.applyQuaternion( quaternion );
  2811. * ```
  2812. */
  2813. class Quaternion {
  2814. /**
  2815. * Constructs a new quaternion.
  2816. *
  2817. * @param {number} [x=0] - The x value of this quaternion.
  2818. * @param {number} [y=0] - The y value of this quaternion.
  2819. * @param {number} [z=0] - The z value of this quaternion.
  2820. * @param {number} [w=1] - The w value of this quaternion.
  2821. */
  2822. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2823. /**
  2824. * This flag can be used for type testing.
  2825. *
  2826. * @type {boolean}
  2827. * @readonly
  2828. * @default true
  2829. */
  2830. this.isQuaternion = true;
  2831. this._x = x;
  2832. this._y = y;
  2833. this._z = z;
  2834. this._w = w;
  2835. }
  2836. /**
  2837. * Interpolates between two quaternions via SLERP. This implementation assumes the
  2838. * quaternion data are managed in flat arrays.
  2839. *
  2840. * @param {Array<number>} dst - The destination array.
  2841. * @param {number} dstOffset - An offset into the destination array.
  2842. * @param {Array<number>} src0 - The source array of the first quaternion.
  2843. * @param {number} srcOffset0 - An offset into the first source array.
  2844. * @param {Array<number>} src1 - The source array of the second quaternion.
  2845. * @param {number} srcOffset1 - An offset into the second source array.
  2846. * @param {number} t - The interpolation factor in the range `[0,1]`.
  2847. * @see {@link Quaternion#slerp}
  2848. */
  2849. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2850. // fuzz-free, array-based Quaternion SLERP operation
  2851. let x0 = src0[ srcOffset0 + 0 ],
  2852. y0 = src0[ srcOffset0 + 1 ],
  2853. z0 = src0[ srcOffset0 + 2 ],
  2854. w0 = src0[ srcOffset0 + 3 ];
  2855. const x1 = src1[ srcOffset1 + 0 ],
  2856. y1 = src1[ srcOffset1 + 1 ],
  2857. z1 = src1[ srcOffset1 + 2 ],
  2858. w1 = src1[ srcOffset1 + 3 ];
  2859. if ( t === 0 ) {
  2860. dst[ dstOffset + 0 ] = x0;
  2861. dst[ dstOffset + 1 ] = y0;
  2862. dst[ dstOffset + 2 ] = z0;
  2863. dst[ dstOffset + 3 ] = w0;
  2864. return;
  2865. }
  2866. if ( t === 1 ) {
  2867. dst[ dstOffset + 0 ] = x1;
  2868. dst[ dstOffset + 1 ] = y1;
  2869. dst[ dstOffset + 2 ] = z1;
  2870. dst[ dstOffset + 3 ] = w1;
  2871. return;
  2872. }
  2873. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2874. let s = 1 - t;
  2875. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2876. dir = ( cos >= 0 ? 1 : -1 ),
  2877. sqrSin = 1 - cos * cos;
  2878. // Skip the Slerp for tiny steps to avoid numeric problems:
  2879. if ( sqrSin > Number.EPSILON ) {
  2880. const sin = Math.sqrt( sqrSin ),
  2881. len = Math.atan2( sin, cos * dir );
  2882. s = Math.sin( s * len ) / sin;
  2883. t = Math.sin( t * len ) / sin;
  2884. }
  2885. const tDir = t * dir;
  2886. x0 = x0 * s + x1 * tDir;
  2887. y0 = y0 * s + y1 * tDir;
  2888. z0 = z0 * s + z1 * tDir;
  2889. w0 = w0 * s + w1 * tDir;
  2890. // Normalize in case we just did a lerp:
  2891. if ( s === 1 - t ) {
  2892. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2893. x0 *= f;
  2894. y0 *= f;
  2895. z0 *= f;
  2896. w0 *= f;
  2897. }
  2898. }
  2899. dst[ dstOffset ] = x0;
  2900. dst[ dstOffset + 1 ] = y0;
  2901. dst[ dstOffset + 2 ] = z0;
  2902. dst[ dstOffset + 3 ] = w0;
  2903. }
  2904. /**
  2905. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  2906. * in flat arrays.
  2907. *
  2908. * @param {Array<number>} dst - The destination array.
  2909. * @param {number} dstOffset - An offset into the destination array.
  2910. * @param {Array<number>} src0 - The source array of the first quaternion.
  2911. * @param {number} srcOffset0 - An offset into the first source array.
  2912. * @param {Array<number>} src1 - The source array of the second quaternion.
  2913. * @param {number} srcOffset1 - An offset into the second source array.
  2914. * @return {Array<number>} The destination array.
  2915. * @see {@link Quaternion#multiplyQuaternions}.
  2916. */
  2917. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2918. const x0 = src0[ srcOffset0 ];
  2919. const y0 = src0[ srcOffset0 + 1 ];
  2920. const z0 = src0[ srcOffset0 + 2 ];
  2921. const w0 = src0[ srcOffset0 + 3 ];
  2922. const x1 = src1[ srcOffset1 ];
  2923. const y1 = src1[ srcOffset1 + 1 ];
  2924. const z1 = src1[ srcOffset1 + 2 ];
  2925. const w1 = src1[ srcOffset1 + 3 ];
  2926. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2927. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2928. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2929. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2930. return dst;
  2931. }
  2932. /**
  2933. * The x value of this quaternion.
  2934. *
  2935. * @type {number}
  2936. * @default 0
  2937. */
  2938. get x() {
  2939. return this._x;
  2940. }
  2941. set x( value ) {
  2942. this._x = value;
  2943. this._onChangeCallback();
  2944. }
  2945. /**
  2946. * The y value of this quaternion.
  2947. *
  2948. * @type {number}
  2949. * @default 0
  2950. */
  2951. get y() {
  2952. return this._y;
  2953. }
  2954. set y( value ) {
  2955. this._y = value;
  2956. this._onChangeCallback();
  2957. }
  2958. /**
  2959. * The z value of this quaternion.
  2960. *
  2961. * @type {number}
  2962. * @default 0
  2963. */
  2964. get z() {
  2965. return this._z;
  2966. }
  2967. set z( value ) {
  2968. this._z = value;
  2969. this._onChangeCallback();
  2970. }
  2971. /**
  2972. * The w value of this quaternion.
  2973. *
  2974. * @type {number}
  2975. * @default 1
  2976. */
  2977. get w() {
  2978. return this._w;
  2979. }
  2980. set w( value ) {
  2981. this._w = value;
  2982. this._onChangeCallback();
  2983. }
  2984. /**
  2985. * Sets the quaternion components.
  2986. *
  2987. * @param {number} x - The x value of this quaternion.
  2988. * @param {number} y - The y value of this quaternion.
  2989. * @param {number} z - The z value of this quaternion.
  2990. * @param {number} w - The w value of this quaternion.
  2991. * @return {Quaternion} A reference to this quaternion.
  2992. */
  2993. set( x, y, z, w ) {
  2994. this._x = x;
  2995. this._y = y;
  2996. this._z = z;
  2997. this._w = w;
  2998. this._onChangeCallback();
  2999. return this;
  3000. }
  3001. /**
  3002. * Returns a new quaternion with copied values from this instance.
  3003. *
  3004. * @return {Quaternion} A clone of this instance.
  3005. */
  3006. clone() {
  3007. return new this.constructor( this._x, this._y, this._z, this._w );
  3008. }
  3009. /**
  3010. * Copies the values of the given quaternion to this instance.
  3011. *
  3012. * @param {Quaternion} quaternion - The quaternion to copy.
  3013. * @return {Quaternion} A reference to this quaternion.
  3014. */
  3015. copy( quaternion ) {
  3016. this._x = quaternion.x;
  3017. this._y = quaternion.y;
  3018. this._z = quaternion.z;
  3019. this._w = quaternion.w;
  3020. this._onChangeCallback();
  3021. return this;
  3022. }
  3023. /**
  3024. * Sets this quaternion from the rotation specified by the given
  3025. * Euler angles.
  3026. *
  3027. * @param {Euler} euler - The Euler angles.
  3028. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3029. * @return {Quaternion} A reference to this quaternion.
  3030. */
  3031. setFromEuler( euler, update = true ) {
  3032. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3033. // http://www.mathworks.com/matlabcentral/fileexchange/
  3034. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3035. // content/SpinCalc.m
  3036. const cos = Math.cos;
  3037. const sin = Math.sin;
  3038. const c1 = cos( x / 2 );
  3039. const c2 = cos( y / 2 );
  3040. const c3 = cos( z / 2 );
  3041. const s1 = sin( x / 2 );
  3042. const s2 = sin( y / 2 );
  3043. const s3 = sin( z / 2 );
  3044. switch ( order ) {
  3045. case 'XYZ':
  3046. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3047. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3048. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3049. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3050. break;
  3051. case 'YXZ':
  3052. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3053. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3054. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3055. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3056. break;
  3057. case 'ZXY':
  3058. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3059. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3060. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3061. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3062. break;
  3063. case 'ZYX':
  3064. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3065. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3066. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3067. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3068. break;
  3069. case 'YZX':
  3070. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3071. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3072. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3073. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3074. break;
  3075. case 'XZY':
  3076. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3077. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3078. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3079. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3080. break;
  3081. default:
  3082. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3083. }
  3084. if ( update === true ) this._onChangeCallback();
  3085. return this;
  3086. }
  3087. /**
  3088. * Sets this quaternion from the given axis and angle.
  3089. *
  3090. * @param {Vector3} axis - The normalized axis.
  3091. * @param {number} angle - The angle in radians.
  3092. * @return {Quaternion} A reference to this quaternion.
  3093. */
  3094. setFromAxisAngle( axis, angle ) {
  3095. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3096. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3097. this._x = axis.x * s;
  3098. this._y = axis.y * s;
  3099. this._z = axis.z * s;
  3100. this._w = Math.cos( halfAngle );
  3101. this._onChangeCallback();
  3102. return this;
  3103. }
  3104. /**
  3105. * Sets this quaternion from the given rotation matrix.
  3106. *
  3107. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3108. * @return {Quaternion} A reference to this quaternion.
  3109. */
  3110. setFromRotationMatrix( m ) {
  3111. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3112. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3113. const te = m.elements,
  3114. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3115. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3116. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3117. trace = m11 + m22 + m33;
  3118. if ( trace > 0 ) {
  3119. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3120. this._w = 0.25 / s;
  3121. this._x = ( m32 - m23 ) * s;
  3122. this._y = ( m13 - m31 ) * s;
  3123. this._z = ( m21 - m12 ) * s;
  3124. } else if ( m11 > m22 && m11 > m33 ) {
  3125. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3126. this._w = ( m32 - m23 ) / s;
  3127. this._x = 0.25 * s;
  3128. this._y = ( m12 + m21 ) / s;
  3129. this._z = ( m13 + m31 ) / s;
  3130. } else if ( m22 > m33 ) {
  3131. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3132. this._w = ( m13 - m31 ) / s;
  3133. this._x = ( m12 + m21 ) / s;
  3134. this._y = 0.25 * s;
  3135. this._z = ( m23 + m32 ) / s;
  3136. } else {
  3137. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3138. this._w = ( m21 - m12 ) / s;
  3139. this._x = ( m13 + m31 ) / s;
  3140. this._y = ( m23 + m32 ) / s;
  3141. this._z = 0.25 * s;
  3142. }
  3143. this._onChangeCallback();
  3144. return this;
  3145. }
  3146. /**
  3147. * Sets this quaternion to the rotation required to rotate the direction vector
  3148. * `vFrom` to the direction vector `vTo`.
  3149. *
  3150. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3151. * @param {Vector3} vTo - The second (normalized) direction vector.
  3152. * @return {Quaternion} A reference to this quaternion.
  3153. */
  3154. setFromUnitVectors( vFrom, vTo ) {
  3155. // assumes direction vectors vFrom and vTo are normalized
  3156. let r = vFrom.dot( vTo ) + 1;
  3157. if ( r < 1e-8 ) { // the epsilon value has been discussed in #31286
  3158. // vFrom and vTo point in opposite directions
  3159. r = 0;
  3160. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3161. this._x = - vFrom.y;
  3162. this._y = vFrom.x;
  3163. this._z = 0;
  3164. this._w = r;
  3165. } else {
  3166. this._x = 0;
  3167. this._y = - vFrom.z;
  3168. this._z = vFrom.y;
  3169. this._w = r;
  3170. }
  3171. } else {
  3172. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3173. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3174. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3175. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3176. this._w = r;
  3177. }
  3178. return this.normalize();
  3179. }
  3180. /**
  3181. * Returns the angle between this quaternion and the given one in radians.
  3182. *
  3183. * @param {Quaternion} q - The quaternion to compute the angle with.
  3184. * @return {number} The angle in radians.
  3185. */
  3186. angleTo( q ) {
  3187. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3188. }
  3189. /**
  3190. * Rotates this quaternion by a given angular step to the given quaternion.
  3191. * The method ensures that the final quaternion will not overshoot `q`.
  3192. *
  3193. * @param {Quaternion} q - The target quaternion.
  3194. * @param {number} step - The angular step in radians.
  3195. * @return {Quaternion} A reference to this quaternion.
  3196. */
  3197. rotateTowards( q, step ) {
  3198. const angle = this.angleTo( q );
  3199. if ( angle === 0 ) return this;
  3200. const t = Math.min( 1, step / angle );
  3201. this.slerp( q, t );
  3202. return this;
  3203. }
  3204. /**
  3205. * Sets this quaternion to the identity quaternion; that is, to the
  3206. * quaternion that represents "no rotation".
  3207. *
  3208. * @return {Quaternion} A reference to this quaternion.
  3209. */
  3210. identity() {
  3211. return this.set( 0, 0, 0, 1 );
  3212. }
  3213. /**
  3214. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  3215. * quaternion is assumed to have unit length.
  3216. *
  3217. * @return {Quaternion} A reference to this quaternion.
  3218. */
  3219. invert() {
  3220. return this.conjugate();
  3221. }
  3222. /**
  3223. * Returns the rotational conjugate of this quaternion. The conjugate of a
  3224. * quaternion represents the same rotation in the opposite direction about
  3225. * the rotational axis.
  3226. *
  3227. * @return {Quaternion} A reference to this quaternion.
  3228. */
  3229. conjugate() {
  3230. this._x *= -1;
  3231. this._y *= -1;
  3232. this._z *= -1;
  3233. this._onChangeCallback();
  3234. return this;
  3235. }
  3236. /**
  3237. * Calculates the dot product of this quaternion and the given one.
  3238. *
  3239. * @param {Quaternion} v - The quaternion to compute the dot product with.
  3240. * @return {number} The result of the dot product.
  3241. */
  3242. dot( v ) {
  3243. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  3244. }
  3245. /**
  3246. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  3247. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  3248. * lengths of two quaternions, as this is a slightly more efficient calculation than
  3249. * {@link Quaternion#length}.
  3250. *
  3251. * @return {number} The squared Euclidean length.
  3252. */
  3253. lengthSq() {
  3254. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  3255. }
  3256. /**
  3257. * Computes the Euclidean length (straight-line length) of this quaternion,
  3258. * considered as a 4 dimensional vector.
  3259. *
  3260. * @return {number} The Euclidean length.
  3261. */
  3262. length() {
  3263. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  3264. }
  3265. /**
  3266. * Normalizes this quaternion - that is, calculated the quaternion that performs
  3267. * the same rotation as this one, but has a length equal to `1`.
  3268. *
  3269. * @return {Quaternion} A reference to this quaternion.
  3270. */
  3271. normalize() {
  3272. let l = this.length();
  3273. if ( l === 0 ) {
  3274. this._x = 0;
  3275. this._y = 0;
  3276. this._z = 0;
  3277. this._w = 1;
  3278. } else {
  3279. l = 1 / l;
  3280. this._x = this._x * l;
  3281. this._y = this._y * l;
  3282. this._z = this._z * l;
  3283. this._w = this._w * l;
  3284. }
  3285. this._onChangeCallback();
  3286. return this;
  3287. }
  3288. /**
  3289. * Multiplies this quaternion by the given one.
  3290. *
  3291. * @param {Quaternion} q - The quaternion.
  3292. * @return {Quaternion} A reference to this quaternion.
  3293. */
  3294. multiply( q ) {
  3295. return this.multiplyQuaternions( this, q );
  3296. }
  3297. /**
  3298. * Pre-multiplies this quaternion by the given one.
  3299. *
  3300. * @param {Quaternion} q - The quaternion.
  3301. * @return {Quaternion} A reference to this quaternion.
  3302. */
  3303. premultiply( q ) {
  3304. return this.multiplyQuaternions( q, this );
  3305. }
  3306. /**
  3307. * Multiplies the given quaternions and stores the result in this instance.
  3308. *
  3309. * @param {Quaternion} a - The first quaternion.
  3310. * @param {Quaternion} b - The second quaternion.
  3311. * @return {Quaternion} A reference to this quaternion.
  3312. */
  3313. multiplyQuaternions( a, b ) {
  3314. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3315. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  3316. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  3317. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3318. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3319. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3320. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3321. this._onChangeCallback();
  3322. return this;
  3323. }
  3324. /**
  3325. * Performs a spherical linear interpolation between quaternions.
  3326. *
  3327. * @param {Quaternion} qb - The target quaternion.
  3328. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3329. * @return {Quaternion} A reference to this quaternion.
  3330. */
  3331. slerp( qb, t ) {
  3332. if ( t === 0 ) return this;
  3333. if ( t === 1 ) return this.copy( qb );
  3334. const x = this._x, y = this._y, z = this._z, w = this._w;
  3335. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  3336. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  3337. if ( cosHalfTheta < 0 ) {
  3338. this._w = - qb._w;
  3339. this._x = - qb._x;
  3340. this._y = - qb._y;
  3341. this._z = - qb._z;
  3342. cosHalfTheta = - cosHalfTheta;
  3343. } else {
  3344. this.copy( qb );
  3345. }
  3346. if ( cosHalfTheta >= 1.0 ) {
  3347. this._w = w;
  3348. this._x = x;
  3349. this._y = y;
  3350. this._z = z;
  3351. return this;
  3352. }
  3353. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  3354. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  3355. const s = 1 - t;
  3356. this._w = s * w + t * this._w;
  3357. this._x = s * x + t * this._x;
  3358. this._y = s * y + t * this._y;
  3359. this._z = s * z + t * this._z;
  3360. this.normalize(); // normalize calls _onChangeCallback()
  3361. return this;
  3362. }
  3363. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  3364. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  3365. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  3366. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  3367. this._w = ( w * ratioA + this._w * ratioB );
  3368. this._x = ( x * ratioA + this._x * ratioB );
  3369. this._y = ( y * ratioA + this._y * ratioB );
  3370. this._z = ( z * ratioA + this._z * ratioB );
  3371. this._onChangeCallback();
  3372. return this;
  3373. }
  3374. /**
  3375. * Performs a spherical linear interpolation between the given quaternions
  3376. * and stores the result in this quaternion.
  3377. *
  3378. * @param {Quaternion} qa - The source quaternion.
  3379. * @param {Quaternion} qb - The target quaternion.
  3380. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3381. * @return {Quaternion} A reference to this quaternion.
  3382. */
  3383. slerpQuaternions( qa, qb, t ) {
  3384. return this.copy( qa ).slerp( qb, t );
  3385. }
  3386. /**
  3387. * Sets this quaternion to a uniformly random, normalized quaternion.
  3388. *
  3389. * @return {Quaternion} A reference to this quaternion.
  3390. */
  3391. random() {
  3392. // Ken Shoemake
  3393. // Uniform random rotations
  3394. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  3395. const theta1 = 2 * Math.PI * Math.random();
  3396. const theta2 = 2 * Math.PI * Math.random();
  3397. const x0 = Math.random();
  3398. const r1 = Math.sqrt( 1 - x0 );
  3399. const r2 = Math.sqrt( x0 );
  3400. return this.set(
  3401. r1 * Math.sin( theta1 ),
  3402. r1 * Math.cos( theta1 ),
  3403. r2 * Math.sin( theta2 ),
  3404. r2 * Math.cos( theta2 ),
  3405. );
  3406. }
  3407. /**
  3408. * Returns `true` if this quaternion is equal with the given one.
  3409. *
  3410. * @param {Quaternion} quaternion - The quaternion to test for equality.
  3411. * @return {boolean} Whether this quaternion is equal with the given one.
  3412. */
  3413. equals( quaternion ) {
  3414. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  3415. }
  3416. /**
  3417. * Sets this quaternion's components from the given array.
  3418. *
  3419. * @param {Array<number>} array - An array holding the quaternion component values.
  3420. * @param {number} [offset=0] - The offset into the array.
  3421. * @return {Quaternion} A reference to this quaternion.
  3422. */
  3423. fromArray( array, offset = 0 ) {
  3424. this._x = array[ offset ];
  3425. this._y = array[ offset + 1 ];
  3426. this._z = array[ offset + 2 ];
  3427. this._w = array[ offset + 3 ];
  3428. this._onChangeCallback();
  3429. return this;
  3430. }
  3431. /**
  3432. * Writes the components of this quaternion to the given array. If no array is provided,
  3433. * the method returns a new instance.
  3434. *
  3435. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  3436. * @param {number} [offset=0] - Index of the first element in the array.
  3437. * @return {Array<number>} The quaternion components.
  3438. */
  3439. toArray( array = [], offset = 0 ) {
  3440. array[ offset ] = this._x;
  3441. array[ offset + 1 ] = this._y;
  3442. array[ offset + 2 ] = this._z;
  3443. array[ offset + 3 ] = this._w;
  3444. return array;
  3445. }
  3446. /**
  3447. * Sets the components of this quaternion from the given buffer attribute.
  3448. *
  3449. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  3450. * @param {number} index - The index into the attribute.
  3451. * @return {Quaternion} A reference to this quaternion.
  3452. */
  3453. fromBufferAttribute( attribute, index ) {
  3454. this._x = attribute.getX( index );
  3455. this._y = attribute.getY( index );
  3456. this._z = attribute.getZ( index );
  3457. this._w = attribute.getW( index );
  3458. this._onChangeCallback();
  3459. return this;
  3460. }
  3461. /**
  3462. * This methods defines the serialization result of this class. Returns the
  3463. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  3464. *
  3465. * @return {Array<number>} The serialized quaternion.
  3466. */
  3467. toJSON() {
  3468. return this.toArray();
  3469. }
  3470. _onChange( callback ) {
  3471. this._onChangeCallback = callback;
  3472. return this;
  3473. }
  3474. _onChangeCallback() {}
  3475. *[ Symbol.iterator ]() {
  3476. yield this._x;
  3477. yield this._y;
  3478. yield this._z;
  3479. yield this._w;
  3480. }
  3481. }
  3482. /**
  3483. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  3484. * (labeled x, y and z), which can be used to represent a number of things, such as:
  3485. *
  3486. * - A point in 3D space.
  3487. * - A direction and length in 3D space. In three.js the length will
  3488. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  3489. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  3490. * - Any arbitrary ordered triplet of numbers.
  3491. *
  3492. * There are other things a 3D vector can be used to represent, such as
  3493. * momentum vectors and so on, however these are the most
  3494. * common uses in three.js.
  3495. *
  3496. * Iterating through a vector instance will yield its components `(x, y, z)` in
  3497. * the corresponding order.
  3498. * ```js
  3499. * const a = new THREE.Vector3( 0, 1, 0 );
  3500. *
  3501. * //no arguments; will be initialised to (0, 0, 0)
  3502. * const b = new THREE.Vector3( );
  3503. *
  3504. * const d = a.distanceTo( b );
  3505. * ```
  3506. */
  3507. class Vector3 {
  3508. /**
  3509. * Constructs a new 3D vector.
  3510. *
  3511. * @param {number} [x=0] - The x value of this vector.
  3512. * @param {number} [y=0] - The y value of this vector.
  3513. * @param {number} [z=0] - The z value of this vector.
  3514. */
  3515. constructor( x = 0, y = 0, z = 0 ) {
  3516. /**
  3517. * This flag can be used for type testing.
  3518. *
  3519. * @type {boolean}
  3520. * @readonly
  3521. * @default true
  3522. */
  3523. Vector3.prototype.isVector3 = true;
  3524. /**
  3525. * The x value of this vector.
  3526. *
  3527. * @type {number}
  3528. */
  3529. this.x = x;
  3530. /**
  3531. * The y value of this vector.
  3532. *
  3533. * @type {number}
  3534. */
  3535. this.y = y;
  3536. /**
  3537. * The z value of this vector.
  3538. *
  3539. * @type {number}
  3540. */
  3541. this.z = z;
  3542. }
  3543. /**
  3544. * Sets the vector components.
  3545. *
  3546. * @param {number} x - The value of the x component.
  3547. * @param {number} y - The value of the y component.
  3548. * @param {number} z - The value of the z component.
  3549. * @return {Vector3} A reference to this vector.
  3550. */
  3551. set( x, y, z ) {
  3552. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  3553. this.x = x;
  3554. this.y = y;
  3555. this.z = z;
  3556. return this;
  3557. }
  3558. /**
  3559. * Sets the vector components to the same value.
  3560. *
  3561. * @param {number} scalar - The value to set for all vector components.
  3562. * @return {Vector3} A reference to this vector.
  3563. */
  3564. setScalar( scalar ) {
  3565. this.x = scalar;
  3566. this.y = scalar;
  3567. this.z = scalar;
  3568. return this;
  3569. }
  3570. /**
  3571. * Sets the vector's x component to the given value
  3572. *
  3573. * @param {number} x - The value to set.
  3574. * @return {Vector3} A reference to this vector.
  3575. */
  3576. setX( x ) {
  3577. this.x = x;
  3578. return this;
  3579. }
  3580. /**
  3581. * Sets the vector's y component to the given value
  3582. *
  3583. * @param {number} y - The value to set.
  3584. * @return {Vector3} A reference to this vector.
  3585. */
  3586. setY( y ) {
  3587. this.y = y;
  3588. return this;
  3589. }
  3590. /**
  3591. * Sets the vector's z component to the given value
  3592. *
  3593. * @param {number} z - The value to set.
  3594. * @return {Vector3} A reference to this vector.
  3595. */
  3596. setZ( z ) {
  3597. this.z = z;
  3598. return this;
  3599. }
  3600. /**
  3601. * Allows to set a vector component with an index.
  3602. *
  3603. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3604. * @param {number} value - The value to set.
  3605. * @return {Vector3} A reference to this vector.
  3606. */
  3607. setComponent( index, value ) {
  3608. switch ( index ) {
  3609. case 0: this.x = value; break;
  3610. case 1: this.y = value; break;
  3611. case 2: this.z = value; break;
  3612. default: throw new Error( 'index is out of range: ' + index );
  3613. }
  3614. return this;
  3615. }
  3616. /**
  3617. * Returns the value of the vector component which matches the given index.
  3618. *
  3619. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3620. * @return {number} A vector component value.
  3621. */
  3622. getComponent( index ) {
  3623. switch ( index ) {
  3624. case 0: return this.x;
  3625. case 1: return this.y;
  3626. case 2: return this.z;
  3627. default: throw new Error( 'index is out of range: ' + index );
  3628. }
  3629. }
  3630. /**
  3631. * Returns a new vector with copied values from this instance.
  3632. *
  3633. * @return {Vector3} A clone of this instance.
  3634. */
  3635. clone() {
  3636. return new this.constructor( this.x, this.y, this.z );
  3637. }
  3638. /**
  3639. * Copies the values of the given vector to this instance.
  3640. *
  3641. * @param {Vector3} v - The vector to copy.
  3642. * @return {Vector3} A reference to this vector.
  3643. */
  3644. copy( v ) {
  3645. this.x = v.x;
  3646. this.y = v.y;
  3647. this.z = v.z;
  3648. return this;
  3649. }
  3650. /**
  3651. * Adds the given vector to this instance.
  3652. *
  3653. * @param {Vector3} v - The vector to add.
  3654. * @return {Vector3} A reference to this vector.
  3655. */
  3656. add( v ) {
  3657. this.x += v.x;
  3658. this.y += v.y;
  3659. this.z += v.z;
  3660. return this;
  3661. }
  3662. /**
  3663. * Adds the given scalar value to all components of this instance.
  3664. *
  3665. * @param {number} s - The scalar to add.
  3666. * @return {Vector3} A reference to this vector.
  3667. */
  3668. addScalar( s ) {
  3669. this.x += s;
  3670. this.y += s;
  3671. this.z += s;
  3672. return this;
  3673. }
  3674. /**
  3675. * Adds the given vectors and stores the result in this instance.
  3676. *
  3677. * @param {Vector3} a - The first vector.
  3678. * @param {Vector3} b - The second vector.
  3679. * @return {Vector3} A reference to this vector.
  3680. */
  3681. addVectors( a, b ) {
  3682. this.x = a.x + b.x;
  3683. this.y = a.y + b.y;
  3684. this.z = a.z + b.z;
  3685. return this;
  3686. }
  3687. /**
  3688. * Adds the given vector scaled by the given factor to this instance.
  3689. *
  3690. * @param {Vector3|Vector4} v - The vector.
  3691. * @param {number} s - The factor that scales `v`.
  3692. * @return {Vector3} A reference to this vector.
  3693. */
  3694. addScaledVector( v, s ) {
  3695. this.x += v.x * s;
  3696. this.y += v.y * s;
  3697. this.z += v.z * s;
  3698. return this;
  3699. }
  3700. /**
  3701. * Subtracts the given vector from this instance.
  3702. *
  3703. * @param {Vector3} v - The vector to subtract.
  3704. * @return {Vector3} A reference to this vector.
  3705. */
  3706. sub( v ) {
  3707. this.x -= v.x;
  3708. this.y -= v.y;
  3709. this.z -= v.z;
  3710. return this;
  3711. }
  3712. /**
  3713. * Subtracts the given scalar value from all components of this instance.
  3714. *
  3715. * @param {number} s - The scalar to subtract.
  3716. * @return {Vector3} A reference to this vector.
  3717. */
  3718. subScalar( s ) {
  3719. this.x -= s;
  3720. this.y -= s;
  3721. this.z -= s;
  3722. return this;
  3723. }
  3724. /**
  3725. * Subtracts the given vectors and stores the result in this instance.
  3726. *
  3727. * @param {Vector3} a - The first vector.
  3728. * @param {Vector3} b - The second vector.
  3729. * @return {Vector3} A reference to this vector.
  3730. */
  3731. subVectors( a, b ) {
  3732. this.x = a.x - b.x;
  3733. this.y = a.y - b.y;
  3734. this.z = a.z - b.z;
  3735. return this;
  3736. }
  3737. /**
  3738. * Multiplies the given vector with this instance.
  3739. *
  3740. * @param {Vector3} v - The vector to multiply.
  3741. * @return {Vector3} A reference to this vector.
  3742. */
  3743. multiply( v ) {
  3744. this.x *= v.x;
  3745. this.y *= v.y;
  3746. this.z *= v.z;
  3747. return this;
  3748. }
  3749. /**
  3750. * Multiplies the given scalar value with all components of this instance.
  3751. *
  3752. * @param {number} scalar - The scalar to multiply.
  3753. * @return {Vector3} A reference to this vector.
  3754. */
  3755. multiplyScalar( scalar ) {
  3756. this.x *= scalar;
  3757. this.y *= scalar;
  3758. this.z *= scalar;
  3759. return this;
  3760. }
  3761. /**
  3762. * Multiplies the given vectors and stores the result in this instance.
  3763. *
  3764. * @param {Vector3} a - The first vector.
  3765. * @param {Vector3} b - The second vector.
  3766. * @return {Vector3} A reference to this vector.
  3767. */
  3768. multiplyVectors( a, b ) {
  3769. this.x = a.x * b.x;
  3770. this.y = a.y * b.y;
  3771. this.z = a.z * b.z;
  3772. return this;
  3773. }
  3774. /**
  3775. * Applies the given Euler rotation to this vector.
  3776. *
  3777. * @param {Euler} euler - The Euler angles.
  3778. * @return {Vector3} A reference to this vector.
  3779. */
  3780. applyEuler( euler ) {
  3781. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  3782. }
  3783. /**
  3784. * Applies a rotation specified by an axis and an angle to this vector.
  3785. *
  3786. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  3787. * @param {number} angle - The angle in radians.
  3788. * @return {Vector3} A reference to this vector.
  3789. */
  3790. applyAxisAngle( axis, angle ) {
  3791. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  3792. }
  3793. /**
  3794. * Multiplies this vector with the given 3x3 matrix.
  3795. *
  3796. * @param {Matrix3} m - The 3x3 matrix.
  3797. * @return {Vector3} A reference to this vector.
  3798. */
  3799. applyMatrix3( m ) {
  3800. const x = this.x, y = this.y, z = this.z;
  3801. const e = m.elements;
  3802. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  3803. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  3804. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  3805. return this;
  3806. }
  3807. /**
  3808. * Multiplies this vector by the given normal matrix and normalizes
  3809. * the result.
  3810. *
  3811. * @param {Matrix3} m - The normal matrix.
  3812. * @return {Vector3} A reference to this vector.
  3813. */
  3814. applyNormalMatrix( m ) {
  3815. return this.applyMatrix3( m ).normalize();
  3816. }
  3817. /**
  3818. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  3819. * divides by perspective.
  3820. *
  3821. * @param {Matrix4} m - The matrix to apply.
  3822. * @return {Vector3} A reference to this vector.
  3823. */
  3824. applyMatrix4( m ) {
  3825. const x = this.x, y = this.y, z = this.z;
  3826. const e = m.elements;
  3827. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  3828. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  3829. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  3830. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  3831. return this;
  3832. }
  3833. /**
  3834. * Applies the given Quaternion to this vector.
  3835. *
  3836. * @param {Quaternion} q - The Quaternion.
  3837. * @return {Vector3} A reference to this vector.
  3838. */
  3839. applyQuaternion( q ) {
  3840. // quaternion q is assumed to have unit length
  3841. const vx = this.x, vy = this.y, vz = this.z;
  3842. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  3843. // t = 2 * cross( q.xyz, v );
  3844. const tx = 2 * ( qy * vz - qz * vy );
  3845. const ty = 2 * ( qz * vx - qx * vz );
  3846. const tz = 2 * ( qx * vy - qy * vx );
  3847. // v + q.w * t + cross( q.xyz, t );
  3848. this.x = vx + qw * tx + qy * tz - qz * ty;
  3849. this.y = vy + qw * ty + qz * tx - qx * tz;
  3850. this.z = vz + qw * tz + qx * ty - qy * tx;
  3851. return this;
  3852. }
  3853. /**
  3854. * Projects this vector from world space into the camera's normalized
  3855. * device coordinate (NDC) space.
  3856. *
  3857. * @param {Camera} camera - The camera.
  3858. * @return {Vector3} A reference to this vector.
  3859. */
  3860. project( camera ) {
  3861. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  3862. }
  3863. /**
  3864. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  3865. * space into world space.
  3866. *
  3867. * @param {Camera} camera - The camera.
  3868. * @return {Vector3} A reference to this vector.
  3869. */
  3870. unproject( camera ) {
  3871. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  3872. }
  3873. /**
  3874. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  3875. * subset of the given 4x4 matrix and then normalizes the result.
  3876. *
  3877. * @param {Matrix4} m - The matrix.
  3878. * @return {Vector3} A reference to this vector.
  3879. */
  3880. transformDirection( m ) {
  3881. // input: THREE.Matrix4 affine matrix
  3882. // vector interpreted as a direction
  3883. const x = this.x, y = this.y, z = this.z;
  3884. const e = m.elements;
  3885. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  3886. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  3887. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  3888. return this.normalize();
  3889. }
  3890. /**
  3891. * Divides this instance by the given vector.
  3892. *
  3893. * @param {Vector3} v - The vector to divide.
  3894. * @return {Vector3} A reference to this vector.
  3895. */
  3896. divide( v ) {
  3897. this.x /= v.x;
  3898. this.y /= v.y;
  3899. this.z /= v.z;
  3900. return this;
  3901. }
  3902. /**
  3903. * Divides this vector by the given scalar.
  3904. *
  3905. * @param {number} scalar - The scalar to divide.
  3906. * @return {Vector3} A reference to this vector.
  3907. */
  3908. divideScalar( scalar ) {
  3909. return this.multiplyScalar( 1 / scalar );
  3910. }
  3911. /**
  3912. * If this vector's x, y or z value is greater than the given vector's x, y or z
  3913. * value, replace that value with the corresponding min value.
  3914. *
  3915. * @param {Vector3} v - The vector.
  3916. * @return {Vector3} A reference to this vector.
  3917. */
  3918. min( v ) {
  3919. this.x = Math.min( this.x, v.x );
  3920. this.y = Math.min( this.y, v.y );
  3921. this.z = Math.min( this.z, v.z );
  3922. return this;
  3923. }
  3924. /**
  3925. * If this vector's x, y or z value is less than the given vector's x, y or z
  3926. * value, replace that value with the corresponding max value.
  3927. *
  3928. * @param {Vector3} v - The vector.
  3929. * @return {Vector3} A reference to this vector.
  3930. */
  3931. max( v ) {
  3932. this.x = Math.max( this.x, v.x );
  3933. this.y = Math.max( this.y, v.y );
  3934. this.z = Math.max( this.z, v.z );
  3935. return this;
  3936. }
  3937. /**
  3938. * If this vector's x, y or z value is greater than the max vector's x, y or z
  3939. * value, it is replaced by the corresponding value.
  3940. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  3941. * it is replaced by the corresponding value.
  3942. *
  3943. * @param {Vector3} min - The minimum x, y and z values.
  3944. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  3945. * @return {Vector3} A reference to this vector.
  3946. */
  3947. clamp( min, max ) {
  3948. // assumes min < max, componentwise
  3949. this.x = clamp( this.x, min.x, max.x );
  3950. this.y = clamp( this.y, min.y, max.y );
  3951. this.z = clamp( this.z, min.z, max.z );
  3952. return this;
  3953. }
  3954. /**
  3955. * If this vector's x, y or z values are greater than the max value, they are
  3956. * replaced by the max value.
  3957. * If this vector's x, y or z values are less than the min value, they are
  3958. * replaced by the min value.
  3959. *
  3960. * @param {number} minVal - The minimum value the components will be clamped to.
  3961. * @param {number} maxVal - The maximum value the components will be clamped to.
  3962. * @return {Vector3} A reference to this vector.
  3963. */
  3964. clampScalar( minVal, maxVal ) {
  3965. this.x = clamp( this.x, minVal, maxVal );
  3966. this.y = clamp( this.y, minVal, maxVal );
  3967. this.z = clamp( this.z, minVal, maxVal );
  3968. return this;
  3969. }
  3970. /**
  3971. * If this vector's length is greater than the max value, it is replaced by
  3972. * the max value.
  3973. * If this vector's length is less than the min value, it is replaced by the
  3974. * min value.
  3975. *
  3976. * @param {number} min - The minimum value the vector length will be clamped to.
  3977. * @param {number} max - The maximum value the vector length will be clamped to.
  3978. * @return {Vector3} A reference to this vector.
  3979. */
  3980. clampLength( min, max ) {
  3981. const length = this.length();
  3982. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  3983. }
  3984. /**
  3985. * The components of this vector are rounded down to the nearest integer value.
  3986. *
  3987. * @return {Vector3} A reference to this vector.
  3988. */
  3989. floor() {
  3990. this.x = Math.floor( this.x );
  3991. this.y = Math.floor( this.y );
  3992. this.z = Math.floor( this.z );
  3993. return this;
  3994. }
  3995. /**
  3996. * The components of this vector are rounded up to the nearest integer value.
  3997. *
  3998. * @return {Vector3} A reference to this vector.
  3999. */
  4000. ceil() {
  4001. this.x = Math.ceil( this.x );
  4002. this.y = Math.ceil( this.y );
  4003. this.z = Math.ceil( this.z );
  4004. return this;
  4005. }
  4006. /**
  4007. * The components of this vector are rounded to the nearest integer value
  4008. *
  4009. * @return {Vector3} A reference to this vector.
  4010. */
  4011. round() {
  4012. this.x = Math.round( this.x );
  4013. this.y = Math.round( this.y );
  4014. this.z = Math.round( this.z );
  4015. return this;
  4016. }
  4017. /**
  4018. * The components of this vector are rounded towards zero (up if negative,
  4019. * down if positive) to an integer value.
  4020. *
  4021. * @return {Vector3} A reference to this vector.
  4022. */
  4023. roundToZero() {
  4024. this.x = Math.trunc( this.x );
  4025. this.y = Math.trunc( this.y );
  4026. this.z = Math.trunc( this.z );
  4027. return this;
  4028. }
  4029. /**
  4030. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4031. *
  4032. * @return {Vector3} A reference to this vector.
  4033. */
  4034. negate() {
  4035. this.x = - this.x;
  4036. this.y = - this.y;
  4037. this.z = - this.z;
  4038. return this;
  4039. }
  4040. /**
  4041. * Calculates the dot product of the given vector with this instance.
  4042. *
  4043. * @param {Vector3} v - The vector to compute the dot product with.
  4044. * @return {number} The result of the dot product.
  4045. */
  4046. dot( v ) {
  4047. return this.x * v.x + this.y * v.y + this.z * v.z;
  4048. }
  4049. // TODO lengthSquared?
  4050. /**
  4051. * Computes the square of the Euclidean length (straight-line length) from
  4052. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4053. * compare the length squared instead as it is slightly more efficient to calculate.
  4054. *
  4055. * @return {number} The square length of this vector.
  4056. */
  4057. lengthSq() {
  4058. return this.x * this.x + this.y * this.y + this.z * this.z;
  4059. }
  4060. /**
  4061. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4062. *
  4063. * @return {number} The length of this vector.
  4064. */
  4065. length() {
  4066. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4067. }
  4068. /**
  4069. * Computes the Manhattan length of this vector.
  4070. *
  4071. * @return {number} The length of this vector.
  4072. */
  4073. manhattanLength() {
  4074. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4075. }
  4076. /**
  4077. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4078. * with the same direction as this one, but with a vector length of `1`.
  4079. *
  4080. * @return {Vector3} A reference to this vector.
  4081. */
  4082. normalize() {
  4083. return this.divideScalar( this.length() || 1 );
  4084. }
  4085. /**
  4086. * Sets this vector to a vector with the same direction as this one, but
  4087. * with the specified length.
  4088. *
  4089. * @param {number} length - The new length of this vector.
  4090. * @return {Vector3} A reference to this vector.
  4091. */
  4092. setLength( length ) {
  4093. return this.normalize().multiplyScalar( length );
  4094. }
  4095. /**
  4096. * Linearly interpolates between the given vector and this instance, where
  4097. * alpha is the percent distance along the line - alpha = 0 will be this
  4098. * vector, and alpha = 1 will be the given one.
  4099. *
  4100. * @param {Vector3} v - The vector to interpolate towards.
  4101. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4102. * @return {Vector3} A reference to this vector.
  4103. */
  4104. lerp( v, alpha ) {
  4105. this.x += ( v.x - this.x ) * alpha;
  4106. this.y += ( v.y - this.y ) * alpha;
  4107. this.z += ( v.z - this.z ) * alpha;
  4108. return this;
  4109. }
  4110. /**
  4111. * Linearly interpolates between the given vectors, where alpha is the percent
  4112. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4113. * be the second one. The result is stored in this instance.
  4114. *
  4115. * @param {Vector3} v1 - The first vector.
  4116. * @param {Vector3} v2 - The second vector.
  4117. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4118. * @return {Vector3} A reference to this vector.
  4119. */
  4120. lerpVectors( v1, v2, alpha ) {
  4121. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4122. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4123. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4124. return this;
  4125. }
  4126. /**
  4127. * Calculates the cross product of the given vector with this instance.
  4128. *
  4129. * @param {Vector3} v - The vector to compute the cross product with.
  4130. * @return {Vector3} The result of the cross product.
  4131. */
  4132. cross( v ) {
  4133. return this.crossVectors( this, v );
  4134. }
  4135. /**
  4136. * Calculates the cross product of the given vectors and stores the result
  4137. * in this instance.
  4138. *
  4139. * @param {Vector3} a - The first vector.
  4140. * @param {Vector3} b - The second vector.
  4141. * @return {Vector3} A reference to this vector.
  4142. */
  4143. crossVectors( a, b ) {
  4144. const ax = a.x, ay = a.y, az = a.z;
  4145. const bx = b.x, by = b.y, bz = b.z;
  4146. this.x = ay * bz - az * by;
  4147. this.y = az * bx - ax * bz;
  4148. this.z = ax * by - ay * bx;
  4149. return this;
  4150. }
  4151. /**
  4152. * Projects this vector onto the given one.
  4153. *
  4154. * @param {Vector3} v - The vector to project to.
  4155. * @return {Vector3} A reference to this vector.
  4156. */
  4157. projectOnVector( v ) {
  4158. const denominator = v.lengthSq();
  4159. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4160. const scalar = v.dot( this ) / denominator;
  4161. return this.copy( v ).multiplyScalar( scalar );
  4162. }
  4163. /**
  4164. * Projects this vector onto a plane by subtracting this
  4165. * vector projected onto the plane's normal from this vector.
  4166. *
  4167. * @param {Vector3} planeNormal - The plane normal.
  4168. * @return {Vector3} A reference to this vector.
  4169. */
  4170. projectOnPlane( planeNormal ) {
  4171. _vector$c.copy( this ).projectOnVector( planeNormal );
  4172. return this.sub( _vector$c );
  4173. }
  4174. /**
  4175. * Reflects this vector off a plane orthogonal to the given normal vector.
  4176. *
  4177. * @param {Vector3} normal - The (normalized) normal vector.
  4178. * @return {Vector3} A reference to this vector.
  4179. */
  4180. reflect( normal ) {
  4181. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4182. }
  4183. /**
  4184. * Returns the angle between the given vector and this instance in radians.
  4185. *
  4186. * @param {Vector3} v - The vector to compute the angle with.
  4187. * @return {number} The angle in radians.
  4188. */
  4189. angleTo( v ) {
  4190. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4191. if ( denominator === 0 ) return Math.PI / 2;
  4192. const theta = this.dot( v ) / denominator;
  4193. // clamp, to handle numerical problems
  4194. return Math.acos( clamp( theta, -1, 1 ) );
  4195. }
  4196. /**
  4197. * Computes the distance from the given vector to this instance.
  4198. *
  4199. * @param {Vector3} v - The vector to compute the distance to.
  4200. * @return {number} The distance.
  4201. */
  4202. distanceTo( v ) {
  4203. return Math.sqrt( this.distanceToSquared( v ) );
  4204. }
  4205. /**
  4206. * Computes the squared distance from the given vector to this instance.
  4207. * If you are just comparing the distance with another distance, you should compare
  4208. * the distance squared instead as it is slightly more efficient to calculate.
  4209. *
  4210. * @param {Vector3} v - The vector to compute the squared distance to.
  4211. * @return {number} The squared distance.
  4212. */
  4213. distanceToSquared( v ) {
  4214. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  4215. return dx * dx + dy * dy + dz * dz;
  4216. }
  4217. /**
  4218. * Computes the Manhattan distance from the given vector to this instance.
  4219. *
  4220. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  4221. * @return {number} The Manhattan distance.
  4222. */
  4223. manhattanDistanceTo( v ) {
  4224. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  4225. }
  4226. /**
  4227. * Sets the vector components from the given spherical coordinates.
  4228. *
  4229. * @param {Spherical} s - The spherical coordinates.
  4230. * @return {Vector3} A reference to this vector.
  4231. */
  4232. setFromSpherical( s ) {
  4233. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  4234. }
  4235. /**
  4236. * Sets the vector components from the given spherical coordinates.
  4237. *
  4238. * @param {number} radius - The radius.
  4239. * @param {number} phi - The phi angle in radians.
  4240. * @param {number} theta - The theta angle in radians.
  4241. * @return {Vector3} A reference to this vector.
  4242. */
  4243. setFromSphericalCoords( radius, phi, theta ) {
  4244. const sinPhiRadius = Math.sin( phi ) * radius;
  4245. this.x = sinPhiRadius * Math.sin( theta );
  4246. this.y = Math.cos( phi ) * radius;
  4247. this.z = sinPhiRadius * Math.cos( theta );
  4248. return this;
  4249. }
  4250. /**
  4251. * Sets the vector components from the given cylindrical coordinates.
  4252. *
  4253. * @param {Cylindrical} c - The cylindrical coordinates.
  4254. * @return {Vector3} A reference to this vector.
  4255. */
  4256. setFromCylindrical( c ) {
  4257. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  4258. }
  4259. /**
  4260. * Sets the vector components from the given cylindrical coordinates.
  4261. *
  4262. * @param {number} radius - The radius.
  4263. * @param {number} theta - The theta angle in radians.
  4264. * @param {number} y - The y value.
  4265. * @return {Vector3} A reference to this vector.
  4266. */
  4267. setFromCylindricalCoords( radius, theta, y ) {
  4268. this.x = radius * Math.sin( theta );
  4269. this.y = y;
  4270. this.z = radius * Math.cos( theta );
  4271. return this;
  4272. }
  4273. /**
  4274. * Sets the vector components to the position elements of the
  4275. * given transformation matrix.
  4276. *
  4277. * @param {Matrix4} m - The 4x4 matrix.
  4278. * @return {Vector3} A reference to this vector.
  4279. */
  4280. setFromMatrixPosition( m ) {
  4281. const e = m.elements;
  4282. this.x = e[ 12 ];
  4283. this.y = e[ 13 ];
  4284. this.z = e[ 14 ];
  4285. return this;
  4286. }
  4287. /**
  4288. * Sets the vector components to the scale elements of the
  4289. * given transformation matrix.
  4290. *
  4291. * @param {Matrix4} m - The 4x4 matrix.
  4292. * @return {Vector3} A reference to this vector.
  4293. */
  4294. setFromMatrixScale( m ) {
  4295. const sx = this.setFromMatrixColumn( m, 0 ).length();
  4296. const sy = this.setFromMatrixColumn( m, 1 ).length();
  4297. const sz = this.setFromMatrixColumn( m, 2 ).length();
  4298. this.x = sx;
  4299. this.y = sy;
  4300. this.z = sz;
  4301. return this;
  4302. }
  4303. /**
  4304. * Sets the vector components from the specified matrix column.
  4305. *
  4306. * @param {Matrix4} m - The 4x4 matrix.
  4307. * @param {number} index - The column index.
  4308. * @return {Vector3} A reference to this vector.
  4309. */
  4310. setFromMatrixColumn( m, index ) {
  4311. return this.fromArray( m.elements, index * 4 );
  4312. }
  4313. /**
  4314. * Sets the vector components from the specified matrix column.
  4315. *
  4316. * @param {Matrix3} m - The 3x3 matrix.
  4317. * @param {number} index - The column index.
  4318. * @return {Vector3} A reference to this vector.
  4319. */
  4320. setFromMatrix3Column( m, index ) {
  4321. return this.fromArray( m.elements, index * 3 );
  4322. }
  4323. /**
  4324. * Sets the vector components from the given Euler angles.
  4325. *
  4326. * @param {Euler} e - The Euler angles to set.
  4327. * @return {Vector3} A reference to this vector.
  4328. */
  4329. setFromEuler( e ) {
  4330. this.x = e._x;
  4331. this.y = e._y;
  4332. this.z = e._z;
  4333. return this;
  4334. }
  4335. /**
  4336. * Sets the vector components from the RGB components of the
  4337. * given color.
  4338. *
  4339. * @param {Color} c - The color to set.
  4340. * @return {Vector3} A reference to this vector.
  4341. */
  4342. setFromColor( c ) {
  4343. this.x = c.r;
  4344. this.y = c.g;
  4345. this.z = c.b;
  4346. return this;
  4347. }
  4348. /**
  4349. * Returns `true` if this vector is equal with the given one.
  4350. *
  4351. * @param {Vector3} v - The vector to test for equality.
  4352. * @return {boolean} Whether this vector is equal with the given one.
  4353. */
  4354. equals( v ) {
  4355. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  4356. }
  4357. /**
  4358. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  4359. * and z value to be `array[ offset + 2 ]`.
  4360. *
  4361. * @param {Array<number>} array - An array holding the vector component values.
  4362. * @param {number} [offset=0] - The offset into the array.
  4363. * @return {Vector3} A reference to this vector.
  4364. */
  4365. fromArray( array, offset = 0 ) {
  4366. this.x = array[ offset ];
  4367. this.y = array[ offset + 1 ];
  4368. this.z = array[ offset + 2 ];
  4369. return this;
  4370. }
  4371. /**
  4372. * Writes the components of this vector to the given array. If no array is provided,
  4373. * the method returns a new instance.
  4374. *
  4375. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  4376. * @param {number} [offset=0] - Index of the first element in the array.
  4377. * @return {Array<number>} The vector components.
  4378. */
  4379. toArray( array = [], offset = 0 ) {
  4380. array[ offset ] = this.x;
  4381. array[ offset + 1 ] = this.y;
  4382. array[ offset + 2 ] = this.z;
  4383. return array;
  4384. }
  4385. /**
  4386. * Sets the components of this vector from the given buffer attribute.
  4387. *
  4388. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  4389. * @param {number} index - The index into the attribute.
  4390. * @return {Vector3} A reference to this vector.
  4391. */
  4392. fromBufferAttribute( attribute, index ) {
  4393. this.x = attribute.getX( index );
  4394. this.y = attribute.getY( index );
  4395. this.z = attribute.getZ( index );
  4396. return this;
  4397. }
  4398. /**
  4399. * Sets each component of this vector to a pseudo-random value between `0` and
  4400. * `1`, excluding `1`.
  4401. *
  4402. * @return {Vector3} A reference to this vector.
  4403. */
  4404. random() {
  4405. this.x = Math.random();
  4406. this.y = Math.random();
  4407. this.z = Math.random();
  4408. return this;
  4409. }
  4410. /**
  4411. * Sets this vector to a uniformly random point on a unit sphere.
  4412. *
  4413. * @return {Vector3} A reference to this vector.
  4414. */
  4415. randomDirection() {
  4416. // https://mathworld.wolfram.com/SpherePointPicking.html
  4417. const theta = Math.random() * Math.PI * 2;
  4418. const u = Math.random() * 2 - 1;
  4419. const c = Math.sqrt( 1 - u * u );
  4420. this.x = c * Math.cos( theta );
  4421. this.y = u;
  4422. this.z = c * Math.sin( theta );
  4423. return this;
  4424. }
  4425. *[ Symbol.iterator ]() {
  4426. yield this.x;
  4427. yield this.y;
  4428. yield this.z;
  4429. }
  4430. }
  4431. const _vector$c = /*@__PURE__*/ new Vector3();
  4432. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  4433. /**
  4434. * Represents a 3x3 matrix.
  4435. *
  4436. * A Note on Row-Major and Column-Major Ordering:
  4437. *
  4438. * The constructor and {@link Matrix3#set} method take arguments in
  4439. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  4440. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  4441. * This means that calling:
  4442. * ```js
  4443. * const m = new THREE.Matrix();
  4444. * m.set( 11, 12, 13,
  4445. * 21, 22, 23,
  4446. * 31, 32, 33 );
  4447. * ```
  4448. * will result in the elements array containing:
  4449. * ```js
  4450. * m.elements = [ 11, 21, 31,
  4451. * 12, 22, 32,
  4452. * 13, 23, 33 ];
  4453. * ```
  4454. * and internally all calculations are performed using column-major ordering.
  4455. * However, as the actual ordering makes no difference mathematically and
  4456. * most people are used to thinking about matrices in row-major order, the
  4457. * three.js documentation shows matrices in row-major order. Just bear in
  4458. * mind that if you are reading the source code, you'll have to take the
  4459. * transpose of any matrices outlined here to make sense of the calculations.
  4460. */
  4461. class Matrix3 {
  4462. /**
  4463. * Constructs a new 3x3 matrix. The arguments are supposed to be
  4464. * in row-major order. If no arguments are provided, the constructor
  4465. * initializes the matrix as an identity matrix.
  4466. *
  4467. * @param {number} [n11] - 1-1 matrix element.
  4468. * @param {number} [n12] - 1-2 matrix element.
  4469. * @param {number} [n13] - 1-3 matrix element.
  4470. * @param {number} [n21] - 2-1 matrix element.
  4471. * @param {number} [n22] - 2-2 matrix element.
  4472. * @param {number} [n23] - 2-3 matrix element.
  4473. * @param {number} [n31] - 3-1 matrix element.
  4474. * @param {number} [n32] - 3-2 matrix element.
  4475. * @param {number} [n33] - 3-3 matrix element.
  4476. */
  4477. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4478. /**
  4479. * This flag can be used for type testing.
  4480. *
  4481. * @type {boolean}
  4482. * @readonly
  4483. * @default true
  4484. */
  4485. Matrix3.prototype.isMatrix3 = true;
  4486. /**
  4487. * A column-major list of matrix values.
  4488. *
  4489. * @type {Array<number>}
  4490. */
  4491. this.elements = [
  4492. 1, 0, 0,
  4493. 0, 1, 0,
  4494. 0, 0, 1
  4495. ];
  4496. if ( n11 !== undefined ) {
  4497. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  4498. }
  4499. }
  4500. /**
  4501. * Sets the elements of the matrix.The arguments are supposed to be
  4502. * in row-major order.
  4503. *
  4504. * @param {number} [n11] - 1-1 matrix element.
  4505. * @param {number} [n12] - 1-2 matrix element.
  4506. * @param {number} [n13] - 1-3 matrix element.
  4507. * @param {number} [n21] - 2-1 matrix element.
  4508. * @param {number} [n22] - 2-2 matrix element.
  4509. * @param {number} [n23] - 2-3 matrix element.
  4510. * @param {number} [n31] - 3-1 matrix element.
  4511. * @param {number} [n32] - 3-2 matrix element.
  4512. * @param {number} [n33] - 3-3 matrix element.
  4513. * @return {Matrix3} A reference to this matrix.
  4514. */
  4515. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4516. const te = this.elements;
  4517. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  4518. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  4519. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  4520. return this;
  4521. }
  4522. /**
  4523. * Sets this matrix to the 3x3 identity matrix.
  4524. *
  4525. * @return {Matrix3} A reference to this matrix.
  4526. */
  4527. identity() {
  4528. this.set(
  4529. 1, 0, 0,
  4530. 0, 1, 0,
  4531. 0, 0, 1
  4532. );
  4533. return this;
  4534. }
  4535. /**
  4536. * Copies the values of the given matrix to this instance.
  4537. *
  4538. * @param {Matrix3} m - The matrix to copy.
  4539. * @return {Matrix3} A reference to this matrix.
  4540. */
  4541. copy( m ) {
  4542. const te = this.elements;
  4543. const me = m.elements;
  4544. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  4545. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  4546. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  4547. return this;
  4548. }
  4549. /**
  4550. * Extracts the basis of this matrix into the three axis vectors provided.
  4551. *
  4552. * @param {Vector3} xAxis - The basis's x axis.
  4553. * @param {Vector3} yAxis - The basis's y axis.
  4554. * @param {Vector3} zAxis - The basis's z axis.
  4555. * @return {Matrix3} A reference to this matrix.
  4556. */
  4557. extractBasis( xAxis, yAxis, zAxis ) {
  4558. xAxis.setFromMatrix3Column( this, 0 );
  4559. yAxis.setFromMatrix3Column( this, 1 );
  4560. zAxis.setFromMatrix3Column( this, 2 );
  4561. return this;
  4562. }
  4563. /**
  4564. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  4565. *
  4566. * @param {Matrix4} m - The 4x4 matrix.
  4567. * @return {Matrix3} A reference to this matrix.
  4568. */
  4569. setFromMatrix4( m ) {
  4570. const me = m.elements;
  4571. this.set(
  4572. me[ 0 ], me[ 4 ], me[ 8 ],
  4573. me[ 1 ], me[ 5 ], me[ 9 ],
  4574. me[ 2 ], me[ 6 ], me[ 10 ]
  4575. );
  4576. return this;
  4577. }
  4578. /**
  4579. * Post-multiplies this matrix by the given 3x3 matrix.
  4580. *
  4581. * @param {Matrix3} m - The matrix to multiply with.
  4582. * @return {Matrix3} A reference to this matrix.
  4583. */
  4584. multiply( m ) {
  4585. return this.multiplyMatrices( this, m );
  4586. }
  4587. /**
  4588. * Pre-multiplies this matrix by the given 3x3 matrix.
  4589. *
  4590. * @param {Matrix3} m - The matrix to multiply with.
  4591. * @return {Matrix3} A reference to this matrix.
  4592. */
  4593. premultiply( m ) {
  4594. return this.multiplyMatrices( m, this );
  4595. }
  4596. /**
  4597. * Multiples the given 3x3 matrices and stores the result
  4598. * in this matrix.
  4599. *
  4600. * @param {Matrix3} a - The first matrix.
  4601. * @param {Matrix3} b - The second matrix.
  4602. * @return {Matrix3} A reference to this matrix.
  4603. */
  4604. multiplyMatrices( a, b ) {
  4605. const ae = a.elements;
  4606. const be = b.elements;
  4607. const te = this.elements;
  4608. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  4609. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  4610. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  4611. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  4612. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  4613. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  4614. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  4615. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  4616. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  4617. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  4618. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  4619. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  4620. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  4621. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  4622. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  4623. return this;
  4624. }
  4625. /**
  4626. * Multiplies every component of the matrix by the given scalar.
  4627. *
  4628. * @param {number} s - The scalar.
  4629. * @return {Matrix3} A reference to this matrix.
  4630. */
  4631. multiplyScalar( s ) {
  4632. const te = this.elements;
  4633. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  4634. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  4635. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  4636. return this;
  4637. }
  4638. /**
  4639. * Computes and returns the determinant of this matrix.
  4640. *
  4641. * @return {number} The determinant.
  4642. */
  4643. determinant() {
  4644. const te = this.elements;
  4645. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  4646. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  4647. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  4648. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  4649. }
  4650. /**
  4651. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  4652. * You can not invert with a determinant of zero. If you attempt this, the method produces
  4653. * a zero matrix instead.
  4654. *
  4655. * @return {Matrix3} A reference to this matrix.
  4656. */
  4657. invert() {
  4658. const te = this.elements,
  4659. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  4660. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  4661. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  4662. t11 = n33 * n22 - n32 * n23,
  4663. t12 = n32 * n13 - n33 * n12,
  4664. t13 = n23 * n12 - n22 * n13,
  4665. det = n11 * t11 + n21 * t12 + n31 * t13;
  4666. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4667. const detInv = 1 / det;
  4668. te[ 0 ] = t11 * detInv;
  4669. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  4670. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  4671. te[ 3 ] = t12 * detInv;
  4672. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  4673. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  4674. te[ 6 ] = t13 * detInv;
  4675. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  4676. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  4677. return this;
  4678. }
  4679. /**
  4680. * Transposes this matrix in place.
  4681. *
  4682. * @return {Matrix3} A reference to this matrix.
  4683. */
  4684. transpose() {
  4685. let tmp;
  4686. const m = this.elements;
  4687. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  4688. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  4689. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  4690. return this;
  4691. }
  4692. /**
  4693. * Computes the normal matrix which is the inverse transpose of the upper
  4694. * left 3x3 portion of the given 4x4 matrix.
  4695. *
  4696. * @param {Matrix4} matrix4 - The 4x4 matrix.
  4697. * @return {Matrix3} A reference to this matrix.
  4698. */
  4699. getNormalMatrix( matrix4 ) {
  4700. return this.setFromMatrix4( matrix4 ).invert().transpose();
  4701. }
  4702. /**
  4703. * Transposes this matrix into the supplied array, and returns itself unchanged.
  4704. *
  4705. * @param {Array<number>} r - An array to store the transposed matrix elements.
  4706. * @return {Matrix3} A reference to this matrix.
  4707. */
  4708. transposeIntoArray( r ) {
  4709. const m = this.elements;
  4710. r[ 0 ] = m[ 0 ];
  4711. r[ 1 ] = m[ 3 ];
  4712. r[ 2 ] = m[ 6 ];
  4713. r[ 3 ] = m[ 1 ];
  4714. r[ 4 ] = m[ 4 ];
  4715. r[ 5 ] = m[ 7 ];
  4716. r[ 6 ] = m[ 2 ];
  4717. r[ 7 ] = m[ 5 ];
  4718. r[ 8 ] = m[ 8 ];
  4719. return this;
  4720. }
  4721. /**
  4722. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  4723. *
  4724. * @param {number} tx - Offset x.
  4725. * @param {number} ty - Offset y.
  4726. * @param {number} sx - Repeat x.
  4727. * @param {number} sy - Repeat y.
  4728. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  4729. * @param {number} cx - Center x of rotation.
  4730. * @param {number} cy - Center y of rotation
  4731. * @return {Matrix3} A reference to this matrix.
  4732. */
  4733. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  4734. const c = Math.cos( rotation );
  4735. const s = Math.sin( rotation );
  4736. this.set(
  4737. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  4738. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  4739. 0, 0, 1
  4740. );
  4741. return this;
  4742. }
  4743. /**
  4744. * Scales this matrix with the given scalar values.
  4745. *
  4746. * @param {number} sx - The amount to scale in the X axis.
  4747. * @param {number} sy - The amount to scale in the Y axis.
  4748. * @return {Matrix3} A reference to this matrix.
  4749. */
  4750. scale( sx, sy ) {
  4751. this.premultiply( _m3.makeScale( sx, sy ) );
  4752. return this;
  4753. }
  4754. /**
  4755. * Rotates this matrix by the given angle.
  4756. *
  4757. * @param {number} theta - The rotation in radians.
  4758. * @return {Matrix3} A reference to this matrix.
  4759. */
  4760. rotate( theta ) {
  4761. this.premultiply( _m3.makeRotation( - theta ) );
  4762. return this;
  4763. }
  4764. /**
  4765. * Translates this matrix by the given scalar values.
  4766. *
  4767. * @param {number} tx - The amount to translate in the X axis.
  4768. * @param {number} ty - The amount to translate in the Y axis.
  4769. * @return {Matrix3} A reference to this matrix.
  4770. */
  4771. translate( tx, ty ) {
  4772. this.premultiply( _m3.makeTranslation( tx, ty ) );
  4773. return this;
  4774. }
  4775. // for 2D Transforms
  4776. /**
  4777. * Sets this matrix as a 2D translation transform.
  4778. *
  4779. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  4780. * @param {number} y - The amount to translate in the Y axis.
  4781. * @return {Matrix3} A reference to this matrix.
  4782. */
  4783. makeTranslation( x, y ) {
  4784. if ( x.isVector2 ) {
  4785. this.set(
  4786. 1, 0, x.x,
  4787. 0, 1, x.y,
  4788. 0, 0, 1
  4789. );
  4790. } else {
  4791. this.set(
  4792. 1, 0, x,
  4793. 0, 1, y,
  4794. 0, 0, 1
  4795. );
  4796. }
  4797. return this;
  4798. }
  4799. /**
  4800. * Sets this matrix as a 2D rotational transformation.
  4801. *
  4802. * @param {number} theta - The rotation in radians.
  4803. * @return {Matrix3} A reference to this matrix.
  4804. */
  4805. makeRotation( theta ) {
  4806. // counterclockwise
  4807. const c = Math.cos( theta );
  4808. const s = Math.sin( theta );
  4809. this.set(
  4810. c, - s, 0,
  4811. s, c, 0,
  4812. 0, 0, 1
  4813. );
  4814. return this;
  4815. }
  4816. /**
  4817. * Sets this matrix as a 2D scale transform.
  4818. *
  4819. * @param {number} x - The amount to scale in the X axis.
  4820. * @param {number} y - The amount to scale in the Y axis.
  4821. * @return {Matrix3} A reference to this matrix.
  4822. */
  4823. makeScale( x, y ) {
  4824. this.set(
  4825. x, 0, 0,
  4826. 0, y, 0,
  4827. 0, 0, 1
  4828. );
  4829. return this;
  4830. }
  4831. /**
  4832. * Returns `true` if this matrix is equal with the given one.
  4833. *
  4834. * @param {Matrix3} matrix - The matrix to test for equality.
  4835. * @return {boolean} Whether this matrix is equal with the given one.
  4836. */
  4837. equals( matrix ) {
  4838. const te = this.elements;
  4839. const me = matrix.elements;
  4840. for ( let i = 0; i < 9; i ++ ) {
  4841. if ( te[ i ] !== me[ i ] ) return false;
  4842. }
  4843. return true;
  4844. }
  4845. /**
  4846. * Sets the elements of the matrix from the given array.
  4847. *
  4848. * @param {Array<number>} array - The matrix elements in column-major order.
  4849. * @param {number} [offset=0] - Index of the first element in the array.
  4850. * @return {Matrix3} A reference to this matrix.
  4851. */
  4852. fromArray( array, offset = 0 ) {
  4853. for ( let i = 0; i < 9; i ++ ) {
  4854. this.elements[ i ] = array[ i + offset ];
  4855. }
  4856. return this;
  4857. }
  4858. /**
  4859. * Writes the elements of this matrix to the given array. If no array is provided,
  4860. * the method returns a new instance.
  4861. *
  4862. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  4863. * @param {number} [offset=0] - Index of the first element in the array.
  4864. * @return {Array<number>} The matrix elements in column-major order.
  4865. */
  4866. toArray( array = [], offset = 0 ) {
  4867. const te = this.elements;
  4868. array[ offset ] = te[ 0 ];
  4869. array[ offset + 1 ] = te[ 1 ];
  4870. array[ offset + 2 ] = te[ 2 ];
  4871. array[ offset + 3 ] = te[ 3 ];
  4872. array[ offset + 4 ] = te[ 4 ];
  4873. array[ offset + 5 ] = te[ 5 ];
  4874. array[ offset + 6 ] = te[ 6 ];
  4875. array[ offset + 7 ] = te[ 7 ];
  4876. array[ offset + 8 ] = te[ 8 ];
  4877. return array;
  4878. }
  4879. /**
  4880. * Returns a matrix with copied values from this instance.
  4881. *
  4882. * @return {Matrix3} A clone of this instance.
  4883. */
  4884. clone() {
  4885. return new this.constructor().fromArray( this.elements );
  4886. }
  4887. }
  4888. const _m3 = /*@__PURE__*/ new Matrix3();
  4889. function arrayNeedsUint32( array ) {
  4890. // assumes larger values usually on last
  4891. for ( let i = array.length - 1; i >= 0; -- i ) {
  4892. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  4893. }
  4894. return false;
  4895. }
  4896. const TYPED_ARRAYS = {
  4897. Int8Array: Int8Array,
  4898. Uint8Array: Uint8Array,
  4899. Uint8ClampedArray: Uint8ClampedArray,
  4900. Int16Array: Int16Array,
  4901. Uint16Array: Uint16Array,
  4902. Int32Array: Int32Array,
  4903. Uint32Array: Uint32Array,
  4904. Float32Array: Float32Array,
  4905. Float64Array: Float64Array
  4906. };
  4907. function getTypedArray( type, buffer ) {
  4908. return new TYPED_ARRAYS[ type ]( buffer );
  4909. }
  4910. function createElementNS( name ) {
  4911. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  4912. }
  4913. function createCanvasElement() {
  4914. const canvas = createElementNS( 'canvas' );
  4915. canvas.style.display = 'block';
  4916. return canvas;
  4917. }
  4918. const _cache = {};
  4919. function warnOnce( message ) {
  4920. if ( message in _cache ) return;
  4921. _cache[ message ] = true;
  4922. console.warn( message );
  4923. }
  4924. function probeAsync( gl, sync, interval ) {
  4925. return new Promise( function ( resolve, reject ) {
  4926. function probe() {
  4927. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  4928. case gl.WAIT_FAILED:
  4929. reject();
  4930. break;
  4931. case gl.TIMEOUT_EXPIRED:
  4932. setTimeout( probe, interval );
  4933. break;
  4934. default:
  4935. resolve();
  4936. }
  4937. }
  4938. setTimeout( probe, interval );
  4939. } );
  4940. }
  4941. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  4942. 0.4123908, 0.3575843, 0.1804808,
  4943. 0.2126390, 0.7151687, 0.0721923,
  4944. 0.0193308, 0.1191948, 0.9505322
  4945. );
  4946. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  4947. 3.2409699, -1.5373832, -0.4986108,
  4948. -0.9692436, 1.8759675, 0.0415551,
  4949. 0.0556301, -0.203977, 1.0569715
  4950. );
  4951. function createColorManagement() {
  4952. const ColorManagement = {
  4953. enabled: true,
  4954. workingColorSpace: LinearSRGBColorSpace,
  4955. /**
  4956. * Implementations of supported color spaces.
  4957. *
  4958. * Required:
  4959. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  4960. * - whitePoint: reference white [ x y ]
  4961. * - transfer: transfer function (pre-defined)
  4962. * - toXYZ: Matrix3 RGB to XYZ transform
  4963. * - fromXYZ: Matrix3 XYZ to RGB transform
  4964. * - luminanceCoefficients: RGB luminance coefficients
  4965. *
  4966. * Optional:
  4967. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' }
  4968. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  4969. *
  4970. * Reference:
  4971. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  4972. */
  4973. spaces: {},
  4974. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  4975. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  4976. return color;
  4977. }
  4978. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  4979. color.r = SRGBToLinear( color.r );
  4980. color.g = SRGBToLinear( color.g );
  4981. color.b = SRGBToLinear( color.b );
  4982. }
  4983. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  4984. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  4985. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  4986. }
  4987. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  4988. color.r = LinearToSRGB( color.r );
  4989. color.g = LinearToSRGB( color.g );
  4990. color.b = LinearToSRGB( color.b );
  4991. }
  4992. return color;
  4993. },
  4994. workingToColorSpace: function ( color, targetColorSpace ) {
  4995. return this.convert( color, this.workingColorSpace, targetColorSpace );
  4996. },
  4997. colorSpaceToWorking: function ( color, sourceColorSpace ) {
  4998. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  4999. },
  5000. getPrimaries: function ( colorSpace ) {
  5001. return this.spaces[ colorSpace ].primaries;
  5002. },
  5003. getTransfer: function ( colorSpace ) {
  5004. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  5005. return this.spaces[ colorSpace ].transfer;
  5006. },
  5007. getToneMappingMode: function ( colorSpace ) {
  5008. return this.spaces[ colorSpace ].outputColorSpaceConfig.toneMappingMode || 'standard';
  5009. },
  5010. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  5011. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  5012. },
  5013. define: function ( colorSpaces ) {
  5014. Object.assign( this.spaces, colorSpaces );
  5015. },
  5016. // Internal APIs
  5017. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  5018. return targetMatrix
  5019. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  5020. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  5021. },
  5022. _getDrawingBufferColorSpace: function ( colorSpace ) {
  5023. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  5024. },
  5025. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  5026. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  5027. },
  5028. // Deprecated
  5029. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  5030. warnOnce( 'THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().' ); // @deprecated, r177
  5031. return ColorManagement.workingToColorSpace( color, targetColorSpace );
  5032. },
  5033. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  5034. warnOnce( 'THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().' ); // @deprecated, r177
  5035. return ColorManagement.colorSpaceToWorking( color, sourceColorSpace );
  5036. },
  5037. };
  5038. /******************************************************************************
  5039. * sRGB definitions
  5040. */
  5041. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  5042. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  5043. const D65 = [ 0.3127, 0.3290 ];
  5044. ColorManagement.define( {
  5045. [ LinearSRGBColorSpace ]: {
  5046. primaries: REC709_PRIMARIES,
  5047. whitePoint: D65,
  5048. transfer: LinearTransfer,
  5049. toXYZ: LINEAR_REC709_TO_XYZ,
  5050. fromXYZ: XYZ_TO_LINEAR_REC709,
  5051. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5052. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  5053. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5054. },
  5055. [ SRGBColorSpace ]: {
  5056. primaries: REC709_PRIMARIES,
  5057. whitePoint: D65,
  5058. transfer: SRGBTransfer,
  5059. toXYZ: LINEAR_REC709_TO_XYZ,
  5060. fromXYZ: XYZ_TO_LINEAR_REC709,
  5061. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5062. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5063. },
  5064. } );
  5065. return ColorManagement;
  5066. }
  5067. const ColorManagement = /*@__PURE__*/ createColorManagement();
  5068. function SRGBToLinear( c ) {
  5069. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5070. }
  5071. function LinearToSRGB( c ) {
  5072. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5073. }
  5074. let _canvas;
  5075. /**
  5076. * A class containing utility functions for images.
  5077. *
  5078. * @hideconstructor
  5079. */
  5080. class ImageUtils {
  5081. /**
  5082. * Returns a data URI containing a representation of the given image.
  5083. *
  5084. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  5085. * @param {string} [type='image/png'] - Indicates the image format.
  5086. * @return {string} The data URI.
  5087. */
  5088. static getDataURL( image, type = 'image/png' ) {
  5089. if ( /^data:/i.test( image.src ) ) {
  5090. return image.src;
  5091. }
  5092. if ( typeof HTMLCanvasElement === 'undefined' ) {
  5093. return image.src;
  5094. }
  5095. let canvas;
  5096. if ( image instanceof HTMLCanvasElement ) {
  5097. canvas = image;
  5098. } else {
  5099. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  5100. _canvas.width = image.width;
  5101. _canvas.height = image.height;
  5102. const context = _canvas.getContext( '2d' );
  5103. if ( image instanceof ImageData ) {
  5104. context.putImageData( image, 0, 0 );
  5105. } else {
  5106. context.drawImage( image, 0, 0, image.width, image.height );
  5107. }
  5108. canvas = _canvas;
  5109. }
  5110. return canvas.toDataURL( type );
  5111. }
  5112. /**
  5113. * Converts the given sRGB image data to linear color space.
  5114. *
  5115. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  5116. * @return {HTMLCanvasElement|Object} The converted image.
  5117. */
  5118. static sRGBToLinear( image ) {
  5119. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5120. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5121. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5122. const canvas = createElementNS( 'canvas' );
  5123. canvas.width = image.width;
  5124. canvas.height = image.height;
  5125. const context = canvas.getContext( '2d' );
  5126. context.drawImage( image, 0, 0, image.width, image.height );
  5127. const imageData = context.getImageData( 0, 0, image.width, image.height );
  5128. const data = imageData.data;
  5129. for ( let i = 0; i < data.length; i ++ ) {
  5130. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  5131. }
  5132. context.putImageData( imageData, 0, 0 );
  5133. return canvas;
  5134. } else if ( image.data ) {
  5135. const data = image.data.slice( 0 );
  5136. for ( let i = 0; i < data.length; i ++ ) {
  5137. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  5138. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  5139. } else {
  5140. // assuming float
  5141. data[ i ] = SRGBToLinear( data[ i ] );
  5142. }
  5143. }
  5144. return {
  5145. data: data,
  5146. width: image.width,
  5147. height: image.height
  5148. };
  5149. } else {
  5150. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  5151. return image;
  5152. }
  5153. }
  5154. }
  5155. let _sourceId = 0;
  5156. /**
  5157. * Represents the data source of a texture.
  5158. *
  5159. * The main purpose of this class is to decouple the data definition from the texture
  5160. * definition so the same data can be used with multiple texture instances.
  5161. */
  5162. class Source {
  5163. /**
  5164. * Constructs a new video texture.
  5165. *
  5166. * @param {any} [data=null] - The data definition of a texture.
  5167. */
  5168. constructor( data = null ) {
  5169. /**
  5170. * This flag can be used for type testing.
  5171. *
  5172. * @type {boolean}
  5173. * @readonly
  5174. * @default true
  5175. */
  5176. this.isSource = true;
  5177. /**
  5178. * The ID of the source.
  5179. *
  5180. * @name Source#id
  5181. * @type {number}
  5182. * @readonly
  5183. */
  5184. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  5185. /**
  5186. * The UUID of the source.
  5187. *
  5188. * @type {string}
  5189. * @readonly
  5190. */
  5191. this.uuid = generateUUID();
  5192. /**
  5193. * The data definition of a texture.
  5194. *
  5195. * @type {any}
  5196. */
  5197. this.data = data;
  5198. /**
  5199. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  5200. * provides more control on how texture data should be processed. When `dataReady` is set
  5201. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  5202. * the data into the GPU memory.
  5203. *
  5204. * @type {boolean}
  5205. * @default true
  5206. */
  5207. this.dataReady = true;
  5208. /**
  5209. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  5210. *
  5211. * @type {number}
  5212. * @readonly
  5213. * @default 0
  5214. */
  5215. this.version = 0;
  5216. }
  5217. /**
  5218. * Returns the dimensions of the source into the given target vector.
  5219. *
  5220. * @param {(Vector2|Vector3)} target - The target object the result is written into.
  5221. * @return {(Vector2|Vector3)} The dimensions of the source.
  5222. */
  5223. getSize( target ) {
  5224. const data = this.data;
  5225. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( data instanceof HTMLVideoElement ) ) {
  5226. target.set( data.videoWidth, data.videoHeight, 0 );
  5227. } else if ( data instanceof VideoFrame ) {
  5228. target.set( data.displayHeight, data.displayWidth, 0 );
  5229. } else if ( data !== null ) {
  5230. target.set( data.width, data.height, data.depth || 0 );
  5231. } else {
  5232. target.set( 0, 0, 0 );
  5233. }
  5234. return target;
  5235. }
  5236. /**
  5237. * When the property is set to `true`, the engine allocates the memory
  5238. * for the texture (if necessary) and triggers the actual texture upload
  5239. * to the GPU next time the source is used.
  5240. *
  5241. * @type {boolean}
  5242. * @default false
  5243. * @param {boolean} value
  5244. */
  5245. set needsUpdate( value ) {
  5246. if ( value === true ) this.version ++;
  5247. }
  5248. /**
  5249. * Serializes the source into JSON.
  5250. *
  5251. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5252. * @return {Object} A JSON object representing the serialized source.
  5253. * @see {@link ObjectLoader#parse}
  5254. */
  5255. toJSON( meta ) {
  5256. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5257. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  5258. return meta.images[ this.uuid ];
  5259. }
  5260. const output = {
  5261. uuid: this.uuid,
  5262. url: ''
  5263. };
  5264. const data = this.data;
  5265. if ( data !== null ) {
  5266. let url;
  5267. if ( Array.isArray( data ) ) {
  5268. // cube texture
  5269. url = [];
  5270. for ( let i = 0, l = data.length; i < l; i ++ ) {
  5271. if ( data[ i ].isDataTexture ) {
  5272. url.push( serializeImage( data[ i ].image ) );
  5273. } else {
  5274. url.push( serializeImage( data[ i ] ) );
  5275. }
  5276. }
  5277. } else {
  5278. // texture
  5279. url = serializeImage( data );
  5280. }
  5281. output.url = url;
  5282. }
  5283. if ( ! isRootObject ) {
  5284. meta.images[ this.uuid ] = output;
  5285. }
  5286. return output;
  5287. }
  5288. }
  5289. function serializeImage( image ) {
  5290. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5291. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5292. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5293. // default images
  5294. return ImageUtils.getDataURL( image );
  5295. } else {
  5296. if ( image.data ) {
  5297. // images of DataTexture
  5298. return {
  5299. data: Array.from( image.data ),
  5300. width: image.width,
  5301. height: image.height,
  5302. type: image.data.constructor.name
  5303. };
  5304. } else {
  5305. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  5306. return {};
  5307. }
  5308. }
  5309. }
  5310. let _textureId = 0;
  5311. const _tempVec3 = /*@__PURE__*/ new Vector3();
  5312. /**
  5313. * Base class for all textures.
  5314. *
  5315. * Note: After the initial use of a texture, its dimensions, format, and type
  5316. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  5317. *
  5318. * @augments EventDispatcher
  5319. */
  5320. class Texture extends EventDispatcher {
  5321. /**
  5322. * Constructs a new texture.
  5323. *
  5324. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  5325. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  5326. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  5327. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  5328. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  5329. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  5330. * @param {number} [format=RGBAFormat] - The texture format.
  5331. * @param {number} [type=UnsignedByteType] - The texture type.
  5332. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  5333. * @param {string} [colorSpace=NoColorSpace] - The color space.
  5334. */
  5335. 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 ) {
  5336. super();
  5337. /**
  5338. * This flag can be used for type testing.
  5339. *
  5340. * @type {boolean}
  5341. * @readonly
  5342. * @default true
  5343. */
  5344. this.isTexture = true;
  5345. /**
  5346. * The ID of the texture.
  5347. *
  5348. * @name Texture#id
  5349. * @type {number}
  5350. * @readonly
  5351. */
  5352. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  5353. /**
  5354. * The UUID of the material.
  5355. *
  5356. * @type {string}
  5357. * @readonly
  5358. */
  5359. this.uuid = generateUUID();
  5360. /**
  5361. * The name of the material.
  5362. *
  5363. * @type {string}
  5364. */
  5365. this.name = '';
  5366. /**
  5367. * The data definition of a texture. A reference to the data source can be
  5368. * shared across textures. This is often useful in context of spritesheets
  5369. * where multiple textures render the same data but with different texture
  5370. * transformations.
  5371. *
  5372. * @type {Source}
  5373. */
  5374. this.source = new Source( image );
  5375. /**
  5376. * An array holding user-defined mipmaps.
  5377. *
  5378. * @type {Array<Object>}
  5379. */
  5380. this.mipmaps = [];
  5381. /**
  5382. * How the texture is applied to the object. The value `UVMapping`
  5383. * is the default, where texture or uv coordinates are used to apply the map.
  5384. *
  5385. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  5386. * @default UVMapping
  5387. */
  5388. this.mapping = mapping;
  5389. /**
  5390. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  5391. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  5392. *
  5393. * @type {number}
  5394. * @default 0
  5395. */
  5396. this.channel = 0;
  5397. /**
  5398. * This defines how the texture is wrapped horizontally and corresponds to
  5399. * *U* in UV mapping.
  5400. *
  5401. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5402. * @default ClampToEdgeWrapping
  5403. */
  5404. this.wrapS = wrapS;
  5405. /**
  5406. * This defines how the texture is wrapped horizontally and corresponds to
  5407. * *V* in UV mapping.
  5408. *
  5409. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5410. * @default ClampToEdgeWrapping
  5411. */
  5412. this.wrapT = wrapT;
  5413. /**
  5414. * How the texture is sampled when a texel covers more than one pixel.
  5415. *
  5416. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5417. * @default LinearFilter
  5418. */
  5419. this.magFilter = magFilter;
  5420. /**
  5421. * How the texture is sampled when a texel covers less than one pixel.
  5422. *
  5423. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5424. * @default LinearMipmapLinearFilter
  5425. */
  5426. this.minFilter = minFilter;
  5427. /**
  5428. * The number of samples taken along the axis through the pixel that has the
  5429. * highest density of texels. By default, this value is `1`. A higher value
  5430. * gives a less blurry result than a basic mipmap, at the cost of more
  5431. * texture samples being used.
  5432. *
  5433. * @type {number}
  5434. * @default 0
  5435. */
  5436. this.anisotropy = anisotropy;
  5437. /**
  5438. * The format of the texture.
  5439. *
  5440. * @type {number}
  5441. * @default RGBAFormat
  5442. */
  5443. this.format = format;
  5444. /**
  5445. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  5446. * defines how the texture data is going to be stored on the GPU.
  5447. *
  5448. * This property allows to overwrite the default format.
  5449. *
  5450. * @type {?string}
  5451. * @default null
  5452. */
  5453. this.internalFormat = null;
  5454. /**
  5455. * The data type of the texture.
  5456. *
  5457. * @type {number}
  5458. * @default UnsignedByteType
  5459. */
  5460. this.type = type;
  5461. /**
  5462. * How much a single repetition of the texture is offset from the beginning,
  5463. * in each direction U and V. Typical range is `0.0` to `1.0`.
  5464. *
  5465. * @type {Vector2}
  5466. * @default (0,0)
  5467. */
  5468. this.offset = new Vector2( 0, 0 );
  5469. /**
  5470. * How many times the texture is repeated across the surface, in each
  5471. * direction U and V. If repeat is set greater than `1` in either direction,
  5472. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  5473. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  5474. *
  5475. * @type {Vector2}
  5476. * @default (1,1)
  5477. */
  5478. this.repeat = new Vector2( 1, 1 );
  5479. /**
  5480. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  5481. * to the center of the texture. Default is `(0, 0)`, the lower left.
  5482. *
  5483. * @type {Vector2}
  5484. * @default (0,0)
  5485. */
  5486. this.center = new Vector2( 0, 0 );
  5487. /**
  5488. * How much the texture is rotated around the center point, in radians.
  5489. * Positive values are counter-clockwise.
  5490. *
  5491. * @type {number}
  5492. * @default 0
  5493. */
  5494. this.rotation = 0;
  5495. /**
  5496. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  5497. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  5498. * {@link Texture#rotation}, and {@link Texture#center}.
  5499. *
  5500. * Set this to `false` if you are specifying the uv-transform matrix directly.
  5501. *
  5502. * @type {boolean}
  5503. * @default true
  5504. */
  5505. this.matrixAutoUpdate = true;
  5506. /**
  5507. * The uv-transformation matrix of the texture.
  5508. *
  5509. * @type {Matrix3}
  5510. */
  5511. this.matrix = new Matrix3();
  5512. /**
  5513. * Whether to generate mipmaps (if possible) for a texture.
  5514. *
  5515. * Set this to `false` if you are creating mipmaps manually.
  5516. *
  5517. * @type {boolean}
  5518. * @default true
  5519. */
  5520. this.generateMipmaps = true;
  5521. /**
  5522. * If set to `true`, the alpha channel, if present, is multiplied into the
  5523. * color channels when the texture is uploaded to the GPU.
  5524. *
  5525. * Note that this property has no effect when using `ImageBitmap`. You need to
  5526. * configure premultiply alpha on bitmap creation instead.
  5527. *
  5528. * @type {boolean}
  5529. * @default false
  5530. */
  5531. this.premultiplyAlpha = false;
  5532. /**
  5533. * If set to `true`, the texture is flipped along the vertical axis when
  5534. * uploaded to the GPU.
  5535. *
  5536. * Note that this property has no effect when using `ImageBitmap`. You need to
  5537. * configure the flip on bitmap creation instead.
  5538. *
  5539. * @type {boolean}
  5540. * @default true
  5541. */
  5542. this.flipY = true;
  5543. /**
  5544. * Specifies the alignment requirements for the start of each pixel row in memory.
  5545. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  5546. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  5547. *
  5548. * @type {number}
  5549. * @default 4
  5550. */
  5551. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  5552. /**
  5553. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  5554. *
  5555. * @type {string}
  5556. * @default NoColorSpace
  5557. */
  5558. this.colorSpace = colorSpace;
  5559. /**
  5560. * An object that can be used to store custom data about the texture. It
  5561. * should not hold references to functions as these will not be cloned.
  5562. *
  5563. * @type {Object}
  5564. */
  5565. this.userData = {};
  5566. /**
  5567. * This can be used to only update a subregion or specific rows of the texture (for example, just the
  5568. * first 3 rows). Use the `addUpdateRange()` function to add ranges to this array.
  5569. *
  5570. * @type {Array<Object>}
  5571. */
  5572. this.updateRanges = [];
  5573. /**
  5574. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  5575. *
  5576. * @type {number}
  5577. * @readonly
  5578. * @default 0
  5579. */
  5580. this.version = 0;
  5581. /**
  5582. * A callback function, called when the texture is updated (e.g., when
  5583. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  5584. *
  5585. * @type {?Function}
  5586. * @default null
  5587. */
  5588. this.onUpdate = null;
  5589. /**
  5590. * An optional back reference to the textures render target.
  5591. *
  5592. * @type {?(RenderTarget|WebGLRenderTarget)}
  5593. * @default null
  5594. */
  5595. this.renderTarget = null;
  5596. /**
  5597. * Indicates whether a texture belongs to a render target or not.
  5598. *
  5599. * @type {boolean}
  5600. * @readonly
  5601. * @default false
  5602. */
  5603. this.isRenderTargetTexture = false;
  5604. /**
  5605. * Indicates if a texture should be handled like a texture array.
  5606. *
  5607. * @type {boolean}
  5608. * @readonly
  5609. * @default false
  5610. */
  5611. this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false;
  5612. /**
  5613. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  5614. * (only relevant for render target textures).
  5615. *
  5616. * @type {number}
  5617. * @readonly
  5618. * @default 0
  5619. */
  5620. this.pmremVersion = 0;
  5621. }
  5622. /**
  5623. * The width of the texture in pixels.
  5624. */
  5625. get width() {
  5626. return this.source.getSize( _tempVec3 ).x;
  5627. }
  5628. /**
  5629. * The height of the texture in pixels.
  5630. */
  5631. get height() {
  5632. return this.source.getSize( _tempVec3 ).y;
  5633. }
  5634. /**
  5635. * The depth of the texture in pixels.
  5636. */
  5637. get depth() {
  5638. return this.source.getSize( _tempVec3 ).z;
  5639. }
  5640. /**
  5641. * The image object holding the texture data.
  5642. *
  5643. * @type {?Object}
  5644. */
  5645. get image() {
  5646. return this.source.data;
  5647. }
  5648. set image( value = null ) {
  5649. this.source.data = value;
  5650. }
  5651. /**
  5652. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  5653. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  5654. */
  5655. updateMatrix() {
  5656. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  5657. }
  5658. /**
  5659. * Adds a range of data in the data texture to be updated on the GPU.
  5660. *
  5661. * @param {number} start - Position at which to start update.
  5662. * @param {number} count - The number of components to update.
  5663. */
  5664. addUpdateRange( start, count ) {
  5665. this.updateRanges.push( { start, count } );
  5666. }
  5667. /**
  5668. * Clears the update ranges.
  5669. */
  5670. clearUpdateRanges() {
  5671. this.updateRanges.length = 0;
  5672. }
  5673. /**
  5674. * Returns a new texture with copied values from this instance.
  5675. *
  5676. * @return {Texture} A clone of this instance.
  5677. */
  5678. clone() {
  5679. return new this.constructor().copy( this );
  5680. }
  5681. /**
  5682. * Copies the values of the given texture to this instance.
  5683. *
  5684. * @param {Texture} source - The texture to copy.
  5685. * @return {Texture} A reference to this instance.
  5686. */
  5687. copy( source ) {
  5688. this.name = source.name;
  5689. this.source = source.source;
  5690. this.mipmaps = source.mipmaps.slice( 0 );
  5691. this.mapping = source.mapping;
  5692. this.channel = source.channel;
  5693. this.wrapS = source.wrapS;
  5694. this.wrapT = source.wrapT;
  5695. this.magFilter = source.magFilter;
  5696. this.minFilter = source.minFilter;
  5697. this.anisotropy = source.anisotropy;
  5698. this.format = source.format;
  5699. this.internalFormat = source.internalFormat;
  5700. this.type = source.type;
  5701. this.offset.copy( source.offset );
  5702. this.repeat.copy( source.repeat );
  5703. this.center.copy( source.center );
  5704. this.rotation = source.rotation;
  5705. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5706. this.matrix.copy( source.matrix );
  5707. this.generateMipmaps = source.generateMipmaps;
  5708. this.premultiplyAlpha = source.premultiplyAlpha;
  5709. this.flipY = source.flipY;
  5710. this.unpackAlignment = source.unpackAlignment;
  5711. this.colorSpace = source.colorSpace;
  5712. this.renderTarget = source.renderTarget;
  5713. this.isRenderTargetTexture = source.isRenderTargetTexture;
  5714. this.isArrayTexture = source.isArrayTexture;
  5715. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5716. this.needsUpdate = true;
  5717. return this;
  5718. }
  5719. /**
  5720. * Sets this texture's properties based on `values`.
  5721. * @param {Object} values - A container with texture parameters.
  5722. */
  5723. setValues( values ) {
  5724. for ( const key in values ) {
  5725. const newValue = values[ key ];
  5726. if ( newValue === undefined ) {
  5727. console.warn( `THREE.Texture.setValues(): parameter '${ key }' has value of undefined.` );
  5728. continue;
  5729. }
  5730. const currentValue = this[ key ];
  5731. if ( currentValue === undefined ) {
  5732. console.warn( `THREE.Texture.setValues(): property '${ key }' does not exist.` );
  5733. continue;
  5734. }
  5735. if ( ( currentValue && newValue ) && ( currentValue.isVector2 && newValue.isVector2 ) ) {
  5736. currentValue.copy( newValue );
  5737. } else if ( ( currentValue && newValue ) && ( currentValue.isVector3 && newValue.isVector3 ) ) {
  5738. currentValue.copy( newValue );
  5739. } else if ( ( currentValue && newValue ) && ( currentValue.isMatrix3 && newValue.isMatrix3 ) ) {
  5740. currentValue.copy( newValue );
  5741. } else {
  5742. this[ key ] = newValue;
  5743. }
  5744. }
  5745. }
  5746. /**
  5747. * Serializes the texture into JSON.
  5748. *
  5749. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5750. * @return {Object} A JSON object representing the serialized texture.
  5751. * @see {@link ObjectLoader#parse}
  5752. */
  5753. toJSON( meta ) {
  5754. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5755. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  5756. return meta.textures[ this.uuid ];
  5757. }
  5758. const output = {
  5759. metadata: {
  5760. version: 4.7,
  5761. type: 'Texture',
  5762. generator: 'Texture.toJSON'
  5763. },
  5764. uuid: this.uuid,
  5765. name: this.name,
  5766. image: this.source.toJSON( meta ).uuid,
  5767. mapping: this.mapping,
  5768. channel: this.channel,
  5769. repeat: [ this.repeat.x, this.repeat.y ],
  5770. offset: [ this.offset.x, this.offset.y ],
  5771. center: [ this.center.x, this.center.y ],
  5772. rotation: this.rotation,
  5773. wrap: [ this.wrapS, this.wrapT ],
  5774. format: this.format,
  5775. internalFormat: this.internalFormat,
  5776. type: this.type,
  5777. colorSpace: this.colorSpace,
  5778. minFilter: this.minFilter,
  5779. magFilter: this.magFilter,
  5780. anisotropy: this.anisotropy,
  5781. flipY: this.flipY,
  5782. generateMipmaps: this.generateMipmaps,
  5783. premultiplyAlpha: this.premultiplyAlpha,
  5784. unpackAlignment: this.unpackAlignment
  5785. };
  5786. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  5787. if ( ! isRootObject ) {
  5788. meta.textures[ this.uuid ] = output;
  5789. }
  5790. return output;
  5791. }
  5792. /**
  5793. * Frees the GPU-related resources allocated by this instance. Call this
  5794. * method whenever this instance is no longer used in your app.
  5795. *
  5796. * @fires Texture#dispose
  5797. */
  5798. dispose() {
  5799. /**
  5800. * Fires when the texture has been disposed of.
  5801. *
  5802. * @event Texture#dispose
  5803. * @type {Object}
  5804. */
  5805. this.dispatchEvent( { type: 'dispose' } );
  5806. }
  5807. /**
  5808. * Transforms the given uv vector with the textures uv transformation matrix.
  5809. *
  5810. * @param {Vector2} uv - The uv vector.
  5811. * @return {Vector2} The transformed uv vector.
  5812. */
  5813. transformUv( uv ) {
  5814. if ( this.mapping !== UVMapping ) return uv;
  5815. uv.applyMatrix3( this.matrix );
  5816. if ( uv.x < 0 || uv.x > 1 ) {
  5817. switch ( this.wrapS ) {
  5818. case RepeatWrapping:
  5819. uv.x = uv.x - Math.floor( uv.x );
  5820. break;
  5821. case ClampToEdgeWrapping:
  5822. uv.x = uv.x < 0 ? 0 : 1;
  5823. break;
  5824. case MirroredRepeatWrapping:
  5825. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  5826. uv.x = Math.ceil( uv.x ) - uv.x;
  5827. } else {
  5828. uv.x = uv.x - Math.floor( uv.x );
  5829. }
  5830. break;
  5831. }
  5832. }
  5833. if ( uv.y < 0 || uv.y > 1 ) {
  5834. switch ( this.wrapT ) {
  5835. case RepeatWrapping:
  5836. uv.y = uv.y - Math.floor( uv.y );
  5837. break;
  5838. case ClampToEdgeWrapping:
  5839. uv.y = uv.y < 0 ? 0 : 1;
  5840. break;
  5841. case MirroredRepeatWrapping:
  5842. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  5843. uv.y = Math.ceil( uv.y ) - uv.y;
  5844. } else {
  5845. uv.y = uv.y - Math.floor( uv.y );
  5846. }
  5847. break;
  5848. }
  5849. }
  5850. if ( this.flipY ) {
  5851. uv.y = 1 - uv.y;
  5852. }
  5853. return uv;
  5854. }
  5855. /**
  5856. * Setting this property to `true` indicates the engine the texture
  5857. * must be updated in the next render. This triggers a texture upload
  5858. * to the GPU and ensures correct texture parameter configuration.
  5859. *
  5860. * @type {boolean}
  5861. * @default false
  5862. * @param {boolean} value
  5863. */
  5864. set needsUpdate( value ) {
  5865. if ( value === true ) {
  5866. this.version ++;
  5867. this.source.needsUpdate = true;
  5868. }
  5869. }
  5870. /**
  5871. * Setting this property to `true` indicates the engine the PMREM
  5872. * must be regenerated.
  5873. *
  5874. * @type {boolean}
  5875. * @default false
  5876. * @param {boolean} value
  5877. */
  5878. set needsPMREMUpdate( value ) {
  5879. if ( value === true ) {
  5880. this.pmremVersion ++;
  5881. }
  5882. }
  5883. }
  5884. /**
  5885. * The default image for all textures.
  5886. *
  5887. * @static
  5888. * @type {?Image}
  5889. * @default null
  5890. */
  5891. Texture.DEFAULT_IMAGE = null;
  5892. /**
  5893. * The default mapping for all textures.
  5894. *
  5895. * @static
  5896. * @type {number}
  5897. * @default UVMapping
  5898. */
  5899. Texture.DEFAULT_MAPPING = UVMapping;
  5900. /**
  5901. * The default anisotropy value for all textures.
  5902. *
  5903. * @static
  5904. * @type {number}
  5905. * @default 1
  5906. */
  5907. Texture.DEFAULT_ANISOTROPY = 1;
  5908. /**
  5909. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  5910. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  5911. *
  5912. * - A point in 4D space.
  5913. * - A direction and length in 4D space. In three.js the length will
  5914. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  5915. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  5916. * - Any arbitrary ordered quadruplet of numbers.
  5917. *
  5918. * There are other things a 4D vector can be used to represent, however these
  5919. * are the most common uses in *three.js*.
  5920. *
  5921. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  5922. * the corresponding order.
  5923. * ```js
  5924. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  5925. *
  5926. * //no arguments; will be initialised to (0, 0, 0, 1)
  5927. * const b = new THREE.Vector4( );
  5928. *
  5929. * const d = a.dot( b );
  5930. * ```
  5931. */
  5932. class Vector4 {
  5933. /**
  5934. * Constructs a new 4D vector.
  5935. *
  5936. * @param {number} [x=0] - The x value of this vector.
  5937. * @param {number} [y=0] - The y value of this vector.
  5938. * @param {number} [z=0] - The z value of this vector.
  5939. * @param {number} [w=1] - The w value of this vector.
  5940. */
  5941. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  5942. /**
  5943. * This flag can be used for type testing.
  5944. *
  5945. * @type {boolean}
  5946. * @readonly
  5947. * @default true
  5948. */
  5949. Vector4.prototype.isVector4 = true;
  5950. /**
  5951. * The x value of this vector.
  5952. *
  5953. * @type {number}
  5954. */
  5955. this.x = x;
  5956. /**
  5957. * The y value of this vector.
  5958. *
  5959. * @type {number}
  5960. */
  5961. this.y = y;
  5962. /**
  5963. * The z value of this vector.
  5964. *
  5965. * @type {number}
  5966. */
  5967. this.z = z;
  5968. /**
  5969. * The w value of this vector.
  5970. *
  5971. * @type {number}
  5972. */
  5973. this.w = w;
  5974. }
  5975. /**
  5976. * Alias for {@link Vector4#z}.
  5977. *
  5978. * @type {number}
  5979. */
  5980. get width() {
  5981. return this.z;
  5982. }
  5983. set width( value ) {
  5984. this.z = value;
  5985. }
  5986. /**
  5987. * Alias for {@link Vector4#w}.
  5988. *
  5989. * @type {number}
  5990. */
  5991. get height() {
  5992. return this.w;
  5993. }
  5994. set height( value ) {
  5995. this.w = value;
  5996. }
  5997. /**
  5998. * Sets the vector components.
  5999. *
  6000. * @param {number} x - The value of the x component.
  6001. * @param {number} y - The value of the y component.
  6002. * @param {number} z - The value of the z component.
  6003. * @param {number} w - The value of the w component.
  6004. * @return {Vector4} A reference to this vector.
  6005. */
  6006. set( x, y, z, w ) {
  6007. this.x = x;
  6008. this.y = y;
  6009. this.z = z;
  6010. this.w = w;
  6011. return this;
  6012. }
  6013. /**
  6014. * Sets the vector components to the same value.
  6015. *
  6016. * @param {number} scalar - The value to set for all vector components.
  6017. * @return {Vector4} A reference to this vector.
  6018. */
  6019. setScalar( scalar ) {
  6020. this.x = scalar;
  6021. this.y = scalar;
  6022. this.z = scalar;
  6023. this.w = scalar;
  6024. return this;
  6025. }
  6026. /**
  6027. * Sets the vector's x component to the given value
  6028. *
  6029. * @param {number} x - The value to set.
  6030. * @return {Vector4} A reference to this vector.
  6031. */
  6032. setX( x ) {
  6033. this.x = x;
  6034. return this;
  6035. }
  6036. /**
  6037. * Sets the vector's y component to the given value
  6038. *
  6039. * @param {number} y - The value to set.
  6040. * @return {Vector4} A reference to this vector.
  6041. */
  6042. setY( y ) {
  6043. this.y = y;
  6044. return this;
  6045. }
  6046. /**
  6047. * Sets the vector's z component to the given value
  6048. *
  6049. * @param {number} z - The value to set.
  6050. * @return {Vector4} A reference to this vector.
  6051. */
  6052. setZ( z ) {
  6053. this.z = z;
  6054. return this;
  6055. }
  6056. /**
  6057. * Sets the vector's w component to the given value
  6058. *
  6059. * @param {number} w - The value to set.
  6060. * @return {Vector4} A reference to this vector.
  6061. */
  6062. setW( w ) {
  6063. this.w = w;
  6064. return this;
  6065. }
  6066. /**
  6067. * Allows to set a vector component with an index.
  6068. *
  6069. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6070. * `2` equals to z, `3` equals to w.
  6071. * @param {number} value - The value to set.
  6072. * @return {Vector4} A reference to this vector.
  6073. */
  6074. setComponent( index, value ) {
  6075. switch ( index ) {
  6076. case 0: this.x = value; break;
  6077. case 1: this.y = value; break;
  6078. case 2: this.z = value; break;
  6079. case 3: this.w = value; break;
  6080. default: throw new Error( 'index is out of range: ' + index );
  6081. }
  6082. return this;
  6083. }
  6084. /**
  6085. * Returns the value of the vector component which matches the given index.
  6086. *
  6087. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6088. * `2` equals to z, `3` equals to w.
  6089. * @return {number} A vector component value.
  6090. */
  6091. getComponent( index ) {
  6092. switch ( index ) {
  6093. case 0: return this.x;
  6094. case 1: return this.y;
  6095. case 2: return this.z;
  6096. case 3: return this.w;
  6097. default: throw new Error( 'index is out of range: ' + index );
  6098. }
  6099. }
  6100. /**
  6101. * Returns a new vector with copied values from this instance.
  6102. *
  6103. * @return {Vector4} A clone of this instance.
  6104. */
  6105. clone() {
  6106. return new this.constructor( this.x, this.y, this.z, this.w );
  6107. }
  6108. /**
  6109. * Copies the values of the given vector to this instance.
  6110. *
  6111. * @param {Vector3|Vector4} v - The vector to copy.
  6112. * @return {Vector4} A reference to this vector.
  6113. */
  6114. copy( v ) {
  6115. this.x = v.x;
  6116. this.y = v.y;
  6117. this.z = v.z;
  6118. this.w = ( v.w !== undefined ) ? v.w : 1;
  6119. return this;
  6120. }
  6121. /**
  6122. * Adds the given vector to this instance.
  6123. *
  6124. * @param {Vector4} v - The vector to add.
  6125. * @return {Vector4} A reference to this vector.
  6126. */
  6127. add( v ) {
  6128. this.x += v.x;
  6129. this.y += v.y;
  6130. this.z += v.z;
  6131. this.w += v.w;
  6132. return this;
  6133. }
  6134. /**
  6135. * Adds the given scalar value to all components of this instance.
  6136. *
  6137. * @param {number} s - The scalar to add.
  6138. * @return {Vector4} A reference to this vector.
  6139. */
  6140. addScalar( s ) {
  6141. this.x += s;
  6142. this.y += s;
  6143. this.z += s;
  6144. this.w += s;
  6145. return this;
  6146. }
  6147. /**
  6148. * Adds the given vectors and stores the result in this instance.
  6149. *
  6150. * @param {Vector4} a - The first vector.
  6151. * @param {Vector4} b - The second vector.
  6152. * @return {Vector4} A reference to this vector.
  6153. */
  6154. addVectors( a, b ) {
  6155. this.x = a.x + b.x;
  6156. this.y = a.y + b.y;
  6157. this.z = a.z + b.z;
  6158. this.w = a.w + b.w;
  6159. return this;
  6160. }
  6161. /**
  6162. * Adds the given vector scaled by the given factor to this instance.
  6163. *
  6164. * @param {Vector4} v - The vector.
  6165. * @param {number} s - The factor that scales `v`.
  6166. * @return {Vector4} A reference to this vector.
  6167. */
  6168. addScaledVector( v, s ) {
  6169. this.x += v.x * s;
  6170. this.y += v.y * s;
  6171. this.z += v.z * s;
  6172. this.w += v.w * s;
  6173. return this;
  6174. }
  6175. /**
  6176. * Subtracts the given vector from this instance.
  6177. *
  6178. * @param {Vector4} v - The vector to subtract.
  6179. * @return {Vector4} A reference to this vector.
  6180. */
  6181. sub( v ) {
  6182. this.x -= v.x;
  6183. this.y -= v.y;
  6184. this.z -= v.z;
  6185. this.w -= v.w;
  6186. return this;
  6187. }
  6188. /**
  6189. * Subtracts the given scalar value from all components of this instance.
  6190. *
  6191. * @param {number} s - The scalar to subtract.
  6192. * @return {Vector4} A reference to this vector.
  6193. */
  6194. subScalar( s ) {
  6195. this.x -= s;
  6196. this.y -= s;
  6197. this.z -= s;
  6198. this.w -= s;
  6199. return this;
  6200. }
  6201. /**
  6202. * Subtracts the given vectors and stores the result in this instance.
  6203. *
  6204. * @param {Vector4} a - The first vector.
  6205. * @param {Vector4} b - The second vector.
  6206. * @return {Vector4} A reference to this vector.
  6207. */
  6208. subVectors( a, b ) {
  6209. this.x = a.x - b.x;
  6210. this.y = a.y - b.y;
  6211. this.z = a.z - b.z;
  6212. this.w = a.w - b.w;
  6213. return this;
  6214. }
  6215. /**
  6216. * Multiplies the given vector with this instance.
  6217. *
  6218. * @param {Vector4} v - The vector to multiply.
  6219. * @return {Vector4} A reference to this vector.
  6220. */
  6221. multiply( v ) {
  6222. this.x *= v.x;
  6223. this.y *= v.y;
  6224. this.z *= v.z;
  6225. this.w *= v.w;
  6226. return this;
  6227. }
  6228. /**
  6229. * Multiplies the given scalar value with all components of this instance.
  6230. *
  6231. * @param {number} scalar - The scalar to multiply.
  6232. * @return {Vector4} A reference to this vector.
  6233. */
  6234. multiplyScalar( scalar ) {
  6235. this.x *= scalar;
  6236. this.y *= scalar;
  6237. this.z *= scalar;
  6238. this.w *= scalar;
  6239. return this;
  6240. }
  6241. /**
  6242. * Multiplies this vector with the given 4x4 matrix.
  6243. *
  6244. * @param {Matrix4} m - The 4x4 matrix.
  6245. * @return {Vector4} A reference to this vector.
  6246. */
  6247. applyMatrix4( m ) {
  6248. const x = this.x, y = this.y, z = this.z, w = this.w;
  6249. const e = m.elements;
  6250. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6251. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6252. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6253. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6254. return this;
  6255. }
  6256. /**
  6257. * Divides this instance by the given vector.
  6258. *
  6259. * @param {Vector4} v - The vector to divide.
  6260. * @return {Vector4} A reference to this vector.
  6261. */
  6262. divide( v ) {
  6263. this.x /= v.x;
  6264. this.y /= v.y;
  6265. this.z /= v.z;
  6266. this.w /= v.w;
  6267. return this;
  6268. }
  6269. /**
  6270. * Divides this vector by the given scalar.
  6271. *
  6272. * @param {number} scalar - The scalar to divide.
  6273. * @return {Vector4} A reference to this vector.
  6274. */
  6275. divideScalar( scalar ) {
  6276. return this.multiplyScalar( 1 / scalar );
  6277. }
  6278. /**
  6279. * Sets the x, y and z components of this
  6280. * vector to the quaternion's axis and w to the angle.
  6281. *
  6282. * @param {Quaternion} q - The Quaternion to set.
  6283. * @return {Vector4} A reference to this vector.
  6284. */
  6285. setAxisAngleFromQuaternion( q ) {
  6286. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6287. // q is assumed to be normalized
  6288. this.w = 2 * Math.acos( q.w );
  6289. const s = Math.sqrt( 1 - q.w * q.w );
  6290. if ( s < 0.0001 ) {
  6291. this.x = 1;
  6292. this.y = 0;
  6293. this.z = 0;
  6294. } else {
  6295. this.x = q.x / s;
  6296. this.y = q.y / s;
  6297. this.z = q.z / s;
  6298. }
  6299. return this;
  6300. }
  6301. /**
  6302. * Sets the x, y and z components of this
  6303. * vector to the axis of rotation and w to the angle.
  6304. *
  6305. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  6306. * @return {Vector4} A reference to this vector.
  6307. */
  6308. setAxisAngleFromRotationMatrix( m ) {
  6309. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6310. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6311. let angle, x, y, z; // variables for result
  6312. const epsilon = 0.01, // margin to allow for rounding errors
  6313. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6314. te = m.elements,
  6315. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6316. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6317. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6318. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6319. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6320. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6321. // singularity found
  6322. // first check for identity matrix which must have +1 for all terms
  6323. // in leading diagonal and zero in other terms
  6324. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6325. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6326. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6327. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6328. // this singularity is identity matrix so angle = 0
  6329. this.set( 1, 0, 0, 0 );
  6330. return this; // zero angle, arbitrary axis
  6331. }
  6332. // otherwise this singularity is angle = 180
  6333. angle = Math.PI;
  6334. const xx = ( m11 + 1 ) / 2;
  6335. const yy = ( m22 + 1 ) / 2;
  6336. const zz = ( m33 + 1 ) / 2;
  6337. const xy = ( m12 + m21 ) / 4;
  6338. const xz = ( m13 + m31 ) / 4;
  6339. const yz = ( m23 + m32 ) / 4;
  6340. if ( ( xx > yy ) && ( xx > zz ) ) {
  6341. // m11 is the largest diagonal term
  6342. if ( xx < epsilon ) {
  6343. x = 0;
  6344. y = 0.707106781;
  6345. z = 0.707106781;
  6346. } else {
  6347. x = Math.sqrt( xx );
  6348. y = xy / x;
  6349. z = xz / x;
  6350. }
  6351. } else if ( yy > zz ) {
  6352. // m22 is the largest diagonal term
  6353. if ( yy < epsilon ) {
  6354. x = 0.707106781;
  6355. y = 0;
  6356. z = 0.707106781;
  6357. } else {
  6358. y = Math.sqrt( yy );
  6359. x = xy / y;
  6360. z = yz / y;
  6361. }
  6362. } else {
  6363. // m33 is the largest diagonal term so base result on this
  6364. if ( zz < epsilon ) {
  6365. x = 0.707106781;
  6366. y = 0.707106781;
  6367. z = 0;
  6368. } else {
  6369. z = Math.sqrt( zz );
  6370. x = xz / z;
  6371. y = yz / z;
  6372. }
  6373. }
  6374. this.set( x, y, z, angle );
  6375. return this; // return 180 deg rotation
  6376. }
  6377. // as we have reached here there are no singularities so we can handle normally
  6378. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6379. ( m13 - m31 ) * ( m13 - m31 ) +
  6380. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6381. if ( Math.abs( s ) < 0.001 ) s = 1;
  6382. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6383. // caught by singularity test above, but I've left it in just in case
  6384. this.x = ( m32 - m23 ) / s;
  6385. this.y = ( m13 - m31 ) / s;
  6386. this.z = ( m21 - m12 ) / s;
  6387. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6388. return this;
  6389. }
  6390. /**
  6391. * Sets the vector components to the position elements of the
  6392. * given transformation matrix.
  6393. *
  6394. * @param {Matrix4} m - The 4x4 matrix.
  6395. * @return {Vector4} A reference to this vector.
  6396. */
  6397. setFromMatrixPosition( m ) {
  6398. const e = m.elements;
  6399. this.x = e[ 12 ];
  6400. this.y = e[ 13 ];
  6401. this.z = e[ 14 ];
  6402. this.w = e[ 15 ];
  6403. return this;
  6404. }
  6405. /**
  6406. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  6407. * value, replace that value with the corresponding min value.
  6408. *
  6409. * @param {Vector4} v - The vector.
  6410. * @return {Vector4} A reference to this vector.
  6411. */
  6412. min( v ) {
  6413. this.x = Math.min( this.x, v.x );
  6414. this.y = Math.min( this.y, v.y );
  6415. this.z = Math.min( this.z, v.z );
  6416. this.w = Math.min( this.w, v.w );
  6417. return this;
  6418. }
  6419. /**
  6420. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  6421. * value, replace that value with the corresponding max value.
  6422. *
  6423. * @param {Vector4} v - The vector.
  6424. * @return {Vector4} A reference to this vector.
  6425. */
  6426. max( v ) {
  6427. this.x = Math.max( this.x, v.x );
  6428. this.y = Math.max( this.y, v.y );
  6429. this.z = Math.max( this.z, v.z );
  6430. this.w = Math.max( this.w, v.w );
  6431. return this;
  6432. }
  6433. /**
  6434. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  6435. * value, it is replaced by the corresponding value.
  6436. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  6437. * it is replaced by the corresponding value.
  6438. *
  6439. * @param {Vector4} min - The minimum x, y and z values.
  6440. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  6441. * @return {Vector4} A reference to this vector.
  6442. */
  6443. clamp( min, max ) {
  6444. // assumes min < max, componentwise
  6445. this.x = clamp( this.x, min.x, max.x );
  6446. this.y = clamp( this.y, min.y, max.y );
  6447. this.z = clamp( this.z, min.z, max.z );
  6448. this.w = clamp( this.w, min.w, max.w );
  6449. return this;
  6450. }
  6451. /**
  6452. * If this vector's x, y, z or w values are greater than the max value, they are
  6453. * replaced by the max value.
  6454. * If this vector's x, y, z or w values are less than the min value, they are
  6455. * replaced by the min value.
  6456. *
  6457. * @param {number} minVal - The minimum value the components will be clamped to.
  6458. * @param {number} maxVal - The maximum value the components will be clamped to.
  6459. * @return {Vector4} A reference to this vector.
  6460. */
  6461. clampScalar( minVal, maxVal ) {
  6462. this.x = clamp( this.x, minVal, maxVal );
  6463. this.y = clamp( this.y, minVal, maxVal );
  6464. this.z = clamp( this.z, minVal, maxVal );
  6465. this.w = clamp( this.w, minVal, maxVal );
  6466. return this;
  6467. }
  6468. /**
  6469. * If this vector's length is greater than the max value, it is replaced by
  6470. * the max value.
  6471. * If this vector's length is less than the min value, it is replaced by the
  6472. * min value.
  6473. *
  6474. * @param {number} min - The minimum value the vector length will be clamped to.
  6475. * @param {number} max - The maximum value the vector length will be clamped to.
  6476. * @return {Vector4} A reference to this vector.
  6477. */
  6478. clampLength( min, max ) {
  6479. const length = this.length();
  6480. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6481. }
  6482. /**
  6483. * The components of this vector are rounded down to the nearest integer value.
  6484. *
  6485. * @return {Vector4} A reference to this vector.
  6486. */
  6487. floor() {
  6488. this.x = Math.floor( this.x );
  6489. this.y = Math.floor( this.y );
  6490. this.z = Math.floor( this.z );
  6491. this.w = Math.floor( this.w );
  6492. return this;
  6493. }
  6494. /**
  6495. * The components of this vector are rounded up to the nearest integer value.
  6496. *
  6497. * @return {Vector4} A reference to this vector.
  6498. */
  6499. ceil() {
  6500. this.x = Math.ceil( this.x );
  6501. this.y = Math.ceil( this.y );
  6502. this.z = Math.ceil( this.z );
  6503. this.w = Math.ceil( this.w );
  6504. return this;
  6505. }
  6506. /**
  6507. * The components of this vector are rounded to the nearest integer value
  6508. *
  6509. * @return {Vector4} A reference to this vector.
  6510. */
  6511. round() {
  6512. this.x = Math.round( this.x );
  6513. this.y = Math.round( this.y );
  6514. this.z = Math.round( this.z );
  6515. this.w = Math.round( this.w );
  6516. return this;
  6517. }
  6518. /**
  6519. * The components of this vector are rounded towards zero (up if negative,
  6520. * down if positive) to an integer value.
  6521. *
  6522. * @return {Vector4} A reference to this vector.
  6523. */
  6524. roundToZero() {
  6525. this.x = Math.trunc( this.x );
  6526. this.y = Math.trunc( this.y );
  6527. this.z = Math.trunc( this.z );
  6528. this.w = Math.trunc( this.w );
  6529. return this;
  6530. }
  6531. /**
  6532. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  6533. *
  6534. * @return {Vector4} A reference to this vector.
  6535. */
  6536. negate() {
  6537. this.x = - this.x;
  6538. this.y = - this.y;
  6539. this.z = - this.z;
  6540. this.w = - this.w;
  6541. return this;
  6542. }
  6543. /**
  6544. * Calculates the dot product of the given vector with this instance.
  6545. *
  6546. * @param {Vector4} v - The vector to compute the dot product with.
  6547. * @return {number} The result of the dot product.
  6548. */
  6549. dot( v ) {
  6550. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6551. }
  6552. /**
  6553. * Computes the square of the Euclidean length (straight-line length) from
  6554. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  6555. * compare the length squared instead as it is slightly more efficient to calculate.
  6556. *
  6557. * @return {number} The square length of this vector.
  6558. */
  6559. lengthSq() {
  6560. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6561. }
  6562. /**
  6563. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  6564. *
  6565. * @return {number} The length of this vector.
  6566. */
  6567. length() {
  6568. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6569. }
  6570. /**
  6571. * Computes the Manhattan length of this vector.
  6572. *
  6573. * @return {number} The length of this vector.
  6574. */
  6575. manhattanLength() {
  6576. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6577. }
  6578. /**
  6579. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6580. * with the same direction as this one, but with a vector length of `1`.
  6581. *
  6582. * @return {Vector4} A reference to this vector.
  6583. */
  6584. normalize() {
  6585. return this.divideScalar( this.length() || 1 );
  6586. }
  6587. /**
  6588. * Sets this vector to a vector with the same direction as this one, but
  6589. * with the specified length.
  6590. *
  6591. * @param {number} length - The new length of this vector.
  6592. * @return {Vector4} A reference to this vector.
  6593. */
  6594. setLength( length ) {
  6595. return this.normalize().multiplyScalar( length );
  6596. }
  6597. /**
  6598. * Linearly interpolates between the given vector and this instance, where
  6599. * alpha is the percent distance along the line - alpha = 0 will be this
  6600. * vector, and alpha = 1 will be the given one.
  6601. *
  6602. * @param {Vector4} v - The vector to interpolate towards.
  6603. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6604. * @return {Vector4} A reference to this vector.
  6605. */
  6606. lerp( v, alpha ) {
  6607. this.x += ( v.x - this.x ) * alpha;
  6608. this.y += ( v.y - this.y ) * alpha;
  6609. this.z += ( v.z - this.z ) * alpha;
  6610. this.w += ( v.w - this.w ) * alpha;
  6611. return this;
  6612. }
  6613. /**
  6614. * Linearly interpolates between the given vectors, where alpha is the percent
  6615. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6616. * be the second one. The result is stored in this instance.
  6617. *
  6618. * @param {Vector4} v1 - The first vector.
  6619. * @param {Vector4} v2 - The second vector.
  6620. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6621. * @return {Vector4} A reference to this vector.
  6622. */
  6623. lerpVectors( v1, v2, alpha ) {
  6624. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6625. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6626. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6627. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  6628. return this;
  6629. }
  6630. /**
  6631. * Returns `true` if this vector is equal with the given one.
  6632. *
  6633. * @param {Vector4} v - The vector to test for equality.
  6634. * @return {boolean} Whether this vector is equal with the given one.
  6635. */
  6636. equals( v ) {
  6637. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6638. }
  6639. /**
  6640. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  6641. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  6642. *
  6643. * @param {Array<number>} array - An array holding the vector component values.
  6644. * @param {number} [offset=0] - The offset into the array.
  6645. * @return {Vector4} A reference to this vector.
  6646. */
  6647. fromArray( array, offset = 0 ) {
  6648. this.x = array[ offset ];
  6649. this.y = array[ offset + 1 ];
  6650. this.z = array[ offset + 2 ];
  6651. this.w = array[ offset + 3 ];
  6652. return this;
  6653. }
  6654. /**
  6655. * Writes the components of this vector to the given array. If no array is provided,
  6656. * the method returns a new instance.
  6657. *
  6658. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  6659. * @param {number} [offset=0] - Index of the first element in the array.
  6660. * @return {Array<number>} The vector components.
  6661. */
  6662. toArray( array = [], offset = 0 ) {
  6663. array[ offset ] = this.x;
  6664. array[ offset + 1 ] = this.y;
  6665. array[ offset + 2 ] = this.z;
  6666. array[ offset + 3 ] = this.w;
  6667. return array;
  6668. }
  6669. /**
  6670. * Sets the components of this vector from the given buffer attribute.
  6671. *
  6672. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  6673. * @param {number} index - The index into the attribute.
  6674. * @return {Vector4} A reference to this vector.
  6675. */
  6676. fromBufferAttribute( attribute, index ) {
  6677. this.x = attribute.getX( index );
  6678. this.y = attribute.getY( index );
  6679. this.z = attribute.getZ( index );
  6680. this.w = attribute.getW( index );
  6681. return this;
  6682. }
  6683. /**
  6684. * Sets each component of this vector to a pseudo-random value between `0` and
  6685. * `1`, excluding `1`.
  6686. *
  6687. * @return {Vector4} A reference to this vector.
  6688. */
  6689. random() {
  6690. this.x = Math.random();
  6691. this.y = Math.random();
  6692. this.z = Math.random();
  6693. this.w = Math.random();
  6694. return this;
  6695. }
  6696. *[ Symbol.iterator ]() {
  6697. yield this.x;
  6698. yield this.y;
  6699. yield this.z;
  6700. yield this.w;
  6701. }
  6702. }
  6703. /**
  6704. * A render target is a buffer where the video card draws pixels for a scene
  6705. * that is being rendered in the background. It is used in different effects,
  6706. * such as applying postprocessing to a rendered image before displaying it
  6707. * on the screen.
  6708. *
  6709. * @augments EventDispatcher
  6710. */
  6711. class RenderTarget extends EventDispatcher {
  6712. /**
  6713. * Render target options.
  6714. *
  6715. * @typedef {Object} RenderTarget~Options
  6716. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  6717. * @property {number} [magFilter=LinearFilter] - The mag filter.
  6718. * @property {number} [minFilter=LinearFilter] - The min filter.
  6719. * @property {number} [format=RGBAFormat] - The texture format.
  6720. * @property {number} [type=UnsignedByteType] - The texture type.
  6721. * @property {?string} [internalFormat=null] - The texture's internal format.
  6722. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6723. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6724. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  6725. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  6726. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  6727. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  6728. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  6729. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  6730. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  6731. * @property {number} [samples=0] - The MSAA samples count.
  6732. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  6733. * @property {number} [depth=1] - The texture depth.
  6734. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering.
  6735. */
  6736. /**
  6737. * Constructs a new render target.
  6738. *
  6739. * @param {number} [width=1] - The width of the render target.
  6740. * @param {number} [height=1] - The height of the render target.
  6741. * @param {RenderTarget~Options} [options] - The configuration object.
  6742. */
  6743. constructor( width = 1, height = 1, options = {} ) {
  6744. super();
  6745. options = Object.assign( {
  6746. generateMipmaps: false,
  6747. internalFormat: null,
  6748. minFilter: LinearFilter,
  6749. depthBuffer: true,
  6750. stencilBuffer: false,
  6751. resolveDepthBuffer: true,
  6752. resolveStencilBuffer: true,
  6753. depthTexture: null,
  6754. samples: 0,
  6755. count: 1,
  6756. depth: 1,
  6757. multiview: false
  6758. }, options );
  6759. /**
  6760. * This flag can be used for type testing.
  6761. *
  6762. * @type {boolean}
  6763. * @readonly
  6764. * @default true
  6765. */
  6766. this.isRenderTarget = true;
  6767. /**
  6768. * The width of the render target.
  6769. *
  6770. * @type {number}
  6771. * @default 1
  6772. */
  6773. this.width = width;
  6774. /**
  6775. * The height of the render target.
  6776. *
  6777. * @type {number}
  6778. * @default 1
  6779. */
  6780. this.height = height;
  6781. /**
  6782. * The depth of the render target.
  6783. *
  6784. * @type {number}
  6785. * @default 1
  6786. */
  6787. this.depth = options.depth;
  6788. /**
  6789. * A rectangular area inside the render target's viewport. Fragments that are
  6790. * outside the area will be discarded.
  6791. *
  6792. * @type {Vector4}
  6793. * @default (0,0,width,height)
  6794. */
  6795. this.scissor = new Vector4( 0, 0, width, height );
  6796. /**
  6797. * Indicates whether the scissor test should be enabled when rendering into
  6798. * this render target or not.
  6799. *
  6800. * @type {boolean}
  6801. * @default false
  6802. */
  6803. this.scissorTest = false;
  6804. /**
  6805. * A rectangular area representing the render target's viewport.
  6806. *
  6807. * @type {Vector4}
  6808. * @default (0,0,width,height)
  6809. */
  6810. this.viewport = new Vector4( 0, 0, width, height );
  6811. const image = { width: width, height: height, depth: options.depth };
  6812. const texture = new Texture( image );
  6813. /**
  6814. * An array of textures. Each color attachment is represented as a separate texture.
  6815. * Has at least a single entry for the default color attachment.
  6816. *
  6817. * @type {Array<Texture>}
  6818. */
  6819. this.textures = [];
  6820. const count = options.count;
  6821. for ( let i = 0; i < count; i ++ ) {
  6822. this.textures[ i ] = texture.clone();
  6823. this.textures[ i ].isRenderTargetTexture = true;
  6824. this.textures[ i ].renderTarget = this;
  6825. }
  6826. this._setTextureOptions( options );
  6827. /**
  6828. * Whether to allocate a depth buffer or not.
  6829. *
  6830. * @type {boolean}
  6831. * @default true
  6832. */
  6833. this.depthBuffer = options.depthBuffer;
  6834. /**
  6835. * Whether to allocate a stencil buffer or not.
  6836. *
  6837. * @type {boolean}
  6838. * @default false
  6839. */
  6840. this.stencilBuffer = options.stencilBuffer;
  6841. /**
  6842. * Whether to resolve the depth buffer or not.
  6843. *
  6844. * @type {boolean}
  6845. * @default true
  6846. */
  6847. this.resolveDepthBuffer = options.resolveDepthBuffer;
  6848. /**
  6849. * Whether to resolve the stencil buffer or not.
  6850. *
  6851. * @type {boolean}
  6852. * @default true
  6853. */
  6854. this.resolveStencilBuffer = options.resolveStencilBuffer;
  6855. this._depthTexture = null;
  6856. this.depthTexture = options.depthTexture;
  6857. /**
  6858. * The number of MSAA samples.
  6859. *
  6860. * A value of `0` disables MSAA.
  6861. *
  6862. * @type {number}
  6863. * @default 0
  6864. */
  6865. this.samples = options.samples;
  6866. /**
  6867. * Whether to this target is used in multiview rendering.
  6868. *
  6869. * @type {boolean}
  6870. * @default false
  6871. */
  6872. this.multiview = options.multiview;
  6873. }
  6874. _setTextureOptions( options = {} ) {
  6875. const values = {
  6876. minFilter: LinearFilter,
  6877. generateMipmaps: false,
  6878. flipY: false,
  6879. internalFormat: null
  6880. };
  6881. if ( options.mapping !== undefined ) values.mapping = options.mapping;
  6882. if ( options.wrapS !== undefined ) values.wrapS = options.wrapS;
  6883. if ( options.wrapT !== undefined ) values.wrapT = options.wrapT;
  6884. if ( options.wrapR !== undefined ) values.wrapR = options.wrapR;
  6885. if ( options.magFilter !== undefined ) values.magFilter = options.magFilter;
  6886. if ( options.minFilter !== undefined ) values.minFilter = options.minFilter;
  6887. if ( options.format !== undefined ) values.format = options.format;
  6888. if ( options.type !== undefined ) values.type = options.type;
  6889. if ( options.anisotropy !== undefined ) values.anisotropy = options.anisotropy;
  6890. if ( options.colorSpace !== undefined ) values.colorSpace = options.colorSpace;
  6891. if ( options.flipY !== undefined ) values.flipY = options.flipY;
  6892. if ( options.generateMipmaps !== undefined ) values.generateMipmaps = options.generateMipmaps;
  6893. if ( options.internalFormat !== undefined ) values.internalFormat = options.internalFormat;
  6894. for ( let i = 0; i < this.textures.length; i ++ ) {
  6895. const texture = this.textures[ i ];
  6896. texture.setValues( values );
  6897. }
  6898. }
  6899. /**
  6900. * The texture representing the default color attachment.
  6901. *
  6902. * @type {Texture}
  6903. */
  6904. get texture() {
  6905. return this.textures[ 0 ];
  6906. }
  6907. set texture( value ) {
  6908. this.textures[ 0 ] = value;
  6909. }
  6910. set depthTexture( current ) {
  6911. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  6912. if ( current !== null ) current.renderTarget = this;
  6913. this._depthTexture = current;
  6914. }
  6915. /**
  6916. * Instead of saving the depth in a renderbuffer, a texture
  6917. * can be used instead which is useful for further processing
  6918. * e.g. in context of post-processing.
  6919. *
  6920. * @type {?DepthTexture}
  6921. * @default null
  6922. */
  6923. get depthTexture() {
  6924. return this._depthTexture;
  6925. }
  6926. /**
  6927. * Sets the size of this render target.
  6928. *
  6929. * @param {number} width - The width.
  6930. * @param {number} height - The height.
  6931. * @param {number} [depth=1] - The depth.
  6932. */
  6933. setSize( width, height, depth = 1 ) {
  6934. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  6935. this.width = width;
  6936. this.height = height;
  6937. this.depth = depth;
  6938. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  6939. this.textures[ i ].image.width = width;
  6940. this.textures[ i ].image.height = height;
  6941. this.textures[ i ].image.depth = depth;
  6942. this.textures[ i ].isArrayTexture = this.textures[ i ].image.depth > 1;
  6943. }
  6944. this.dispose();
  6945. }
  6946. this.viewport.set( 0, 0, width, height );
  6947. this.scissor.set( 0, 0, width, height );
  6948. }
  6949. /**
  6950. * Returns a new render target with copied values from this instance.
  6951. *
  6952. * @return {RenderTarget} A clone of this instance.
  6953. */
  6954. clone() {
  6955. return new this.constructor().copy( this );
  6956. }
  6957. /**
  6958. * Copies the settings of the given render target. This is a structural copy so
  6959. * no resources are shared between render targets after the copy. That includes
  6960. * all MRT textures and the depth texture.
  6961. *
  6962. * @param {RenderTarget} source - The render target to copy.
  6963. * @return {RenderTarget} A reference to this instance.
  6964. */
  6965. copy( source ) {
  6966. this.width = source.width;
  6967. this.height = source.height;
  6968. this.depth = source.depth;
  6969. this.scissor.copy( source.scissor );
  6970. this.scissorTest = source.scissorTest;
  6971. this.viewport.copy( source.viewport );
  6972. this.textures.length = 0;
  6973. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  6974. this.textures[ i ] = source.textures[ i ].clone();
  6975. this.textures[ i ].isRenderTargetTexture = true;
  6976. this.textures[ i ].renderTarget = this;
  6977. // ensure image object is not shared, see #20328
  6978. const image = Object.assign( {}, source.textures[ i ].image );
  6979. this.textures[ i ].source = new Source( image );
  6980. }
  6981. this.depthBuffer = source.depthBuffer;
  6982. this.stencilBuffer = source.stencilBuffer;
  6983. this.resolveDepthBuffer = source.resolveDepthBuffer;
  6984. this.resolveStencilBuffer = source.resolveStencilBuffer;
  6985. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  6986. this.samples = source.samples;
  6987. return this;
  6988. }
  6989. /**
  6990. * Frees the GPU-related resources allocated by this instance. Call this
  6991. * method whenever this instance is no longer used in your app.
  6992. *
  6993. * @fires RenderTarget#dispose
  6994. */
  6995. dispose() {
  6996. this.dispatchEvent( { type: 'dispose' } );
  6997. }
  6998. }
  6999. /**
  7000. * A render target used in context of {@link WebGLRenderer}.
  7001. *
  7002. * @augments RenderTarget
  7003. */
  7004. class WebGLRenderTarget extends RenderTarget {
  7005. /**
  7006. * Constructs a new 3D render target.
  7007. *
  7008. * @param {number} [width=1] - The width of the render target.
  7009. * @param {number} [height=1] - The height of the render target.
  7010. * @param {RenderTarget~Options} [options] - The configuration object.
  7011. */
  7012. constructor( width = 1, height = 1, options = {} ) {
  7013. super( width, height, options );
  7014. /**
  7015. * This flag can be used for type testing.
  7016. *
  7017. * @type {boolean}
  7018. * @readonly
  7019. * @default true
  7020. */
  7021. this.isWebGLRenderTarget = true;
  7022. }
  7023. }
  7024. /**
  7025. * Creates an array of textures directly from raw buffer data.
  7026. *
  7027. * @augments Texture
  7028. */
  7029. class DataArrayTexture extends Texture {
  7030. /**
  7031. * Constructs a new data array texture.
  7032. *
  7033. * @param {?TypedArray} [data=null] - The buffer data.
  7034. * @param {number} [width=1] - The width of the texture.
  7035. * @param {number} [height=1] - The height of the texture.
  7036. * @param {number} [depth=1] - The depth of the texture.
  7037. */
  7038. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7039. super( null );
  7040. /**
  7041. * This flag can be used for type testing.
  7042. *
  7043. * @type {boolean}
  7044. * @readonly
  7045. * @default true
  7046. */
  7047. this.isDataArrayTexture = true;
  7048. /**
  7049. * The image definition of a data texture.
  7050. *
  7051. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7052. */
  7053. this.image = { data, width, height, depth };
  7054. /**
  7055. * How the texture is sampled when a texel covers more than one pixel.
  7056. *
  7057. * Overwritten and set to `NearestFilter` by default.
  7058. *
  7059. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7060. * @default NearestFilter
  7061. */
  7062. this.magFilter = NearestFilter;
  7063. /**
  7064. * How the texture is sampled when a texel covers less than one pixel.
  7065. *
  7066. * Overwritten and set to `NearestFilter` by default.
  7067. *
  7068. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7069. * @default NearestFilter
  7070. */
  7071. this.minFilter = NearestFilter;
  7072. /**
  7073. * This defines how the texture is wrapped in the depth and corresponds to
  7074. * *W* in UVW mapping.
  7075. *
  7076. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7077. * @default ClampToEdgeWrapping
  7078. */
  7079. this.wrapR = ClampToEdgeWrapping;
  7080. /**
  7081. * Whether to generate mipmaps (if possible) for a texture.
  7082. *
  7083. * Overwritten and set to `false` by default.
  7084. *
  7085. * @type {boolean}
  7086. * @default false
  7087. */
  7088. this.generateMipmaps = false;
  7089. /**
  7090. * If set to `true`, the texture is flipped along the vertical axis when
  7091. * uploaded to the GPU.
  7092. *
  7093. * Overwritten and set to `false` by default.
  7094. *
  7095. * @type {boolean}
  7096. * @default false
  7097. */
  7098. this.flipY = false;
  7099. /**
  7100. * Specifies the alignment requirements for the start of each pixel row in memory.
  7101. *
  7102. * Overwritten and set to `1` by default.
  7103. *
  7104. * @type {boolean}
  7105. * @default 1
  7106. */
  7107. this.unpackAlignment = 1;
  7108. /**
  7109. * A set of all layers which need to be updated in the texture.
  7110. *
  7111. * @type {Set<number>}
  7112. */
  7113. this.layerUpdates = new Set();
  7114. }
  7115. /**
  7116. * Describes that a specific layer of the texture needs to be updated.
  7117. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  7118. * entire data texture array is sent to the GPU. Marking specific
  7119. * layers will only transmit subsets of all mipmaps associated with a
  7120. * specific depth in the array which is often much more performant.
  7121. *
  7122. * @param {number} layerIndex - The layer index that should be updated.
  7123. */
  7124. addLayerUpdate( layerIndex ) {
  7125. this.layerUpdates.add( layerIndex );
  7126. }
  7127. /**
  7128. * Resets the layer updates registry.
  7129. */
  7130. clearLayerUpdates() {
  7131. this.layerUpdates.clear();
  7132. }
  7133. }
  7134. /**
  7135. * An array render target used in context of {@link WebGLRenderer}.
  7136. *
  7137. * @augments WebGLRenderTarget
  7138. */
  7139. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  7140. /**
  7141. * Constructs a new array render target.
  7142. *
  7143. * @param {number} [width=1] - The width of the render target.
  7144. * @param {number} [height=1] - The height of the render target.
  7145. * @param {number} [depth=1] - The height of the render target.
  7146. * @param {RenderTarget~Options} [options] - The configuration object.
  7147. */
  7148. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7149. super( width, height, options );
  7150. /**
  7151. * This flag can be used for type testing.
  7152. *
  7153. * @type {boolean}
  7154. * @readonly
  7155. * @default true
  7156. */
  7157. this.isWebGLArrayRenderTarget = true;
  7158. this.depth = depth;
  7159. /**
  7160. * Overwritten with a different texture type.
  7161. *
  7162. * @type {DataArrayTexture}
  7163. */
  7164. this.texture = new DataArrayTexture( null, width, height, depth );
  7165. this._setTextureOptions( options );
  7166. this.texture.isRenderTargetTexture = true;
  7167. }
  7168. }
  7169. /**
  7170. * Creates a three-dimensional texture from raw data, with parameters to
  7171. * divide it into width, height, and depth.
  7172. *
  7173. * @augments Texture
  7174. */
  7175. class Data3DTexture extends Texture {
  7176. /**
  7177. * Constructs a new data array texture.
  7178. *
  7179. * @param {?TypedArray} [data=null] - The buffer data.
  7180. * @param {number} [width=1] - The width of the texture.
  7181. * @param {number} [height=1] - The height of the texture.
  7182. * @param {number} [depth=1] - The depth of the texture.
  7183. */
  7184. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7185. // We're going to add .setXXX() methods for setting properties later.
  7186. // Users can still set in Data3DTexture directly.
  7187. //
  7188. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  7189. // texture.anisotropy = 16;
  7190. //
  7191. // See #14839
  7192. super( null );
  7193. /**
  7194. * This flag can be used for type testing.
  7195. *
  7196. * @type {boolean}
  7197. * @readonly
  7198. * @default true
  7199. */
  7200. this.isData3DTexture = true;
  7201. /**
  7202. * The image definition of a data texture.
  7203. *
  7204. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7205. */
  7206. this.image = { data, width, height, depth };
  7207. /**
  7208. * How the texture is sampled when a texel covers more than one pixel.
  7209. *
  7210. * Overwritten and set to `NearestFilter` by default.
  7211. *
  7212. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7213. * @default NearestFilter
  7214. */
  7215. this.magFilter = NearestFilter;
  7216. /**
  7217. * How the texture is sampled when a texel covers less than one pixel.
  7218. *
  7219. * Overwritten and set to `NearestFilter` by default.
  7220. *
  7221. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7222. * @default NearestFilter
  7223. */
  7224. this.minFilter = NearestFilter;
  7225. /**
  7226. * This defines how the texture is wrapped in the depth and corresponds to
  7227. * *W* in UVW mapping.
  7228. *
  7229. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7230. * @default ClampToEdgeWrapping
  7231. */
  7232. this.wrapR = ClampToEdgeWrapping;
  7233. /**
  7234. * Whether to generate mipmaps (if possible) for a texture.
  7235. *
  7236. * Overwritten and set to `false` by default.
  7237. *
  7238. * @type {boolean}
  7239. * @default false
  7240. */
  7241. this.generateMipmaps = false;
  7242. /**
  7243. * If set to `true`, the texture is flipped along the vertical axis when
  7244. * uploaded to the GPU.
  7245. *
  7246. * Overwritten and set to `false` by default.
  7247. *
  7248. * @type {boolean}
  7249. * @default false
  7250. */
  7251. this.flipY = false;
  7252. /**
  7253. * Specifies the alignment requirements for the start of each pixel row in memory.
  7254. *
  7255. * Overwritten and set to `1` by default.
  7256. *
  7257. * @type {boolean}
  7258. * @default 1
  7259. */
  7260. this.unpackAlignment = 1;
  7261. }
  7262. }
  7263. /**
  7264. * A 3D render target used in context of {@link WebGLRenderer}.
  7265. *
  7266. * @augments WebGLRenderTarget
  7267. */
  7268. class WebGL3DRenderTarget extends WebGLRenderTarget {
  7269. /**
  7270. * Constructs a new 3D render target.
  7271. *
  7272. * @param {number} [width=1] - The width of the render target.
  7273. * @param {number} [height=1] - The height of the render target.
  7274. * @param {number} [depth=1] - The height of the render target.
  7275. * @param {RenderTarget~Options} [options] - The configuration object.
  7276. */
  7277. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7278. super( width, height, options );
  7279. /**
  7280. * This flag can be used for type testing.
  7281. *
  7282. * @type {boolean}
  7283. * @readonly
  7284. * @default true
  7285. */
  7286. this.isWebGL3DRenderTarget = true;
  7287. this.depth = depth;
  7288. /**
  7289. * Overwritten with a different texture type.
  7290. *
  7291. * @type {Data3DTexture}
  7292. */
  7293. this.texture = new Data3DTexture( null, width, height, depth );
  7294. this._setTextureOptions( options );
  7295. this.texture.isRenderTargetTexture = true;
  7296. }
  7297. }
  7298. /**
  7299. * Represents an axis-aligned bounding box (AABB) in 3D space.
  7300. */
  7301. class Box3 {
  7302. /**
  7303. * Constructs a new bounding box.
  7304. *
  7305. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  7306. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  7307. */
  7308. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  7309. /**
  7310. * This flag can be used for type testing.
  7311. *
  7312. * @type {boolean}
  7313. * @readonly
  7314. * @default true
  7315. */
  7316. this.isBox3 = true;
  7317. /**
  7318. * The lower boundary of the box.
  7319. *
  7320. * @type {Vector3}
  7321. */
  7322. this.min = min;
  7323. /**
  7324. * The upper boundary of the box.
  7325. *
  7326. * @type {Vector3}
  7327. */
  7328. this.max = max;
  7329. }
  7330. /**
  7331. * Sets the lower and upper boundaries of this box.
  7332. * Please note that this method only copies the values from the given objects.
  7333. *
  7334. * @param {Vector3} min - The lower boundary of the box.
  7335. * @param {Vector3} max - The upper boundary of the box.
  7336. * @return {Box3} A reference to this bounding box.
  7337. */
  7338. set( min, max ) {
  7339. this.min.copy( min );
  7340. this.max.copy( max );
  7341. return this;
  7342. }
  7343. /**
  7344. * Sets the upper and lower bounds of this box so it encloses the position data
  7345. * in the given array.
  7346. *
  7347. * @param {Array<number>} array - An array holding 3D position data.
  7348. * @return {Box3} A reference to this bounding box.
  7349. */
  7350. setFromArray( array ) {
  7351. this.makeEmpty();
  7352. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  7353. this.expandByPoint( _vector$b.fromArray( array, i ) );
  7354. }
  7355. return this;
  7356. }
  7357. /**
  7358. * Sets the upper and lower bounds of this box so it encloses the position data
  7359. * in the given buffer attribute.
  7360. *
  7361. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  7362. * @return {Box3} A reference to this bounding box.
  7363. */
  7364. setFromBufferAttribute( attribute ) {
  7365. this.makeEmpty();
  7366. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  7367. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  7368. }
  7369. return this;
  7370. }
  7371. /**
  7372. * Sets the upper and lower bounds of this box so it encloses the position data
  7373. * in the given array.
  7374. *
  7375. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  7376. * @return {Box3} A reference to this bounding box.
  7377. */
  7378. setFromPoints( points ) {
  7379. this.makeEmpty();
  7380. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7381. this.expandByPoint( points[ i ] );
  7382. }
  7383. return this;
  7384. }
  7385. /**
  7386. * Centers this box on the given center vector and sets this box's width, height and
  7387. * depth to the given size values.
  7388. *
  7389. * @param {Vector3} center - The center of the box.
  7390. * @param {Vector3} size - The x, y and z dimensions of the box.
  7391. * @return {Box3} A reference to this bounding box.
  7392. */
  7393. setFromCenterAndSize( center, size ) {
  7394. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  7395. this.min.copy( center ).sub( halfSize );
  7396. this.max.copy( center ).add( halfSize );
  7397. return this;
  7398. }
  7399. /**
  7400. * Computes the world-axis-aligned bounding box for the given 3D object
  7401. * (including its children), accounting for the object's, and children's,
  7402. * world transforms. The function may result in a larger box than strictly necessary.
  7403. *
  7404. * @param {Object3D} object - The 3D object to compute the bounding box for.
  7405. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  7406. * world-axis-aligned bounding box at the expense of more computation.
  7407. * @return {Box3} A reference to this bounding box.
  7408. */
  7409. setFromObject( object, precise = false ) {
  7410. this.makeEmpty();
  7411. return this.expandByObject( object, precise );
  7412. }
  7413. /**
  7414. * Returns a new box with copied values from this instance.
  7415. *
  7416. * @return {Box3} A clone of this instance.
  7417. */
  7418. clone() {
  7419. return new this.constructor().copy( this );
  7420. }
  7421. /**
  7422. * Copies the values of the given box to this instance.
  7423. *
  7424. * @param {Box3} box - The box to copy.
  7425. * @return {Box3} A reference to this bounding box.
  7426. */
  7427. copy( box ) {
  7428. this.min.copy( box.min );
  7429. this.max.copy( box.max );
  7430. return this;
  7431. }
  7432. /**
  7433. * Makes this box empty which means in encloses a zero space in 3D.
  7434. *
  7435. * @return {Box3} A reference to this bounding box.
  7436. */
  7437. makeEmpty() {
  7438. this.min.x = this.min.y = this.min.z = + Infinity;
  7439. this.max.x = this.max.y = this.max.z = - Infinity;
  7440. return this;
  7441. }
  7442. /**
  7443. * Returns true if this box includes zero points within its bounds.
  7444. * Note that a box with equal lower and upper bounds still includes one
  7445. * point, the one both bounds share.
  7446. *
  7447. * @return {boolean} Whether this box is empty or not.
  7448. */
  7449. isEmpty() {
  7450. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  7451. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  7452. }
  7453. /**
  7454. * Returns the center point of this box.
  7455. *
  7456. * @param {Vector3} target - The target vector that is used to store the method's result.
  7457. * @return {Vector3} The center point.
  7458. */
  7459. getCenter( target ) {
  7460. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  7461. }
  7462. /**
  7463. * Returns the dimensions of this box.
  7464. *
  7465. * @param {Vector3} target - The target vector that is used to store the method's result.
  7466. * @return {Vector3} The size.
  7467. */
  7468. getSize( target ) {
  7469. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  7470. }
  7471. /**
  7472. * Expands the boundaries of this box to include the given point.
  7473. *
  7474. * @param {Vector3} point - The point that should be included by the bounding box.
  7475. * @return {Box3} A reference to this bounding box.
  7476. */
  7477. expandByPoint( point ) {
  7478. this.min.min( point );
  7479. this.max.max( point );
  7480. return this;
  7481. }
  7482. /**
  7483. * Expands this box equilaterally by the given vector. The width of this
  7484. * box will be expanded by the x component of the vector in both
  7485. * directions. The height of this box will be expanded by the y component of
  7486. * the vector in both directions. The depth of this box will be
  7487. * expanded by the z component of the vector in both directions.
  7488. *
  7489. * @param {Vector3} vector - The vector that should expand the bounding box.
  7490. * @return {Box3} A reference to this bounding box.
  7491. */
  7492. expandByVector( vector ) {
  7493. this.min.sub( vector );
  7494. this.max.add( vector );
  7495. return this;
  7496. }
  7497. /**
  7498. * Expands each dimension of the box by the given scalar. If negative, the
  7499. * dimensions of the box will be contracted.
  7500. *
  7501. * @param {number} scalar - The scalar value that should expand the bounding box.
  7502. * @return {Box3} A reference to this bounding box.
  7503. */
  7504. expandByScalar( scalar ) {
  7505. this.min.addScalar( - scalar );
  7506. this.max.addScalar( scalar );
  7507. return this;
  7508. }
  7509. /**
  7510. * Expands the boundaries of this box to include the given 3D object and
  7511. * its children, accounting for the object's, and children's, world
  7512. * transforms. The function may result in a larger box than strictly
  7513. * necessary (unless the precise parameter is set to true).
  7514. *
  7515. * @param {Object3D} object - The 3D object that should expand the bounding box.
  7516. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  7517. * as little as necessary at the expense of more computation.
  7518. * @return {Box3} A reference to this bounding box.
  7519. */
  7520. expandByObject( object, precise = false ) {
  7521. // Computes the world-axis-aligned bounding box of an object (including its children),
  7522. // accounting for both the object's, and children's, world transforms
  7523. object.updateWorldMatrix( false, false );
  7524. const geometry = object.geometry;
  7525. if ( geometry !== undefined ) {
  7526. const positionAttribute = geometry.getAttribute( 'position' );
  7527. // precise AABB computation based on vertex data requires at least a position attribute.
  7528. // instancing isn't supported so far and uses the normal (conservative) code path.
  7529. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  7530. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  7531. if ( object.isMesh === true ) {
  7532. object.getVertexPosition( i, _vector$b );
  7533. } else {
  7534. _vector$b.fromBufferAttribute( positionAttribute, i );
  7535. }
  7536. _vector$b.applyMatrix4( object.matrixWorld );
  7537. this.expandByPoint( _vector$b );
  7538. }
  7539. } else {
  7540. if ( object.boundingBox !== undefined ) {
  7541. // object-level bounding box
  7542. if ( object.boundingBox === null ) {
  7543. object.computeBoundingBox();
  7544. }
  7545. _box$4.copy( object.boundingBox );
  7546. } else {
  7547. // geometry-level bounding box
  7548. if ( geometry.boundingBox === null ) {
  7549. geometry.computeBoundingBox();
  7550. }
  7551. _box$4.copy( geometry.boundingBox );
  7552. }
  7553. _box$4.applyMatrix4( object.matrixWorld );
  7554. this.union( _box$4 );
  7555. }
  7556. }
  7557. const children = object.children;
  7558. for ( let i = 0, l = children.length; i < l; i ++ ) {
  7559. this.expandByObject( children[ i ], precise );
  7560. }
  7561. return this;
  7562. }
  7563. /**
  7564. * Returns `true` if the given point lies within or on the boundaries of this box.
  7565. *
  7566. * @param {Vector3} point - The point to test.
  7567. * @return {boolean} Whether the bounding box contains the given point or not.
  7568. */
  7569. containsPoint( point ) {
  7570. return point.x >= this.min.x && point.x <= this.max.x &&
  7571. point.y >= this.min.y && point.y <= this.max.y &&
  7572. point.z >= this.min.z && point.z <= this.max.z;
  7573. }
  7574. /**
  7575. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  7576. * If this box and the given one are identical, this function also returns `true`.
  7577. *
  7578. * @param {Box3} box - The bounding box to test.
  7579. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  7580. */
  7581. containsBox( box ) {
  7582. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  7583. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  7584. this.min.z <= box.min.z && box.max.z <= this.max.z;
  7585. }
  7586. /**
  7587. * Returns a point as a proportion of this box's width, height and depth.
  7588. *
  7589. * @param {Vector3} point - A point in 3D space.
  7590. * @param {Vector3} target - The target vector that is used to store the method's result.
  7591. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  7592. */
  7593. getParameter( point, target ) {
  7594. // This can potentially have a divide by zero if the box
  7595. // has a size dimension of 0.
  7596. return target.set(
  7597. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7598. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  7599. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  7600. );
  7601. }
  7602. /**
  7603. * Returns `true` if the given bounding box intersects with this bounding box.
  7604. *
  7605. * @param {Box3} box - The bounding box to test.
  7606. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  7607. */
  7608. intersectsBox( box ) {
  7609. // using 6 splitting planes to rule out intersections.
  7610. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  7611. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  7612. box.max.z >= this.min.z && box.min.z <= this.max.z;
  7613. }
  7614. /**
  7615. * Returns `true` if the given bounding sphere intersects with this bounding box.
  7616. *
  7617. * @param {Sphere} sphere - The bounding sphere to test.
  7618. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  7619. */
  7620. intersectsSphere( sphere ) {
  7621. // Find the point on the AABB closest to the sphere center.
  7622. this.clampPoint( sphere.center, _vector$b );
  7623. // If that point is inside the sphere, the AABB and sphere intersect.
  7624. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  7625. }
  7626. /**
  7627. * Returns `true` if the given plane intersects with this bounding box.
  7628. *
  7629. * @param {Plane} plane - The plane to test.
  7630. * @return {boolean} Whether the given plane intersects with this bounding box.
  7631. */
  7632. intersectsPlane( plane ) {
  7633. // We compute the minimum and maximum dot product values. If those values
  7634. // are on the same side (back or front) of the plane, then there is no intersection.
  7635. let min, max;
  7636. if ( plane.normal.x > 0 ) {
  7637. min = plane.normal.x * this.min.x;
  7638. max = plane.normal.x * this.max.x;
  7639. } else {
  7640. min = plane.normal.x * this.max.x;
  7641. max = plane.normal.x * this.min.x;
  7642. }
  7643. if ( plane.normal.y > 0 ) {
  7644. min += plane.normal.y * this.min.y;
  7645. max += plane.normal.y * this.max.y;
  7646. } else {
  7647. min += plane.normal.y * this.max.y;
  7648. max += plane.normal.y * this.min.y;
  7649. }
  7650. if ( plane.normal.z > 0 ) {
  7651. min += plane.normal.z * this.min.z;
  7652. max += plane.normal.z * this.max.z;
  7653. } else {
  7654. min += plane.normal.z * this.max.z;
  7655. max += plane.normal.z * this.min.z;
  7656. }
  7657. return ( min <= - plane.constant && max >= - plane.constant );
  7658. }
  7659. /**
  7660. * Returns `true` if the given triangle intersects with this bounding box.
  7661. *
  7662. * @param {Triangle} triangle - The triangle to test.
  7663. * @return {boolean} Whether the given triangle intersects with this bounding box.
  7664. */
  7665. intersectsTriangle( triangle ) {
  7666. if ( this.isEmpty() ) {
  7667. return false;
  7668. }
  7669. // compute box center and extents
  7670. this.getCenter( _center );
  7671. _extents.subVectors( this.max, _center );
  7672. // translate triangle to aabb origin
  7673. _v0$3.subVectors( triangle.a, _center );
  7674. _v1$7.subVectors( triangle.b, _center );
  7675. _v2$4.subVectors( triangle.c, _center );
  7676. // compute edge vectors for triangle
  7677. _f0.subVectors( _v1$7, _v0$3 );
  7678. _f1.subVectors( _v2$4, _v1$7 );
  7679. _f2.subVectors( _v0$3, _v2$4 );
  7680. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7681. // 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
  7682. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7683. let axes = [
  7684. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  7685. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  7686. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  7687. ];
  7688. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  7689. return false;
  7690. }
  7691. // test 3 face normals from the aabb
  7692. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7693. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  7694. return false;
  7695. }
  7696. // finally testing the face normal of the triangle
  7697. // use already existing triangle edge vectors here
  7698. _triangleNormal.crossVectors( _f0, _f1 );
  7699. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  7700. return satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents );
  7701. }
  7702. /**
  7703. * Clamps the given point within the bounds of this box.
  7704. *
  7705. * @param {Vector3} point - The point to clamp.
  7706. * @param {Vector3} target - The target vector that is used to store the method's result.
  7707. * @return {Vector3} The clamped point.
  7708. */
  7709. clampPoint( point, target ) {
  7710. return target.copy( point ).clamp( this.min, this.max );
  7711. }
  7712. /**
  7713. * Returns the euclidean distance from any edge of this box to the specified point. If
  7714. * the given point lies inside of this box, the distance will be `0`.
  7715. *
  7716. * @param {Vector3} point - The point to compute the distance to.
  7717. * @return {number} The euclidean distance.
  7718. */
  7719. distanceToPoint( point ) {
  7720. return this.clampPoint( point, _vector$b ).distanceTo( point );
  7721. }
  7722. /**
  7723. * Returns a bounding sphere that encloses this bounding box.
  7724. *
  7725. * @param {Sphere} target - The target sphere that is used to store the method's result.
  7726. * @return {Sphere} The bounding sphere that encloses this bounding box.
  7727. */
  7728. getBoundingSphere( target ) {
  7729. if ( this.isEmpty() ) {
  7730. target.makeEmpty();
  7731. } else {
  7732. this.getCenter( target.center );
  7733. target.radius = this.getSize( _vector$b ).length() * 0.5;
  7734. }
  7735. return target;
  7736. }
  7737. /**
  7738. * Computes the intersection of this bounding box and the given one, setting the upper
  7739. * bound of this box to the lesser of the two boxes' upper bounds and the
  7740. * lower bound of this box to the greater of the two boxes' lower bounds. If
  7741. * there's no overlap, makes this box empty.
  7742. *
  7743. * @param {Box3} box - The bounding box to intersect with.
  7744. * @return {Box3} A reference to this bounding box.
  7745. */
  7746. intersect( box ) {
  7747. this.min.max( box.min );
  7748. this.max.min( box.max );
  7749. // 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.
  7750. if ( this.isEmpty() ) this.makeEmpty();
  7751. return this;
  7752. }
  7753. /**
  7754. * Computes the union of this box and another and the given one, setting the upper
  7755. * bound of this box to the greater of the two boxes' upper bounds and the
  7756. * lower bound of this box to the lesser of the two boxes' lower bounds.
  7757. *
  7758. * @param {Box3} box - The bounding box that will be unioned with this instance.
  7759. * @return {Box3} A reference to this bounding box.
  7760. */
  7761. union( box ) {
  7762. this.min.min( box.min );
  7763. this.max.max( box.max );
  7764. return this;
  7765. }
  7766. /**
  7767. * Transforms this bounding box by the given 4x4 transformation matrix.
  7768. *
  7769. * @param {Matrix4} matrix - The transformation matrix.
  7770. * @return {Box3} A reference to this bounding box.
  7771. */
  7772. applyMatrix4( matrix ) {
  7773. // transform of empty box is an empty box.
  7774. if ( this.isEmpty() ) return this;
  7775. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  7776. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  7777. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  7778. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  7779. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  7780. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  7781. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  7782. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  7783. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  7784. this.setFromPoints( _points );
  7785. return this;
  7786. }
  7787. /**
  7788. * Adds the given offset to both the upper and lower bounds of this bounding box,
  7789. * effectively moving it in 3D space.
  7790. *
  7791. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  7792. * @return {Box3} A reference to this bounding box.
  7793. */
  7794. translate( offset ) {
  7795. this.min.add( offset );
  7796. this.max.add( offset );
  7797. return this;
  7798. }
  7799. /**
  7800. * Returns `true` if this bounding box is equal with the given one.
  7801. *
  7802. * @param {Box3} box - The box to test for equality.
  7803. * @return {boolean} Whether this bounding box is equal with the given one.
  7804. */
  7805. equals( box ) {
  7806. return box.min.equals( this.min ) && box.max.equals( this.max );
  7807. }
  7808. /**
  7809. * Returns a serialized structure of the bounding box.
  7810. *
  7811. * @return {Object} Serialized structure with fields representing the object state.
  7812. */
  7813. toJSON() {
  7814. return {
  7815. min: this.min.toArray(),
  7816. max: this.max.toArray()
  7817. };
  7818. }
  7819. /**
  7820. * Returns a serialized structure of the bounding box.
  7821. *
  7822. * @param {Object} json - The serialized json to set the box from.
  7823. * @return {Box3} A reference to this bounding box.
  7824. */
  7825. fromJSON( json ) {
  7826. this.min.fromArray( json.min );
  7827. this.max.fromArray( json.max );
  7828. return this;
  7829. }
  7830. }
  7831. const _points = [
  7832. /*@__PURE__*/ new Vector3(),
  7833. /*@__PURE__*/ new Vector3(),
  7834. /*@__PURE__*/ new Vector3(),
  7835. /*@__PURE__*/ new Vector3(),
  7836. /*@__PURE__*/ new Vector3(),
  7837. /*@__PURE__*/ new Vector3(),
  7838. /*@__PURE__*/ new Vector3(),
  7839. /*@__PURE__*/ new Vector3()
  7840. ];
  7841. const _vector$b = /*@__PURE__*/ new Vector3();
  7842. const _box$4 = /*@__PURE__*/ new Box3();
  7843. // triangle centered vertices
  7844. const _v0$3 = /*@__PURE__*/ new Vector3();
  7845. const _v1$7 = /*@__PURE__*/ new Vector3();
  7846. const _v2$4 = /*@__PURE__*/ new Vector3();
  7847. // triangle edge vectors
  7848. const _f0 = /*@__PURE__*/ new Vector3();
  7849. const _f1 = /*@__PURE__*/ new Vector3();
  7850. const _f2 = /*@__PURE__*/ new Vector3();
  7851. const _center = /*@__PURE__*/ new Vector3();
  7852. const _extents = /*@__PURE__*/ new Vector3();
  7853. const _triangleNormal = /*@__PURE__*/ new Vector3();
  7854. const _testAxis = /*@__PURE__*/ new Vector3();
  7855. function satForAxes( axes, v0, v1, v2, extents ) {
  7856. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  7857. _testAxis.fromArray( axes, i );
  7858. // project the aabb onto the separating axis
  7859. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  7860. // project all 3 vertices of the triangle onto the separating axis
  7861. const p0 = v0.dot( _testAxis );
  7862. const p1 = v1.dot( _testAxis );
  7863. const p2 = v2.dot( _testAxis );
  7864. // actual test, basically see if either of the most extreme of the triangle points intersects r
  7865. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  7866. // points of the projected triangle are outside the projected half-length of the aabb
  7867. // the axis is separating and we can exit
  7868. return false;
  7869. }
  7870. }
  7871. return true;
  7872. }
  7873. const _box$3 = /*@__PURE__*/ new Box3();
  7874. const _v1$6 = /*@__PURE__*/ new Vector3();
  7875. const _v2$3 = /*@__PURE__*/ new Vector3();
  7876. /**
  7877. * An analytical 3D sphere defined by a center and radius. This class is mainly
  7878. * used as a Bounding Sphere for 3D objects.
  7879. */
  7880. class Sphere {
  7881. /**
  7882. * Constructs a new sphere.
  7883. *
  7884. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  7885. * @param {number} [radius=-1] - The radius of the sphere.
  7886. */
  7887. constructor( center = new Vector3(), radius = -1 ) {
  7888. /**
  7889. * This flag can be used for type testing.
  7890. *
  7891. * @type {boolean}
  7892. * @readonly
  7893. * @default true
  7894. */
  7895. this.isSphere = true;
  7896. /**
  7897. * The center of the sphere
  7898. *
  7899. * @type {Vector3}
  7900. */
  7901. this.center = center;
  7902. /**
  7903. * The radius of the sphere.
  7904. *
  7905. * @type {number}
  7906. */
  7907. this.radius = radius;
  7908. }
  7909. /**
  7910. * Sets the sphere's components by copying the given values.
  7911. *
  7912. * @param {Vector3} center - The center.
  7913. * @param {number} radius - The radius.
  7914. * @return {Sphere} A reference to this sphere.
  7915. */
  7916. set( center, radius ) {
  7917. this.center.copy( center );
  7918. this.radius = radius;
  7919. return this;
  7920. }
  7921. /**
  7922. * Computes the minimum bounding sphere for list of points.
  7923. * If the optional center point is given, it is used as the sphere's
  7924. * center. Otherwise, the center of the axis-aligned bounding box
  7925. * encompassing the points is calculated.
  7926. *
  7927. * @param {Array<Vector3>} points - A list of points in 3D space.
  7928. * @param {Vector3} [optionalCenter] - The center of the sphere.
  7929. * @return {Sphere} A reference to this sphere.
  7930. */
  7931. setFromPoints( points, optionalCenter ) {
  7932. const center = this.center;
  7933. if ( optionalCenter !== undefined ) {
  7934. center.copy( optionalCenter );
  7935. } else {
  7936. _box$3.setFromPoints( points ).getCenter( center );
  7937. }
  7938. let maxRadiusSq = 0;
  7939. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7940. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  7941. }
  7942. this.radius = Math.sqrt( maxRadiusSq );
  7943. return this;
  7944. }
  7945. /**
  7946. * Copies the values of the given sphere to this instance.
  7947. *
  7948. * @param {Sphere} sphere - The sphere to copy.
  7949. * @return {Sphere} A reference to this sphere.
  7950. */
  7951. copy( sphere ) {
  7952. this.center.copy( sphere.center );
  7953. this.radius = sphere.radius;
  7954. return this;
  7955. }
  7956. /**
  7957. * Returns `true` if the sphere is empty (the radius set to a negative number).
  7958. *
  7959. * Spheres with a radius of `0` contain only their center point and are not
  7960. * considered to be empty.
  7961. *
  7962. * @return {boolean} Whether this sphere is empty or not.
  7963. */
  7964. isEmpty() {
  7965. return ( this.radius < 0 );
  7966. }
  7967. /**
  7968. * Makes this sphere empty which means in encloses a zero space in 3D.
  7969. *
  7970. * @return {Sphere} A reference to this sphere.
  7971. */
  7972. makeEmpty() {
  7973. this.center.set( 0, 0, 0 );
  7974. this.radius = -1;
  7975. return this;
  7976. }
  7977. /**
  7978. * Returns `true` if this sphere contains the given point inclusive of
  7979. * the surface of the sphere.
  7980. *
  7981. * @param {Vector3} point - The point to check.
  7982. * @return {boolean} Whether this sphere contains the given point or not.
  7983. */
  7984. containsPoint( point ) {
  7985. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  7986. }
  7987. /**
  7988. * Returns the closest distance from the boundary of the sphere to the
  7989. * given point. If the sphere contains the point, the distance will
  7990. * be negative.
  7991. *
  7992. * @param {Vector3} point - The point to compute the distance to.
  7993. * @return {number} The distance to the point.
  7994. */
  7995. distanceToPoint( point ) {
  7996. return ( point.distanceTo( this.center ) - this.radius );
  7997. }
  7998. /**
  7999. * Returns `true` if this sphere intersects with the given one.
  8000. *
  8001. * @param {Sphere} sphere - The sphere to test.
  8002. * @return {boolean} Whether this sphere intersects with the given one or not.
  8003. */
  8004. intersectsSphere( sphere ) {
  8005. const radiusSum = this.radius + sphere.radius;
  8006. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  8007. }
  8008. /**
  8009. * Returns `true` if this sphere intersects with the given box.
  8010. *
  8011. * @param {Box3} box - The box to test.
  8012. * @return {boolean} Whether this sphere intersects with the given box or not.
  8013. */
  8014. intersectsBox( box ) {
  8015. return box.intersectsSphere( this );
  8016. }
  8017. /**
  8018. * Returns `true` if this sphere intersects with the given plane.
  8019. *
  8020. * @param {Plane} plane - The plane to test.
  8021. * @return {boolean} Whether this sphere intersects with the given plane or not.
  8022. */
  8023. intersectsPlane( plane ) {
  8024. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  8025. }
  8026. /**
  8027. * Clamps a point within the sphere. If the point is outside the sphere, it
  8028. * will clamp it to the closest point on the edge of the sphere. Points
  8029. * already inside the sphere will not be affected.
  8030. *
  8031. * @param {Vector3} point - The plane to clamp.
  8032. * @param {Vector3} target - The target vector that is used to store the method's result.
  8033. * @return {Vector3} The clamped point.
  8034. */
  8035. clampPoint( point, target ) {
  8036. const deltaLengthSq = this.center.distanceToSquared( point );
  8037. target.copy( point );
  8038. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  8039. target.sub( this.center ).normalize();
  8040. target.multiplyScalar( this.radius ).add( this.center );
  8041. }
  8042. return target;
  8043. }
  8044. /**
  8045. * Returns a bounding box that encloses this sphere.
  8046. *
  8047. * @param {Box3} target - The target box that is used to store the method's result.
  8048. * @return {Box3} The bounding box that encloses this sphere.
  8049. */
  8050. getBoundingBox( target ) {
  8051. if ( this.isEmpty() ) {
  8052. // Empty sphere produces empty bounding box
  8053. target.makeEmpty();
  8054. return target;
  8055. }
  8056. target.set( this.center, this.center );
  8057. target.expandByScalar( this.radius );
  8058. return target;
  8059. }
  8060. /**
  8061. * Transforms this sphere with the given 4x4 transformation matrix.
  8062. *
  8063. * @param {Matrix4} matrix - The transformation matrix.
  8064. * @return {Sphere} A reference to this sphere.
  8065. */
  8066. applyMatrix4( matrix ) {
  8067. this.center.applyMatrix4( matrix );
  8068. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  8069. return this;
  8070. }
  8071. /**
  8072. * Translates the sphere's center by the given offset.
  8073. *
  8074. * @param {Vector3} offset - The offset.
  8075. * @return {Sphere} A reference to this sphere.
  8076. */
  8077. translate( offset ) {
  8078. this.center.add( offset );
  8079. return this;
  8080. }
  8081. /**
  8082. * Expands the boundaries of this sphere to include the given point.
  8083. *
  8084. * @param {Vector3} point - The point to include.
  8085. * @return {Sphere} A reference to this sphere.
  8086. */
  8087. expandByPoint( point ) {
  8088. if ( this.isEmpty() ) {
  8089. this.center.copy( point );
  8090. this.radius = 0;
  8091. return this;
  8092. }
  8093. _v1$6.subVectors( point, this.center );
  8094. const lengthSq = _v1$6.lengthSq();
  8095. if ( lengthSq > ( this.radius * this.radius ) ) {
  8096. // calculate the minimal sphere
  8097. const length = Math.sqrt( lengthSq );
  8098. const delta = ( length - this.radius ) * 0.5;
  8099. this.center.addScaledVector( _v1$6, delta / length );
  8100. this.radius += delta;
  8101. }
  8102. return this;
  8103. }
  8104. /**
  8105. * Expands this sphere to enclose both the original sphere and the given sphere.
  8106. *
  8107. * @param {Sphere} sphere - The sphere to include.
  8108. * @return {Sphere} A reference to this sphere.
  8109. */
  8110. union( sphere ) {
  8111. if ( sphere.isEmpty() ) {
  8112. return this;
  8113. }
  8114. if ( this.isEmpty() ) {
  8115. this.copy( sphere );
  8116. return this;
  8117. }
  8118. if ( this.center.equals( sphere.center ) === true ) {
  8119. this.radius = Math.max( this.radius, sphere.radius );
  8120. } else {
  8121. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  8122. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  8123. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  8124. }
  8125. return this;
  8126. }
  8127. /**
  8128. * Returns `true` if this sphere is equal with the given one.
  8129. *
  8130. * @param {Sphere} sphere - The sphere to test for equality.
  8131. * @return {boolean} Whether this bounding sphere is equal with the given one.
  8132. */
  8133. equals( sphere ) {
  8134. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  8135. }
  8136. /**
  8137. * Returns a new sphere with copied values from this instance.
  8138. *
  8139. * @return {Sphere} A clone of this instance.
  8140. */
  8141. clone() {
  8142. return new this.constructor().copy( this );
  8143. }
  8144. /**
  8145. * Returns a serialized structure of the bounding sphere.
  8146. *
  8147. * @return {Object} Serialized structure with fields representing the object state.
  8148. */
  8149. toJSON() {
  8150. return {
  8151. radius: this.radius,
  8152. center: this.center.toArray()
  8153. };
  8154. }
  8155. /**
  8156. * Returns a serialized structure of the bounding sphere.
  8157. *
  8158. * @param {Object} json - The serialized json to set the sphere from.
  8159. * @return {Box3} A reference to this bounding sphere.
  8160. */
  8161. fromJSON( json ) {
  8162. this.radius = json.radius;
  8163. this.center.fromArray( json.center );
  8164. return this;
  8165. }
  8166. }
  8167. const _vector$a = /*@__PURE__*/ new Vector3();
  8168. const _segCenter = /*@__PURE__*/ new Vector3();
  8169. const _segDir = /*@__PURE__*/ new Vector3();
  8170. const _diff = /*@__PURE__*/ new Vector3();
  8171. const _edge1 = /*@__PURE__*/ new Vector3();
  8172. const _edge2 = /*@__PURE__*/ new Vector3();
  8173. const _normal$1 = /*@__PURE__*/ new Vector3();
  8174. /**
  8175. * A ray that emits from an origin in a certain direction. The class is used by
  8176. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  8177. * mouse picking (working out what objects in the 3D space the mouse is over)
  8178. * amongst other things.
  8179. */
  8180. class Ray {
  8181. /**
  8182. * Constructs a new ray.
  8183. *
  8184. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  8185. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  8186. */
  8187. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  8188. /**
  8189. * The origin of the ray.
  8190. *
  8191. * @type {Vector3}
  8192. */
  8193. this.origin = origin;
  8194. /**
  8195. * The (normalized) direction of the ray.
  8196. *
  8197. * @type {Vector3}
  8198. */
  8199. this.direction = direction;
  8200. }
  8201. /**
  8202. * Sets the ray's components by copying the given values.
  8203. *
  8204. * @param {Vector3} origin - The origin.
  8205. * @param {Vector3} direction - The direction.
  8206. * @return {Ray} A reference to this ray.
  8207. */
  8208. set( origin, direction ) {
  8209. this.origin.copy( origin );
  8210. this.direction.copy( direction );
  8211. return this;
  8212. }
  8213. /**
  8214. * Copies the values of the given ray to this instance.
  8215. *
  8216. * @param {Ray} ray - The ray to copy.
  8217. * @return {Ray} A reference to this ray.
  8218. */
  8219. copy( ray ) {
  8220. this.origin.copy( ray.origin );
  8221. this.direction.copy( ray.direction );
  8222. return this;
  8223. }
  8224. /**
  8225. * Returns a vector that is located at a given distance along this ray.
  8226. *
  8227. * @param {number} t - The distance along the ray to retrieve a position for.
  8228. * @param {Vector3} target - The target vector that is used to store the method's result.
  8229. * @return {Vector3} A position on the ray.
  8230. */
  8231. at( t, target ) {
  8232. return target.copy( this.origin ).addScaledVector( this.direction, t );
  8233. }
  8234. /**
  8235. * Adjusts the direction of the ray to point at the given vector in world space.
  8236. *
  8237. * @param {Vector3} v - The target position.
  8238. * @return {Ray} A reference to this ray.
  8239. */
  8240. lookAt( v ) {
  8241. this.direction.copy( v ).sub( this.origin ).normalize();
  8242. return this;
  8243. }
  8244. /**
  8245. * Shift the origin of this ray along its direction by the given distance.
  8246. *
  8247. * @param {number} t - The distance along the ray to interpolate.
  8248. * @return {Ray} A reference to this ray.
  8249. */
  8250. recast( t ) {
  8251. this.origin.copy( this.at( t, _vector$a ) );
  8252. return this;
  8253. }
  8254. /**
  8255. * Returns the point along this ray that is closest to the given point.
  8256. *
  8257. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  8258. * @param {Vector3} target - The target vector that is used to store the method's result.
  8259. * @return {Vector3} The closest point on this ray.
  8260. */
  8261. closestPointToPoint( point, target ) {
  8262. target.subVectors( point, this.origin );
  8263. const directionDistance = target.dot( this.direction );
  8264. if ( directionDistance < 0 ) {
  8265. return target.copy( this.origin );
  8266. }
  8267. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8268. }
  8269. /**
  8270. * Returns the distance of the closest approach between this ray and the given point.
  8271. *
  8272. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8273. * @return {number} The distance.
  8274. */
  8275. distanceToPoint( point ) {
  8276. return Math.sqrt( this.distanceSqToPoint( point ) );
  8277. }
  8278. /**
  8279. * Returns the squared distance of the closest approach between this ray and the given point.
  8280. *
  8281. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8282. * @return {number} The squared distance.
  8283. */
  8284. distanceSqToPoint( point ) {
  8285. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  8286. // point behind the ray
  8287. if ( directionDistance < 0 ) {
  8288. return this.origin.distanceToSquared( point );
  8289. }
  8290. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8291. return _vector$a.distanceToSquared( point );
  8292. }
  8293. /**
  8294. * Returns the squared distance between this ray and the given line segment.
  8295. *
  8296. * @param {Vector3} v0 - The start point of the line segment.
  8297. * @param {Vector3} v1 - The end point of the line segment.
  8298. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  8299. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  8300. * @return {number} The squared distance.
  8301. */
  8302. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  8303. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8304. // It returns the min distance between the ray and the segment
  8305. // defined by v0 and v1
  8306. // It can also set two optional targets :
  8307. // - The closest point on the ray
  8308. // - The closest point on the segment
  8309. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  8310. _segDir.copy( v1 ).sub( v0 ).normalize();
  8311. _diff.copy( this.origin ).sub( _segCenter );
  8312. const segExtent = v0.distanceTo( v1 ) * 0.5;
  8313. const a01 = - this.direction.dot( _segDir );
  8314. const b0 = _diff.dot( this.direction );
  8315. const b1 = - _diff.dot( _segDir );
  8316. const c = _diff.lengthSq();
  8317. const det = Math.abs( 1 - a01 * a01 );
  8318. let s0, s1, sqrDist, extDet;
  8319. if ( det > 0 ) {
  8320. // The ray and segment are not parallel.
  8321. s0 = a01 * b1 - b0;
  8322. s1 = a01 * b0 - b1;
  8323. extDet = segExtent * det;
  8324. if ( s0 >= 0 ) {
  8325. if ( s1 >= - extDet ) {
  8326. if ( s1 <= extDet ) {
  8327. // region 0
  8328. // Minimum at interior points of ray and segment.
  8329. const invDet = 1 / det;
  8330. s0 *= invDet;
  8331. s1 *= invDet;
  8332. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  8333. } else {
  8334. // region 1
  8335. s1 = segExtent;
  8336. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8337. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8338. }
  8339. } else {
  8340. // region 5
  8341. s1 = - segExtent;
  8342. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8343. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8344. }
  8345. } else {
  8346. if ( s1 <= - extDet ) {
  8347. // region 4
  8348. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  8349. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8350. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8351. } else if ( s1 <= extDet ) {
  8352. // region 3
  8353. s0 = 0;
  8354. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8355. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  8356. } else {
  8357. // region 2
  8358. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  8359. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8360. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8361. }
  8362. }
  8363. } else {
  8364. // Ray and segment are parallel.
  8365. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  8366. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8367. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8368. }
  8369. if ( optionalPointOnRay ) {
  8370. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  8371. }
  8372. if ( optionalPointOnSegment ) {
  8373. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  8374. }
  8375. return sqrDist;
  8376. }
  8377. /**
  8378. * Intersects this ray with the given sphere, returning the intersection
  8379. * point or `null` if there is no intersection.
  8380. *
  8381. * @param {Sphere} sphere - The sphere to intersect.
  8382. * @param {Vector3} target - The target vector that is used to store the method's result.
  8383. * @return {?Vector3} The intersection point.
  8384. */
  8385. intersectSphere( sphere, target ) {
  8386. _vector$a.subVectors( sphere.center, this.origin );
  8387. const tca = _vector$a.dot( this.direction );
  8388. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  8389. const radius2 = sphere.radius * sphere.radius;
  8390. if ( d2 > radius2 ) return null;
  8391. const thc = Math.sqrt( radius2 - d2 );
  8392. // t0 = first intersect point - entrance on front of sphere
  8393. const t0 = tca - thc;
  8394. // t1 = second intersect point - exit point on back of sphere
  8395. const t1 = tca + thc;
  8396. // test to see if t1 is behind the ray - if so, return null
  8397. if ( t1 < 0 ) return null;
  8398. // test to see if t0 is behind the ray:
  8399. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  8400. // in order to always return an intersect point that is in front of the ray.
  8401. if ( t0 < 0 ) return this.at( t1, target );
  8402. // else t0 is in front of the ray, so return the first collision point scaled by t0
  8403. return this.at( t0, target );
  8404. }
  8405. /**
  8406. * Returns `true` if this ray intersects with the given sphere.
  8407. *
  8408. * @param {Sphere} sphere - The sphere to intersect.
  8409. * @return {boolean} Whether this ray intersects with the given sphere or not.
  8410. */
  8411. intersectsSphere( sphere ) {
  8412. if ( sphere.radius < 0 ) return false; // handle empty spheres, see #31187
  8413. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  8414. }
  8415. /**
  8416. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  8417. * does not intersect with the plane.
  8418. *
  8419. * @param {Plane} plane - The plane to compute the distance to.
  8420. * @return {?number} Whether this ray intersects with the given sphere or not.
  8421. */
  8422. distanceToPlane( plane ) {
  8423. const denominator = plane.normal.dot( this.direction );
  8424. if ( denominator === 0 ) {
  8425. // line is coplanar, return origin
  8426. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  8427. return 0;
  8428. }
  8429. // Null is preferable to undefined since undefined means.... it is undefined
  8430. return null;
  8431. }
  8432. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  8433. // Return if the ray never intersects the plane
  8434. return t >= 0 ? t : null;
  8435. }
  8436. /**
  8437. * Intersects this ray with the given plane, returning the intersection
  8438. * point or `null` if there is no intersection.
  8439. *
  8440. * @param {Plane} plane - The plane to intersect.
  8441. * @param {Vector3} target - The target vector that is used to store the method's result.
  8442. * @return {?Vector3} The intersection point.
  8443. */
  8444. intersectPlane( plane, target ) {
  8445. const t = this.distanceToPlane( plane );
  8446. if ( t === null ) {
  8447. return null;
  8448. }
  8449. return this.at( t, target );
  8450. }
  8451. /**
  8452. * Returns `true` if this ray intersects with the given plane.
  8453. *
  8454. * @param {Plane} plane - The plane to intersect.
  8455. * @return {boolean} Whether this ray intersects with the given plane or not.
  8456. */
  8457. intersectsPlane( plane ) {
  8458. // check if the ray lies on the plane first
  8459. const distToPoint = plane.distanceToPoint( this.origin );
  8460. if ( distToPoint === 0 ) {
  8461. return true;
  8462. }
  8463. const denominator = plane.normal.dot( this.direction );
  8464. if ( denominator * distToPoint < 0 ) {
  8465. return true;
  8466. }
  8467. // ray origin is behind the plane (and is pointing behind it)
  8468. return false;
  8469. }
  8470. /**
  8471. * Intersects this ray with the given bounding box, returning the intersection
  8472. * point or `null` if there is no intersection.
  8473. *
  8474. * @param {Box3} box - The box to intersect.
  8475. * @param {Vector3} target - The target vector that is used to store the method's result.
  8476. * @return {?Vector3} The intersection point.
  8477. */
  8478. intersectBox( box, target ) {
  8479. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  8480. const invdirx = 1 / this.direction.x,
  8481. invdiry = 1 / this.direction.y,
  8482. invdirz = 1 / this.direction.z;
  8483. const origin = this.origin;
  8484. if ( invdirx >= 0 ) {
  8485. tmin = ( box.min.x - origin.x ) * invdirx;
  8486. tmax = ( box.max.x - origin.x ) * invdirx;
  8487. } else {
  8488. tmin = ( box.max.x - origin.x ) * invdirx;
  8489. tmax = ( box.min.x - origin.x ) * invdirx;
  8490. }
  8491. if ( invdiry >= 0 ) {
  8492. tymin = ( box.min.y - origin.y ) * invdiry;
  8493. tymax = ( box.max.y - origin.y ) * invdiry;
  8494. } else {
  8495. tymin = ( box.max.y - origin.y ) * invdiry;
  8496. tymax = ( box.min.y - origin.y ) * invdiry;
  8497. }
  8498. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  8499. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  8500. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  8501. if ( invdirz >= 0 ) {
  8502. tzmin = ( box.min.z - origin.z ) * invdirz;
  8503. tzmax = ( box.max.z - origin.z ) * invdirz;
  8504. } else {
  8505. tzmin = ( box.max.z - origin.z ) * invdirz;
  8506. tzmax = ( box.min.z - origin.z ) * invdirz;
  8507. }
  8508. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  8509. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  8510. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  8511. //return point closest to the ray (positive side)
  8512. if ( tmax < 0 ) return null;
  8513. return this.at( tmin >= 0 ? tmin : tmax, target );
  8514. }
  8515. /**
  8516. * Returns `true` if this ray intersects with the given box.
  8517. *
  8518. * @param {Box3} box - The box to intersect.
  8519. * @return {boolean} Whether this ray intersects with the given box or not.
  8520. */
  8521. intersectsBox( box ) {
  8522. return this.intersectBox( box, _vector$a ) !== null;
  8523. }
  8524. /**
  8525. * Intersects this ray with the given triangle, returning the intersection
  8526. * point or `null` if there is no intersection.
  8527. *
  8528. * @param {Vector3} a - The first vertex of the triangle.
  8529. * @param {Vector3} b - The second vertex of the triangle.
  8530. * @param {Vector3} c - The third vertex of the triangle.
  8531. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  8532. * @param {Vector3} target - The target vector that is used to store the method's result.
  8533. * @return {?Vector3} The intersection point.
  8534. */
  8535. intersectTriangle( a, b, c, backfaceCulling, target ) {
  8536. // Compute the offset origin, edges, and normal.
  8537. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  8538. _edge1.subVectors( b, a );
  8539. _edge2.subVectors( c, a );
  8540. _normal$1.crossVectors( _edge1, _edge2 );
  8541. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  8542. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  8543. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  8544. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  8545. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  8546. let DdN = this.direction.dot( _normal$1 );
  8547. let sign;
  8548. if ( DdN > 0 ) {
  8549. if ( backfaceCulling ) return null;
  8550. sign = 1;
  8551. } else if ( DdN < 0 ) {
  8552. sign = -1;
  8553. DdN = - DdN;
  8554. } else {
  8555. return null;
  8556. }
  8557. _diff.subVectors( this.origin, a );
  8558. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  8559. // b1 < 0, no intersection
  8560. if ( DdQxE2 < 0 ) {
  8561. return null;
  8562. }
  8563. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  8564. // b2 < 0, no intersection
  8565. if ( DdE1xQ < 0 ) {
  8566. return null;
  8567. }
  8568. // b1+b2 > 1, no intersection
  8569. if ( DdQxE2 + DdE1xQ > DdN ) {
  8570. return null;
  8571. }
  8572. // Line intersects triangle, check if ray does.
  8573. const QdN = - sign * _diff.dot( _normal$1 );
  8574. // t < 0, no intersection
  8575. if ( QdN < 0 ) {
  8576. return null;
  8577. }
  8578. // Ray intersects triangle.
  8579. return this.at( QdN / DdN, target );
  8580. }
  8581. /**
  8582. * Transforms this ray with the given 4x4 transformation matrix.
  8583. *
  8584. * @param {Matrix4} matrix4 - The transformation matrix.
  8585. * @return {Ray} A reference to this ray.
  8586. */
  8587. applyMatrix4( matrix4 ) {
  8588. this.origin.applyMatrix4( matrix4 );
  8589. this.direction.transformDirection( matrix4 );
  8590. return this;
  8591. }
  8592. /**
  8593. * Returns `true` if this ray is equal with the given one.
  8594. *
  8595. * @param {Ray} ray - The ray to test for equality.
  8596. * @return {boolean} Whether this ray is equal with the given one.
  8597. */
  8598. equals( ray ) {
  8599. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  8600. }
  8601. /**
  8602. * Returns a new ray with copied values from this instance.
  8603. *
  8604. * @return {Ray} A clone of this instance.
  8605. */
  8606. clone() {
  8607. return new this.constructor().copy( this );
  8608. }
  8609. }
  8610. /**
  8611. * Represents a 4x4 matrix.
  8612. *
  8613. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  8614. * 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}
  8615. *
  8616. * This allows a 3D vector representing a point in 3D space to undergo
  8617. * transformations such as translation, rotation, shear, scale, reflection,
  8618. * orthogonal or perspective projection and so on, by being multiplied by the
  8619. * matrix. This is known as `applying` the matrix to the vector.
  8620. *
  8621. * A Note on Row-Major and Column-Major Ordering:
  8622. *
  8623. * The constructor and {@link Matrix3#set} method take arguments in
  8624. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  8625. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  8626. * This means that calling:
  8627. * ```js
  8628. * const m = new THREE.Matrix4();
  8629. * m.set( 11, 12, 13, 14,
  8630. * 21, 22, 23, 24,
  8631. * 31, 32, 33, 34,
  8632. * 41, 42, 43, 44 );
  8633. * ```
  8634. * will result in the elements array containing:
  8635. * ```js
  8636. * m.elements = [ 11, 21, 31, 41,
  8637. * 12, 22, 32, 42,
  8638. * 13, 23, 33, 43,
  8639. * 14, 24, 34, 44 ];
  8640. * ```
  8641. * and internally all calculations are performed using column-major ordering.
  8642. * However, as the actual ordering makes no difference mathematically and
  8643. * most people are used to thinking about matrices in row-major order, the
  8644. * three.js documentation shows matrices in row-major order. Just bear in
  8645. * mind that if you are reading the source code, you'll have to take the
  8646. * transpose of any matrices outlined here to make sense of the calculations.
  8647. */
  8648. class Matrix4 {
  8649. /**
  8650. * Constructs a new 4x4 matrix. The arguments are supposed to be
  8651. * in row-major order. If no arguments are provided, the constructor
  8652. * initializes the matrix as an identity matrix.
  8653. *
  8654. * @param {number} [n11] - 1-1 matrix element.
  8655. * @param {number} [n12] - 1-2 matrix element.
  8656. * @param {number} [n13] - 1-3 matrix element.
  8657. * @param {number} [n14] - 1-4 matrix element.
  8658. * @param {number} [n21] - 2-1 matrix element.
  8659. * @param {number} [n22] - 2-2 matrix element.
  8660. * @param {number} [n23] - 2-3 matrix element.
  8661. * @param {number} [n24] - 2-4 matrix element.
  8662. * @param {number} [n31] - 3-1 matrix element.
  8663. * @param {number} [n32] - 3-2 matrix element.
  8664. * @param {number} [n33] - 3-3 matrix element.
  8665. * @param {number} [n34] - 3-4 matrix element.
  8666. * @param {number} [n41] - 4-1 matrix element.
  8667. * @param {number} [n42] - 4-2 matrix element.
  8668. * @param {number} [n43] - 4-3 matrix element.
  8669. * @param {number} [n44] - 4-4 matrix element.
  8670. */
  8671. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8672. /**
  8673. * This flag can be used for type testing.
  8674. *
  8675. * @type {boolean}
  8676. * @readonly
  8677. * @default true
  8678. */
  8679. Matrix4.prototype.isMatrix4 = true;
  8680. /**
  8681. * A column-major list of matrix values.
  8682. *
  8683. * @type {Array<number>}
  8684. */
  8685. this.elements = [
  8686. 1, 0, 0, 0,
  8687. 0, 1, 0, 0,
  8688. 0, 0, 1, 0,
  8689. 0, 0, 0, 1
  8690. ];
  8691. if ( n11 !== undefined ) {
  8692. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  8693. }
  8694. }
  8695. /**
  8696. * Sets the elements of the matrix.The arguments are supposed to be
  8697. * in row-major order.
  8698. *
  8699. * @param {number} [n11] - 1-1 matrix element.
  8700. * @param {number} [n12] - 1-2 matrix element.
  8701. * @param {number} [n13] - 1-3 matrix element.
  8702. * @param {number} [n14] - 1-4 matrix element.
  8703. * @param {number} [n21] - 2-1 matrix element.
  8704. * @param {number} [n22] - 2-2 matrix element.
  8705. * @param {number} [n23] - 2-3 matrix element.
  8706. * @param {number} [n24] - 2-4 matrix element.
  8707. * @param {number} [n31] - 3-1 matrix element.
  8708. * @param {number} [n32] - 3-2 matrix element.
  8709. * @param {number} [n33] - 3-3 matrix element.
  8710. * @param {number} [n34] - 3-4 matrix element.
  8711. * @param {number} [n41] - 4-1 matrix element.
  8712. * @param {number} [n42] - 4-2 matrix element.
  8713. * @param {number} [n43] - 4-3 matrix element.
  8714. * @param {number} [n44] - 4-4 matrix element.
  8715. * @return {Matrix4} A reference to this matrix.
  8716. */
  8717. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8718. const te = this.elements;
  8719. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  8720. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  8721. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  8722. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  8723. return this;
  8724. }
  8725. /**
  8726. * Sets this matrix to the 4x4 identity matrix.
  8727. *
  8728. * @return {Matrix4} A reference to this matrix.
  8729. */
  8730. identity() {
  8731. this.set(
  8732. 1, 0, 0, 0,
  8733. 0, 1, 0, 0,
  8734. 0, 0, 1, 0,
  8735. 0, 0, 0, 1
  8736. );
  8737. return this;
  8738. }
  8739. /**
  8740. * Returns a matrix with copied values from this instance.
  8741. *
  8742. * @return {Matrix4} A clone of this instance.
  8743. */
  8744. clone() {
  8745. return new Matrix4().fromArray( this.elements );
  8746. }
  8747. /**
  8748. * Copies the values of the given matrix to this instance.
  8749. *
  8750. * @param {Matrix4} m - The matrix to copy.
  8751. * @return {Matrix4} A reference to this matrix.
  8752. */
  8753. copy( m ) {
  8754. const te = this.elements;
  8755. const me = m.elements;
  8756. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  8757. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  8758. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  8759. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  8760. return this;
  8761. }
  8762. /**
  8763. * Copies the translation component of the given matrix
  8764. * into this matrix's translation component.
  8765. *
  8766. * @param {Matrix4} m - The matrix to copy the translation component.
  8767. * @return {Matrix4} A reference to this matrix.
  8768. */
  8769. copyPosition( m ) {
  8770. const te = this.elements, me = m.elements;
  8771. te[ 12 ] = me[ 12 ];
  8772. te[ 13 ] = me[ 13 ];
  8773. te[ 14 ] = me[ 14 ];
  8774. return this;
  8775. }
  8776. /**
  8777. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  8778. *
  8779. * @param {Matrix3} m - The 3x3 matrix.
  8780. * @return {Matrix4} A reference to this matrix.
  8781. */
  8782. setFromMatrix3( m ) {
  8783. const me = m.elements;
  8784. this.set(
  8785. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  8786. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  8787. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  8788. 0, 0, 0, 1
  8789. );
  8790. return this;
  8791. }
  8792. /**
  8793. * Extracts the basis of this matrix into the three axis vectors provided.
  8794. *
  8795. * @param {Vector3} xAxis - The basis's x axis.
  8796. * @param {Vector3} yAxis - The basis's y axis.
  8797. * @param {Vector3} zAxis - The basis's z axis.
  8798. * @return {Matrix4} A reference to this matrix.
  8799. */
  8800. extractBasis( xAxis, yAxis, zAxis ) {
  8801. xAxis.setFromMatrixColumn( this, 0 );
  8802. yAxis.setFromMatrixColumn( this, 1 );
  8803. zAxis.setFromMatrixColumn( this, 2 );
  8804. return this;
  8805. }
  8806. /**
  8807. * Sets the given basis vectors to this matrix.
  8808. *
  8809. * @param {Vector3} xAxis - The basis's x axis.
  8810. * @param {Vector3} yAxis - The basis's y axis.
  8811. * @param {Vector3} zAxis - The basis's z axis.
  8812. * @return {Matrix4} A reference to this matrix.
  8813. */
  8814. makeBasis( xAxis, yAxis, zAxis ) {
  8815. this.set(
  8816. xAxis.x, yAxis.x, zAxis.x, 0,
  8817. xAxis.y, yAxis.y, zAxis.y, 0,
  8818. xAxis.z, yAxis.z, zAxis.z, 0,
  8819. 0, 0, 0, 1
  8820. );
  8821. return this;
  8822. }
  8823. /**
  8824. * Extracts the rotation component of the given matrix
  8825. * into this matrix's rotation component.
  8826. *
  8827. * Note: This method does not support reflection matrices.
  8828. *
  8829. * @param {Matrix4} m - The matrix.
  8830. * @return {Matrix4} A reference to this matrix.
  8831. */
  8832. extractRotation( m ) {
  8833. const te = this.elements;
  8834. const me = m.elements;
  8835. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  8836. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  8837. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  8838. te[ 0 ] = me[ 0 ] * scaleX;
  8839. te[ 1 ] = me[ 1 ] * scaleX;
  8840. te[ 2 ] = me[ 2 ] * scaleX;
  8841. te[ 3 ] = 0;
  8842. te[ 4 ] = me[ 4 ] * scaleY;
  8843. te[ 5 ] = me[ 5 ] * scaleY;
  8844. te[ 6 ] = me[ 6 ] * scaleY;
  8845. te[ 7 ] = 0;
  8846. te[ 8 ] = me[ 8 ] * scaleZ;
  8847. te[ 9 ] = me[ 9 ] * scaleZ;
  8848. te[ 10 ] = me[ 10 ] * scaleZ;
  8849. te[ 11 ] = 0;
  8850. te[ 12 ] = 0;
  8851. te[ 13 ] = 0;
  8852. te[ 14 ] = 0;
  8853. te[ 15 ] = 1;
  8854. return this;
  8855. }
  8856. /**
  8857. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  8858. * the rotation specified by the given Euler angles. The rest of
  8859. * the matrix is set to the identity. Depending on the {@link Euler#order},
  8860. * there are six possible outcomes. See [this page]{@link https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix}
  8861. * for a complete list.
  8862. *
  8863. * @param {Euler} euler - The Euler angles.
  8864. * @return {Matrix4} A reference to this matrix.
  8865. */
  8866. makeRotationFromEuler( euler ) {
  8867. const te = this.elements;
  8868. const x = euler.x, y = euler.y, z = euler.z;
  8869. const a = Math.cos( x ), b = Math.sin( x );
  8870. const c = Math.cos( y ), d = Math.sin( y );
  8871. const e = Math.cos( z ), f = Math.sin( z );
  8872. if ( euler.order === 'XYZ' ) {
  8873. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8874. te[ 0 ] = c * e;
  8875. te[ 4 ] = - c * f;
  8876. te[ 8 ] = d;
  8877. te[ 1 ] = af + be * d;
  8878. te[ 5 ] = ae - bf * d;
  8879. te[ 9 ] = - b * c;
  8880. te[ 2 ] = bf - ae * d;
  8881. te[ 6 ] = be + af * d;
  8882. te[ 10 ] = a * c;
  8883. } else if ( euler.order === 'YXZ' ) {
  8884. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8885. te[ 0 ] = ce + df * b;
  8886. te[ 4 ] = de * b - cf;
  8887. te[ 8 ] = a * d;
  8888. te[ 1 ] = a * f;
  8889. te[ 5 ] = a * e;
  8890. te[ 9 ] = - b;
  8891. te[ 2 ] = cf * b - de;
  8892. te[ 6 ] = df + ce * b;
  8893. te[ 10 ] = a * c;
  8894. } else if ( euler.order === 'ZXY' ) {
  8895. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8896. te[ 0 ] = ce - df * b;
  8897. te[ 4 ] = - a * f;
  8898. te[ 8 ] = de + cf * b;
  8899. te[ 1 ] = cf + de * b;
  8900. te[ 5 ] = a * e;
  8901. te[ 9 ] = df - ce * b;
  8902. te[ 2 ] = - a * d;
  8903. te[ 6 ] = b;
  8904. te[ 10 ] = a * c;
  8905. } else if ( euler.order === 'ZYX' ) {
  8906. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8907. te[ 0 ] = c * e;
  8908. te[ 4 ] = be * d - af;
  8909. te[ 8 ] = ae * d + bf;
  8910. te[ 1 ] = c * f;
  8911. te[ 5 ] = bf * d + ae;
  8912. te[ 9 ] = af * d - be;
  8913. te[ 2 ] = - d;
  8914. te[ 6 ] = b * c;
  8915. te[ 10 ] = a * c;
  8916. } else if ( euler.order === 'YZX' ) {
  8917. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8918. te[ 0 ] = c * e;
  8919. te[ 4 ] = bd - ac * f;
  8920. te[ 8 ] = bc * f + ad;
  8921. te[ 1 ] = f;
  8922. te[ 5 ] = a * e;
  8923. te[ 9 ] = - b * e;
  8924. te[ 2 ] = - d * e;
  8925. te[ 6 ] = ad * f + bc;
  8926. te[ 10 ] = ac - bd * f;
  8927. } else if ( euler.order === 'XZY' ) {
  8928. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8929. te[ 0 ] = c * e;
  8930. te[ 4 ] = - f;
  8931. te[ 8 ] = d * e;
  8932. te[ 1 ] = ac * f + bd;
  8933. te[ 5 ] = a * e;
  8934. te[ 9 ] = ad * f - bc;
  8935. te[ 2 ] = bc * f - ad;
  8936. te[ 6 ] = b * e;
  8937. te[ 10 ] = bd * f + ac;
  8938. }
  8939. // bottom row
  8940. te[ 3 ] = 0;
  8941. te[ 7 ] = 0;
  8942. te[ 11 ] = 0;
  8943. // last column
  8944. te[ 12 ] = 0;
  8945. te[ 13 ] = 0;
  8946. te[ 14 ] = 0;
  8947. te[ 15 ] = 1;
  8948. return this;
  8949. }
  8950. /**
  8951. * Sets the rotation component of this matrix to the rotation specified by
  8952. * the given Quaternion as outlined [here]{@link https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion}
  8953. * The rest of the matrix is set to the identity.
  8954. *
  8955. * @param {Quaternion} q - The Quaternion.
  8956. * @return {Matrix4} A reference to this matrix.
  8957. */
  8958. makeRotationFromQuaternion( q ) {
  8959. return this.compose( _zero, q, _one );
  8960. }
  8961. /**
  8962. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  8963. * `target`, and oriented by the up-direction.
  8964. *
  8965. * @param {Vector3} eye - The eye vector.
  8966. * @param {Vector3} target - The target vector.
  8967. * @param {Vector3} up - The up vector.
  8968. * @return {Matrix4} A reference to this matrix.
  8969. */
  8970. lookAt( eye, target, up ) {
  8971. const te = this.elements;
  8972. _z.subVectors( eye, target );
  8973. if ( _z.lengthSq() === 0 ) {
  8974. // eye and target are in the same position
  8975. _z.z = 1;
  8976. }
  8977. _z.normalize();
  8978. _x.crossVectors( up, _z );
  8979. if ( _x.lengthSq() === 0 ) {
  8980. // up and z are parallel
  8981. if ( Math.abs( up.z ) === 1 ) {
  8982. _z.x += 0.0001;
  8983. } else {
  8984. _z.z += 0.0001;
  8985. }
  8986. _z.normalize();
  8987. _x.crossVectors( up, _z );
  8988. }
  8989. _x.normalize();
  8990. _y.crossVectors( _z, _x );
  8991. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  8992. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  8993. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  8994. return this;
  8995. }
  8996. /**
  8997. * Post-multiplies this matrix by the given 4x4 matrix.
  8998. *
  8999. * @param {Matrix4} m - The matrix to multiply with.
  9000. * @return {Matrix4} A reference to this matrix.
  9001. */
  9002. multiply( m ) {
  9003. return this.multiplyMatrices( this, m );
  9004. }
  9005. /**
  9006. * Pre-multiplies this matrix by the given 4x4 matrix.
  9007. *
  9008. * @param {Matrix4} m - The matrix to multiply with.
  9009. * @return {Matrix4} A reference to this matrix.
  9010. */
  9011. premultiply( m ) {
  9012. return this.multiplyMatrices( m, this );
  9013. }
  9014. /**
  9015. * Multiples the given 4x4 matrices and stores the result
  9016. * in this matrix.
  9017. *
  9018. * @param {Matrix4} a - The first matrix.
  9019. * @param {Matrix4} b - The second matrix.
  9020. * @return {Matrix4} A reference to this matrix.
  9021. */
  9022. multiplyMatrices( a, b ) {
  9023. const ae = a.elements;
  9024. const be = b.elements;
  9025. const te = this.elements;
  9026. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  9027. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  9028. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  9029. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  9030. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  9031. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  9032. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  9033. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  9034. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  9035. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  9036. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  9037. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  9038. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  9039. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  9040. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  9041. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  9042. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  9043. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  9044. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  9045. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  9046. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  9047. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  9048. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  9049. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  9050. return this;
  9051. }
  9052. /**
  9053. * Multiplies every component of the matrix by the given scalar.
  9054. *
  9055. * @param {number} s - The scalar.
  9056. * @return {Matrix4} A reference to this matrix.
  9057. */
  9058. multiplyScalar( s ) {
  9059. const te = this.elements;
  9060. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  9061. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  9062. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  9063. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  9064. return this;
  9065. }
  9066. /**
  9067. * Computes and returns the determinant of this matrix.
  9068. *
  9069. * Based on the method outlined [here]{@link http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html}.
  9070. *
  9071. * @return {number} The determinant.
  9072. */
  9073. determinant() {
  9074. const te = this.elements;
  9075. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  9076. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  9077. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  9078. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  9079. //TODO: make this more efficient
  9080. return (
  9081. n41 * (
  9082. + n14 * n23 * n32
  9083. - n13 * n24 * n32
  9084. - n14 * n22 * n33
  9085. + n12 * n24 * n33
  9086. + n13 * n22 * n34
  9087. - n12 * n23 * n34
  9088. ) +
  9089. n42 * (
  9090. + n11 * n23 * n34
  9091. - n11 * n24 * n33
  9092. + n14 * n21 * n33
  9093. - n13 * n21 * n34
  9094. + n13 * n24 * n31
  9095. - n14 * n23 * n31
  9096. ) +
  9097. n43 * (
  9098. + n11 * n24 * n32
  9099. - n11 * n22 * n34
  9100. - n14 * n21 * n32
  9101. + n12 * n21 * n34
  9102. + n14 * n22 * n31
  9103. - n12 * n24 * n31
  9104. ) +
  9105. n44 * (
  9106. - n13 * n22 * n31
  9107. - n11 * n23 * n32
  9108. + n11 * n22 * n33
  9109. + n13 * n21 * n32
  9110. - n12 * n21 * n33
  9111. + n12 * n23 * n31
  9112. )
  9113. );
  9114. }
  9115. /**
  9116. * Transposes this matrix in place.
  9117. *
  9118. * @return {Matrix4} A reference to this matrix.
  9119. */
  9120. transpose() {
  9121. const te = this.elements;
  9122. let tmp;
  9123. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  9124. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  9125. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  9126. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  9127. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  9128. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  9129. return this;
  9130. }
  9131. /**
  9132. * Sets the position component for this matrix from the given vector,
  9133. * without affecting the rest of the matrix.
  9134. *
  9135. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  9136. * @param {number} y - The y component of the vector.
  9137. * @param {number} z - The z component of the vector.
  9138. * @return {Matrix4} A reference to this matrix.
  9139. */
  9140. setPosition( x, y, z ) {
  9141. const te = this.elements;
  9142. if ( x.isVector3 ) {
  9143. te[ 12 ] = x.x;
  9144. te[ 13 ] = x.y;
  9145. te[ 14 ] = x.z;
  9146. } else {
  9147. te[ 12 ] = x;
  9148. te[ 13 ] = y;
  9149. te[ 14 ] = z;
  9150. }
  9151. return this;
  9152. }
  9153. /**
  9154. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  9155. * You can not invert with a determinant of zero. If you attempt this, the method produces
  9156. * a zero matrix instead.
  9157. *
  9158. * @return {Matrix4} A reference to this matrix.
  9159. */
  9160. invert() {
  9161. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  9162. const te = this.elements,
  9163. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  9164. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  9165. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  9166. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  9167. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  9168. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  9169. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  9170. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  9171. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  9172. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  9173. const detInv = 1 / det;
  9174. te[ 0 ] = t11 * detInv;
  9175. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  9176. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  9177. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  9178. te[ 4 ] = t12 * detInv;
  9179. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  9180. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  9181. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  9182. te[ 8 ] = t13 * detInv;
  9183. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  9184. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  9185. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  9186. te[ 12 ] = t14 * detInv;
  9187. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  9188. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  9189. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  9190. return this;
  9191. }
  9192. /**
  9193. * Multiplies the columns of this matrix by the given vector.
  9194. *
  9195. * @param {Vector3} v - The scale vector.
  9196. * @return {Matrix4} A reference to this matrix.
  9197. */
  9198. scale( v ) {
  9199. const te = this.elements;
  9200. const x = v.x, y = v.y, z = v.z;
  9201. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  9202. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  9203. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  9204. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  9205. return this;
  9206. }
  9207. /**
  9208. * Gets the maximum scale value of the three axes.
  9209. *
  9210. * @return {number} The maximum scale.
  9211. */
  9212. getMaxScaleOnAxis() {
  9213. const te = this.elements;
  9214. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  9215. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  9216. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  9217. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  9218. }
  9219. /**
  9220. * Sets this matrix as a translation transform from the given vector.
  9221. *
  9222. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  9223. * @param {number} y - The amount to translate in the Y axis.
  9224. * @param {number} z - The amount to translate in the z axis.
  9225. * @return {Matrix4} A reference to this matrix.
  9226. */
  9227. makeTranslation( x, y, z ) {
  9228. if ( x.isVector3 ) {
  9229. this.set(
  9230. 1, 0, 0, x.x,
  9231. 0, 1, 0, x.y,
  9232. 0, 0, 1, x.z,
  9233. 0, 0, 0, 1
  9234. );
  9235. } else {
  9236. this.set(
  9237. 1, 0, 0, x,
  9238. 0, 1, 0, y,
  9239. 0, 0, 1, z,
  9240. 0, 0, 0, 1
  9241. );
  9242. }
  9243. return this;
  9244. }
  9245. /**
  9246. * Sets this matrix as a rotational transformation around the X axis by
  9247. * the given angle.
  9248. *
  9249. * @param {number} theta - The rotation in radians.
  9250. * @return {Matrix4} A reference to this matrix.
  9251. */
  9252. makeRotationX( theta ) {
  9253. const c = Math.cos( theta ), s = Math.sin( theta );
  9254. this.set(
  9255. 1, 0, 0, 0,
  9256. 0, c, - s, 0,
  9257. 0, s, c, 0,
  9258. 0, 0, 0, 1
  9259. );
  9260. return this;
  9261. }
  9262. /**
  9263. * Sets this matrix as a rotational transformation around the Y axis by
  9264. * the given angle.
  9265. *
  9266. * @param {number} theta - The rotation in radians.
  9267. * @return {Matrix4} A reference to this matrix.
  9268. */
  9269. makeRotationY( theta ) {
  9270. const c = Math.cos( theta ), s = Math.sin( theta );
  9271. this.set(
  9272. c, 0, s, 0,
  9273. 0, 1, 0, 0,
  9274. - s, 0, c, 0,
  9275. 0, 0, 0, 1
  9276. );
  9277. return this;
  9278. }
  9279. /**
  9280. * Sets this matrix as a rotational transformation around the Z axis by
  9281. * the given angle.
  9282. *
  9283. * @param {number} theta - The rotation in radians.
  9284. * @return {Matrix4} A reference to this matrix.
  9285. */
  9286. makeRotationZ( theta ) {
  9287. const c = Math.cos( theta ), s = Math.sin( theta );
  9288. this.set(
  9289. c, - s, 0, 0,
  9290. s, c, 0, 0,
  9291. 0, 0, 1, 0,
  9292. 0, 0, 0, 1
  9293. );
  9294. return this;
  9295. }
  9296. /**
  9297. * Sets this matrix as a rotational transformation around the given axis by
  9298. * the given angle.
  9299. *
  9300. * This is a somewhat controversial but mathematically sound alternative to
  9301. * rotating via Quaternions. See the discussion [here]{@link https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199}.
  9302. *
  9303. * @param {Vector3} axis - The normalized rotation axis.
  9304. * @param {number} angle - The rotation in radians.
  9305. * @return {Matrix4} A reference to this matrix.
  9306. */
  9307. makeRotationAxis( axis, angle ) {
  9308. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  9309. const c = Math.cos( angle );
  9310. const s = Math.sin( angle );
  9311. const t = 1 - c;
  9312. const x = axis.x, y = axis.y, z = axis.z;
  9313. const tx = t * x, ty = t * y;
  9314. this.set(
  9315. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  9316. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  9317. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  9318. 0, 0, 0, 1
  9319. );
  9320. return this;
  9321. }
  9322. /**
  9323. * Sets this matrix as a scale transformation.
  9324. *
  9325. * @param {number} x - The amount to scale in the X axis.
  9326. * @param {number} y - The amount to scale in the Y axis.
  9327. * @param {number} z - The amount to scale in the Z axis.
  9328. * @return {Matrix4} A reference to this matrix.
  9329. */
  9330. makeScale( x, y, z ) {
  9331. this.set(
  9332. x, 0, 0, 0,
  9333. 0, y, 0, 0,
  9334. 0, 0, z, 0,
  9335. 0, 0, 0, 1
  9336. );
  9337. return this;
  9338. }
  9339. /**
  9340. * Sets this matrix as a shear transformation.
  9341. *
  9342. * @param {number} xy - The amount to shear X by Y.
  9343. * @param {number} xz - The amount to shear X by Z.
  9344. * @param {number} yx - The amount to shear Y by X.
  9345. * @param {number} yz - The amount to shear Y by Z.
  9346. * @param {number} zx - The amount to shear Z by X.
  9347. * @param {number} zy - The amount to shear Z by Y.
  9348. * @return {Matrix4} A reference to this matrix.
  9349. */
  9350. makeShear( xy, xz, yx, yz, zx, zy ) {
  9351. this.set(
  9352. 1, yx, zx, 0,
  9353. xy, 1, zy, 0,
  9354. xz, yz, 1, 0,
  9355. 0, 0, 0, 1
  9356. );
  9357. return this;
  9358. }
  9359. /**
  9360. * Sets this matrix to the transformation composed of the given position,
  9361. * rotation (Quaternion) and scale.
  9362. *
  9363. * @param {Vector3} position - The position vector.
  9364. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9365. * @param {Vector3} scale - The scale vector.
  9366. * @return {Matrix4} A reference to this matrix.
  9367. */
  9368. compose( position, quaternion, scale ) {
  9369. const te = this.elements;
  9370. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  9371. const x2 = x + x, y2 = y + y, z2 = z + z;
  9372. const xx = x * x2, xy = x * y2, xz = x * z2;
  9373. const yy = y * y2, yz = y * z2, zz = z * z2;
  9374. const wx = w * x2, wy = w * y2, wz = w * z2;
  9375. const sx = scale.x, sy = scale.y, sz = scale.z;
  9376. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  9377. te[ 1 ] = ( xy + wz ) * sx;
  9378. te[ 2 ] = ( xz - wy ) * sx;
  9379. te[ 3 ] = 0;
  9380. te[ 4 ] = ( xy - wz ) * sy;
  9381. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  9382. te[ 6 ] = ( yz + wx ) * sy;
  9383. te[ 7 ] = 0;
  9384. te[ 8 ] = ( xz + wy ) * sz;
  9385. te[ 9 ] = ( yz - wx ) * sz;
  9386. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  9387. te[ 11 ] = 0;
  9388. te[ 12 ] = position.x;
  9389. te[ 13 ] = position.y;
  9390. te[ 14 ] = position.z;
  9391. te[ 15 ] = 1;
  9392. return this;
  9393. }
  9394. /**
  9395. * Decomposes this matrix into its position, rotation and scale components
  9396. * and provides the result in the given objects.
  9397. *
  9398. * Note: Not all matrices are decomposable in this way. For example, if an
  9399. * object has a non-uniformly scaled parent, then the object's world matrix
  9400. * may not be decomposable, and this method may not be appropriate.
  9401. *
  9402. * @param {Vector3} position - The position vector.
  9403. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9404. * @param {Vector3} scale - The scale vector.
  9405. * @return {Matrix4} A reference to this matrix.
  9406. */
  9407. decompose( position, quaternion, scale ) {
  9408. const te = this.elements;
  9409. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  9410. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  9411. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  9412. // if determine is negative, we need to invert one scale
  9413. const det = this.determinant();
  9414. if ( det < 0 ) sx = - sx;
  9415. position.x = te[ 12 ];
  9416. position.y = te[ 13 ];
  9417. position.z = te[ 14 ];
  9418. // scale the rotation part
  9419. _m1$4.copy( this );
  9420. const invSX = 1 / sx;
  9421. const invSY = 1 / sy;
  9422. const invSZ = 1 / sz;
  9423. _m1$4.elements[ 0 ] *= invSX;
  9424. _m1$4.elements[ 1 ] *= invSX;
  9425. _m1$4.elements[ 2 ] *= invSX;
  9426. _m1$4.elements[ 4 ] *= invSY;
  9427. _m1$4.elements[ 5 ] *= invSY;
  9428. _m1$4.elements[ 6 ] *= invSY;
  9429. _m1$4.elements[ 8 ] *= invSZ;
  9430. _m1$4.elements[ 9 ] *= invSZ;
  9431. _m1$4.elements[ 10 ] *= invSZ;
  9432. quaternion.setFromRotationMatrix( _m1$4 );
  9433. scale.x = sx;
  9434. scale.y = sy;
  9435. scale.z = sz;
  9436. return this;
  9437. }
  9438. /**
  9439. * Creates a perspective projection matrix. This is used internally by
  9440. * {@link PerspectiveCamera#updateProjectionMatrix}.
  9441. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9442. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9443. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9444. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9445. * @param {number} near - The distance from the camera to the near plane.
  9446. * @param {number} far - The distance from the camera to the far plane.
  9447. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9448. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9449. * @return {Matrix4} A reference to this matrix.
  9450. */
  9451. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9452. const te = this.elements;
  9453. const x = 2 * near / ( right - left );
  9454. const y = 2 * near / ( top - bottom );
  9455. const a = ( right + left ) / ( right - left );
  9456. const b = ( top + bottom ) / ( top - bottom );
  9457. let c, d;
  9458. if ( reversedDepth ) {
  9459. c = near / ( far - near );
  9460. d = ( far * near ) / ( far - near );
  9461. } else {
  9462. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9463. c = - ( far + near ) / ( far - near );
  9464. d = ( -2 * far * near ) / ( far - near );
  9465. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9466. c = - far / ( far - near );
  9467. d = ( - far * near ) / ( far - near );
  9468. } else {
  9469. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  9470. }
  9471. }
  9472. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  9473. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  9474. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9475. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  9476. return this;
  9477. }
  9478. /**
  9479. * Creates a orthographic projection matrix. This is used internally by
  9480. * {@link OrthographicCamera#updateProjectionMatrix}.
  9481. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9482. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9483. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9484. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9485. * @param {number} near - The distance from the camera to the near plane.
  9486. * @param {number} far - The distance from the camera to the far plane.
  9487. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9488. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9489. * @return {Matrix4} A reference to this matrix.
  9490. */
  9491. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9492. const te = this.elements;
  9493. const x = 2 / ( right - left );
  9494. const y = 2 / ( top - bottom );
  9495. const a = - ( right + left ) / ( right - left );
  9496. const b = - ( top + bottom ) / ( top - bottom );
  9497. let c, d;
  9498. if ( reversedDepth ) {
  9499. c = 1 / ( far - near );
  9500. d = far / ( far - near );
  9501. } else {
  9502. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9503. c = -2 / ( far - near );
  9504. d = - ( far + near ) / ( far - near );
  9505. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9506. c = -1 / ( far - near );
  9507. d = - near / ( far - near );
  9508. } else {
  9509. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  9510. }
  9511. }
  9512. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = a;
  9513. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = 0; te[ 13 ] = b;
  9514. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9515. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  9516. return this;
  9517. }
  9518. /**
  9519. * Returns `true` if this matrix is equal with the given one.
  9520. *
  9521. * @param {Matrix4} matrix - The matrix to test for equality.
  9522. * @return {boolean} Whether this matrix is equal with the given one.
  9523. */
  9524. equals( matrix ) {
  9525. const te = this.elements;
  9526. const me = matrix.elements;
  9527. for ( let i = 0; i < 16; i ++ ) {
  9528. if ( te[ i ] !== me[ i ] ) return false;
  9529. }
  9530. return true;
  9531. }
  9532. /**
  9533. * Sets the elements of the matrix from the given array.
  9534. *
  9535. * @param {Array<number>} array - The matrix elements in column-major order.
  9536. * @param {number} [offset=0] - Index of the first element in the array.
  9537. * @return {Matrix4} A reference to this matrix.
  9538. */
  9539. fromArray( array, offset = 0 ) {
  9540. for ( let i = 0; i < 16; i ++ ) {
  9541. this.elements[ i ] = array[ i + offset ];
  9542. }
  9543. return this;
  9544. }
  9545. /**
  9546. * Writes the elements of this matrix to the given array. If no array is provided,
  9547. * the method returns a new instance.
  9548. *
  9549. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  9550. * @param {number} [offset=0] - Index of the first element in the array.
  9551. * @return {Array<number>} The matrix elements in column-major order.
  9552. */
  9553. toArray( array = [], offset = 0 ) {
  9554. const te = this.elements;
  9555. array[ offset ] = te[ 0 ];
  9556. array[ offset + 1 ] = te[ 1 ];
  9557. array[ offset + 2 ] = te[ 2 ];
  9558. array[ offset + 3 ] = te[ 3 ];
  9559. array[ offset + 4 ] = te[ 4 ];
  9560. array[ offset + 5 ] = te[ 5 ];
  9561. array[ offset + 6 ] = te[ 6 ];
  9562. array[ offset + 7 ] = te[ 7 ];
  9563. array[ offset + 8 ] = te[ 8 ];
  9564. array[ offset + 9 ] = te[ 9 ];
  9565. array[ offset + 10 ] = te[ 10 ];
  9566. array[ offset + 11 ] = te[ 11 ];
  9567. array[ offset + 12 ] = te[ 12 ];
  9568. array[ offset + 13 ] = te[ 13 ];
  9569. array[ offset + 14 ] = te[ 14 ];
  9570. array[ offset + 15 ] = te[ 15 ];
  9571. return array;
  9572. }
  9573. }
  9574. const _v1$5 = /*@__PURE__*/ new Vector3();
  9575. const _m1$4 = /*@__PURE__*/ new Matrix4();
  9576. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  9577. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  9578. const _x = /*@__PURE__*/ new Vector3();
  9579. const _y = /*@__PURE__*/ new Vector3();
  9580. const _z = /*@__PURE__*/ new Vector3();
  9581. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  9582. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  9583. /**
  9584. * A class representing Euler angles.
  9585. *
  9586. * Euler angles describe a rotational transformation by rotating an object on
  9587. * its various axes in specified amounts per axis, and a specified axis
  9588. * order.
  9589. *
  9590. * Iterating through an instance will yield its components (x, y, z,
  9591. * order) in the corresponding order.
  9592. *
  9593. * ```js
  9594. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  9595. * const b = new THREE.Vector3( 1, 0, 1 );
  9596. * b.applyEuler(a);
  9597. * ```
  9598. */
  9599. class Euler {
  9600. /**
  9601. * Constructs a new euler instance.
  9602. *
  9603. * @param {number} [x=0] - The angle of the x axis in radians.
  9604. * @param {number} [y=0] - The angle of the y axis in radians.
  9605. * @param {number} [z=0] - The angle of the z axis in radians.
  9606. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  9607. */
  9608. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  9609. /**
  9610. * This flag can be used for type testing.
  9611. *
  9612. * @type {boolean}
  9613. * @readonly
  9614. * @default true
  9615. */
  9616. this.isEuler = true;
  9617. this._x = x;
  9618. this._y = y;
  9619. this._z = z;
  9620. this._order = order;
  9621. }
  9622. /**
  9623. * The angle of the x axis in radians.
  9624. *
  9625. * @type {number}
  9626. * @default 0
  9627. */
  9628. get x() {
  9629. return this._x;
  9630. }
  9631. set x( value ) {
  9632. this._x = value;
  9633. this._onChangeCallback();
  9634. }
  9635. /**
  9636. * The angle of the y axis in radians.
  9637. *
  9638. * @type {number}
  9639. * @default 0
  9640. */
  9641. get y() {
  9642. return this._y;
  9643. }
  9644. set y( value ) {
  9645. this._y = value;
  9646. this._onChangeCallback();
  9647. }
  9648. /**
  9649. * The angle of the z axis in radians.
  9650. *
  9651. * @type {number}
  9652. * @default 0
  9653. */
  9654. get z() {
  9655. return this._z;
  9656. }
  9657. set z( value ) {
  9658. this._z = value;
  9659. this._onChangeCallback();
  9660. }
  9661. /**
  9662. * A string representing the order that the rotations are applied.
  9663. *
  9664. * @type {string}
  9665. * @default 'XYZ'
  9666. */
  9667. get order() {
  9668. return this._order;
  9669. }
  9670. set order( value ) {
  9671. this._order = value;
  9672. this._onChangeCallback();
  9673. }
  9674. /**
  9675. * Sets the Euler components.
  9676. *
  9677. * @param {number} x - The angle of the x axis in radians.
  9678. * @param {number} y - The angle of the y axis in radians.
  9679. * @param {number} z - The angle of the z axis in radians.
  9680. * @param {string} [order] - A string representing the order that the rotations are applied.
  9681. * @return {Euler} A reference to this Euler instance.
  9682. */
  9683. set( x, y, z, order = this._order ) {
  9684. this._x = x;
  9685. this._y = y;
  9686. this._z = z;
  9687. this._order = order;
  9688. this._onChangeCallback();
  9689. return this;
  9690. }
  9691. /**
  9692. * Returns a new Euler instance with copied values from this instance.
  9693. *
  9694. * @return {Euler} A clone of this instance.
  9695. */
  9696. clone() {
  9697. return new this.constructor( this._x, this._y, this._z, this._order );
  9698. }
  9699. /**
  9700. * Copies the values of the given Euler instance to this instance.
  9701. *
  9702. * @param {Euler} euler - The Euler instance to copy.
  9703. * @return {Euler} A reference to this Euler instance.
  9704. */
  9705. copy( euler ) {
  9706. this._x = euler._x;
  9707. this._y = euler._y;
  9708. this._z = euler._z;
  9709. this._order = euler._order;
  9710. this._onChangeCallback();
  9711. return this;
  9712. }
  9713. /**
  9714. * Sets the angles of this Euler instance from a pure rotation matrix.
  9715. *
  9716. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  9717. * @param {string} [order] - A string representing the order that the rotations are applied.
  9718. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9719. * @return {Euler} A reference to this Euler instance.
  9720. */
  9721. setFromRotationMatrix( m, order = this._order, update = true ) {
  9722. const te = m.elements;
  9723. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  9724. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  9725. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  9726. switch ( order ) {
  9727. case 'XYZ':
  9728. this._y = Math.asin( clamp( m13, -1, 1 ) );
  9729. if ( Math.abs( m13 ) < 0.9999999 ) {
  9730. this._x = Math.atan2( - m23, m33 );
  9731. this._z = Math.atan2( - m12, m11 );
  9732. } else {
  9733. this._x = Math.atan2( m32, m22 );
  9734. this._z = 0;
  9735. }
  9736. break;
  9737. case 'YXZ':
  9738. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  9739. if ( Math.abs( m23 ) < 0.9999999 ) {
  9740. this._y = Math.atan2( m13, m33 );
  9741. this._z = Math.atan2( m21, m22 );
  9742. } else {
  9743. this._y = Math.atan2( - m31, m11 );
  9744. this._z = 0;
  9745. }
  9746. break;
  9747. case 'ZXY':
  9748. this._x = Math.asin( clamp( m32, -1, 1 ) );
  9749. if ( Math.abs( m32 ) < 0.9999999 ) {
  9750. this._y = Math.atan2( - m31, m33 );
  9751. this._z = Math.atan2( - m12, m22 );
  9752. } else {
  9753. this._y = 0;
  9754. this._z = Math.atan2( m21, m11 );
  9755. }
  9756. break;
  9757. case 'ZYX':
  9758. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  9759. if ( Math.abs( m31 ) < 0.9999999 ) {
  9760. this._x = Math.atan2( m32, m33 );
  9761. this._z = Math.atan2( m21, m11 );
  9762. } else {
  9763. this._x = 0;
  9764. this._z = Math.atan2( - m12, m22 );
  9765. }
  9766. break;
  9767. case 'YZX':
  9768. this._z = Math.asin( clamp( m21, -1, 1 ) );
  9769. if ( Math.abs( m21 ) < 0.9999999 ) {
  9770. this._x = Math.atan2( - m23, m22 );
  9771. this._y = Math.atan2( - m31, m11 );
  9772. } else {
  9773. this._x = 0;
  9774. this._y = Math.atan2( m13, m33 );
  9775. }
  9776. break;
  9777. case 'XZY':
  9778. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  9779. if ( Math.abs( m12 ) < 0.9999999 ) {
  9780. this._x = Math.atan2( m32, m22 );
  9781. this._y = Math.atan2( m13, m11 );
  9782. } else {
  9783. this._x = Math.atan2( - m23, m33 );
  9784. this._y = 0;
  9785. }
  9786. break;
  9787. default:
  9788. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  9789. }
  9790. this._order = order;
  9791. if ( update === true ) this._onChangeCallback();
  9792. return this;
  9793. }
  9794. /**
  9795. * Sets the angles of this Euler instance from a normalized quaternion.
  9796. *
  9797. * @param {Quaternion} q - A normalized Quaternion.
  9798. * @param {string} [order] - A string representing the order that the rotations are applied.
  9799. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9800. * @return {Euler} A reference to this Euler instance.
  9801. */
  9802. setFromQuaternion( q, order, update ) {
  9803. _matrix$2.makeRotationFromQuaternion( q );
  9804. return this.setFromRotationMatrix( _matrix$2, order, update );
  9805. }
  9806. /**
  9807. * Sets the angles of this Euler instance from the given vector.
  9808. *
  9809. * @param {Vector3} v - The vector.
  9810. * @param {string} [order] - A string representing the order that the rotations are applied.
  9811. * @return {Euler} A reference to this Euler instance.
  9812. */
  9813. setFromVector3( v, order = this._order ) {
  9814. return this.set( v.x, v.y, v.z, order );
  9815. }
  9816. /**
  9817. * Resets the euler angle with a new order by creating a quaternion from this
  9818. * euler angle and then setting this euler angle with the quaternion and the
  9819. * new order.
  9820. *
  9821. * Warning: This discards revolution information.
  9822. *
  9823. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  9824. * @return {Euler} A reference to this Euler instance.
  9825. */
  9826. reorder( newOrder ) {
  9827. _quaternion$3.setFromEuler( this );
  9828. return this.setFromQuaternion( _quaternion$3, newOrder );
  9829. }
  9830. /**
  9831. * Returns `true` if this Euler instance is equal with the given one.
  9832. *
  9833. * @param {Euler} euler - The Euler instance to test for equality.
  9834. * @return {boolean} Whether this Euler instance is equal with the given one.
  9835. */
  9836. equals( euler ) {
  9837. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  9838. }
  9839. /**
  9840. * Sets this Euler instance's components to values from the given array. The first three
  9841. * entries of the array are assign to the x,y and z components. An optional fourth entry
  9842. * defines the Euler order.
  9843. *
  9844. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  9845. * @return {Euler} A reference to this Euler instance.
  9846. */
  9847. fromArray( array ) {
  9848. this._x = array[ 0 ];
  9849. this._y = array[ 1 ];
  9850. this._z = array[ 2 ];
  9851. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  9852. this._onChangeCallback();
  9853. return this;
  9854. }
  9855. /**
  9856. * Writes the components of this Euler instance to the given array. If no array is provided,
  9857. * the method returns a new instance.
  9858. *
  9859. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  9860. * @param {number} [offset=0] - Index of the first element in the array.
  9861. * @return {Array<number,number,number,string>} The Euler components.
  9862. */
  9863. toArray( array = [], offset = 0 ) {
  9864. array[ offset ] = this._x;
  9865. array[ offset + 1 ] = this._y;
  9866. array[ offset + 2 ] = this._z;
  9867. array[ offset + 3 ] = this._order;
  9868. return array;
  9869. }
  9870. _onChange( callback ) {
  9871. this._onChangeCallback = callback;
  9872. return this;
  9873. }
  9874. _onChangeCallback() {}
  9875. *[ Symbol.iterator ]() {
  9876. yield this._x;
  9877. yield this._y;
  9878. yield this._z;
  9879. yield this._order;
  9880. }
  9881. }
  9882. /**
  9883. * The default Euler angle order.
  9884. *
  9885. * @static
  9886. * @type {string}
  9887. * @default 'XYZ'
  9888. */
  9889. Euler.DEFAULT_ORDER = 'XYZ';
  9890. /**
  9891. * A layers object assigns an 3D object to 1 or more of 32
  9892. * layers numbered `0` to `31` - internally the layers are stored as a
  9893. * bit mask], and by default all 3D objects are a member of layer `0`.
  9894. *
  9895. * This can be used to control visibility - an object must share a layer with
  9896. * a camera to be visible when that camera's view is
  9897. * rendered.
  9898. *
  9899. * All classes that inherit from {@link Object3D} have an `layers` property which
  9900. * is an instance of this class.
  9901. */
  9902. class Layers {
  9903. /**
  9904. * Constructs a new layers instance, with membership
  9905. * initially set to layer `0`.
  9906. */
  9907. constructor() {
  9908. /**
  9909. * A bit mask storing which of the 32 layers this layers object is currently
  9910. * a member of.
  9911. *
  9912. * @type {number}
  9913. */
  9914. this.mask = 1 | 0;
  9915. }
  9916. /**
  9917. * Sets membership to the given layer, and remove membership all other layers.
  9918. *
  9919. * @param {number} layer - The layer to set.
  9920. */
  9921. set( layer ) {
  9922. this.mask = ( 1 << layer | 0 ) >>> 0;
  9923. }
  9924. /**
  9925. * Adds membership of the given layer.
  9926. *
  9927. * @param {number} layer - The layer to enable.
  9928. */
  9929. enable( layer ) {
  9930. this.mask |= 1 << layer | 0;
  9931. }
  9932. /**
  9933. * Adds membership to all layers.
  9934. */
  9935. enableAll() {
  9936. this.mask = 0xffffffff | 0;
  9937. }
  9938. /**
  9939. * Toggles the membership of the given layer.
  9940. *
  9941. * @param {number} layer - The layer to toggle.
  9942. */
  9943. toggle( layer ) {
  9944. this.mask ^= 1 << layer | 0;
  9945. }
  9946. /**
  9947. * Removes membership of the given layer.
  9948. *
  9949. * @param {number} layer - The layer to enable.
  9950. */
  9951. disable( layer ) {
  9952. this.mask &= ~ ( 1 << layer | 0 );
  9953. }
  9954. /**
  9955. * Removes the membership from all layers.
  9956. */
  9957. disableAll() {
  9958. this.mask = 0;
  9959. }
  9960. /**
  9961. * Returns `true` if this and the given layers object have at least one
  9962. * layer in common.
  9963. *
  9964. * @param {Layers} layers - The layers to test.
  9965. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  9966. */
  9967. test( layers ) {
  9968. return ( this.mask & layers.mask ) !== 0;
  9969. }
  9970. /**
  9971. * Returns `true` if the given layer is enabled.
  9972. *
  9973. * @param {number} layer - The layer to test.
  9974. * @return {boolean } Whether the given layer is enabled or not.
  9975. */
  9976. isEnabled( layer ) {
  9977. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  9978. }
  9979. }
  9980. let _object3DId = 0;
  9981. const _v1$4 = /*@__PURE__*/ new Vector3();
  9982. const _q1 = /*@__PURE__*/ new Quaternion();
  9983. const _m1$3 = /*@__PURE__*/ new Matrix4();
  9984. const _target = /*@__PURE__*/ new Vector3();
  9985. const _position$3 = /*@__PURE__*/ new Vector3();
  9986. const _scale$2 = /*@__PURE__*/ new Vector3();
  9987. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  9988. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  9989. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  9990. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  9991. /**
  9992. * Fires when the object has been added to its parent object.
  9993. *
  9994. * @event Object3D#added
  9995. * @type {Object}
  9996. */
  9997. const _addedEvent = { type: 'added' };
  9998. /**
  9999. * Fires when the object has been removed from its parent object.
  10000. *
  10001. * @event Object3D#removed
  10002. * @type {Object}
  10003. */
  10004. const _removedEvent = { type: 'removed' };
  10005. /**
  10006. * Fires when a new child object has been added.
  10007. *
  10008. * @event Object3D#childadded
  10009. * @type {Object}
  10010. */
  10011. const _childaddedEvent = { type: 'childadded', child: null };
  10012. /**
  10013. * Fires when a child object has been removed.
  10014. *
  10015. * @event Object3D#childremoved
  10016. * @type {Object}
  10017. */
  10018. const _childremovedEvent = { type: 'childremoved', child: null };
  10019. /**
  10020. * This is the base class for most objects in three.js and provides a set of
  10021. * properties and methods for manipulating objects in 3D space.
  10022. *
  10023. * @augments EventDispatcher
  10024. */
  10025. class Object3D extends EventDispatcher {
  10026. /**
  10027. * Constructs a new 3D object.
  10028. */
  10029. constructor() {
  10030. super();
  10031. /**
  10032. * This flag can be used for type testing.
  10033. *
  10034. * @type {boolean}
  10035. * @readonly
  10036. * @default true
  10037. */
  10038. this.isObject3D = true;
  10039. /**
  10040. * The ID of the 3D object.
  10041. *
  10042. * @name Object3D#id
  10043. * @type {number}
  10044. * @readonly
  10045. */
  10046. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  10047. /**
  10048. * The UUID of the 3D object.
  10049. *
  10050. * @type {string}
  10051. * @readonly
  10052. */
  10053. this.uuid = generateUUID();
  10054. /**
  10055. * The name of the 3D object.
  10056. *
  10057. * @type {string}
  10058. */
  10059. this.name = '';
  10060. /**
  10061. * The type property is used for detecting the object type
  10062. * in context of serialization/deserialization.
  10063. *
  10064. * @type {string}
  10065. * @readonly
  10066. */
  10067. this.type = 'Object3D';
  10068. /**
  10069. * A reference to the parent object.
  10070. *
  10071. * @type {?Object3D}
  10072. * @default null
  10073. */
  10074. this.parent = null;
  10075. /**
  10076. * An array holding the child 3D objects of this instance.
  10077. *
  10078. * @type {Array<Object3D>}
  10079. */
  10080. this.children = [];
  10081. /**
  10082. * Defines the `up` direction of the 3D object which influences
  10083. * the orientation via methods like {@link Object3D#lookAt}.
  10084. *
  10085. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  10086. *
  10087. * @type {Vector3}
  10088. */
  10089. this.up = Object3D.DEFAULT_UP.clone();
  10090. const position = new Vector3();
  10091. const rotation = new Euler();
  10092. const quaternion = new Quaternion();
  10093. const scale = new Vector3( 1, 1, 1 );
  10094. function onRotationChange() {
  10095. quaternion.setFromEuler( rotation, false );
  10096. }
  10097. function onQuaternionChange() {
  10098. rotation.setFromQuaternion( quaternion, undefined, false );
  10099. }
  10100. rotation._onChange( onRotationChange );
  10101. quaternion._onChange( onQuaternionChange );
  10102. Object.defineProperties( this, {
  10103. /**
  10104. * Represents the object's local position.
  10105. *
  10106. * @name Object3D#position
  10107. * @type {Vector3}
  10108. * @default (0,0,0)
  10109. */
  10110. position: {
  10111. configurable: true,
  10112. enumerable: true,
  10113. value: position
  10114. },
  10115. /**
  10116. * Represents the object's local rotation as Euler angles, in radians.
  10117. *
  10118. * @name Object3D#rotation
  10119. * @type {Euler}
  10120. * @default (0,0,0)
  10121. */
  10122. rotation: {
  10123. configurable: true,
  10124. enumerable: true,
  10125. value: rotation
  10126. },
  10127. /**
  10128. * Represents the object's local rotation as Quaternions.
  10129. *
  10130. * @name Object3D#quaternion
  10131. * @type {Quaternion}
  10132. */
  10133. quaternion: {
  10134. configurable: true,
  10135. enumerable: true,
  10136. value: quaternion
  10137. },
  10138. /**
  10139. * Represents the object's local scale.
  10140. *
  10141. * @name Object3D#scale
  10142. * @type {Vector3}
  10143. * @default (1,1,1)
  10144. */
  10145. scale: {
  10146. configurable: true,
  10147. enumerable: true,
  10148. value: scale
  10149. },
  10150. /**
  10151. * Represents the object's model-view matrix.
  10152. *
  10153. * @name Object3D#modelViewMatrix
  10154. * @type {Matrix4}
  10155. */
  10156. modelViewMatrix: {
  10157. value: new Matrix4()
  10158. },
  10159. /**
  10160. * Represents the object's normal matrix.
  10161. *
  10162. * @name Object3D#normalMatrix
  10163. * @type {Matrix3}
  10164. */
  10165. normalMatrix: {
  10166. value: new Matrix3()
  10167. }
  10168. } );
  10169. /**
  10170. * Represents the object's transformation matrix in local space.
  10171. *
  10172. * @type {Matrix4}
  10173. */
  10174. this.matrix = new Matrix4();
  10175. /**
  10176. * Represents the object's transformation matrix in world space.
  10177. * If the 3D object has no parent, then it's identical to the local transformation matrix
  10178. *
  10179. * @type {Matrix4}
  10180. */
  10181. this.matrixWorld = new Matrix4();
  10182. /**
  10183. * When set to `true`, the engine automatically computes the local matrix from position,
  10184. * rotation and scale every frame.
  10185. *
  10186. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  10187. *
  10188. * @type {boolean}
  10189. * @default true
  10190. */
  10191. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  10192. /**
  10193. * When set to `true`, the engine automatically computes the world matrix from the current local
  10194. * matrix and the object's transformation hierarchy.
  10195. *
  10196. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  10197. *
  10198. * @type {boolean}
  10199. * @default true
  10200. */
  10201. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  10202. /**
  10203. * When set to `true`, it calculates the world matrix in that frame and resets this property
  10204. * to `false`.
  10205. *
  10206. * @type {boolean}
  10207. * @default false
  10208. */
  10209. this.matrixWorldNeedsUpdate = false;
  10210. /**
  10211. * The layer membership of the 3D object. The 3D object is only visible if it has
  10212. * at least one layer in common with the camera in use. This property can also be
  10213. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  10214. *
  10215. * @type {Layers}
  10216. */
  10217. this.layers = new Layers();
  10218. /**
  10219. * When set to `true`, the 3D object gets rendered.
  10220. *
  10221. * @type {boolean}
  10222. * @default true
  10223. */
  10224. this.visible = true;
  10225. /**
  10226. * When set to `true`, the 3D object gets rendered into shadow maps.
  10227. *
  10228. * @type {boolean}
  10229. * @default false
  10230. */
  10231. this.castShadow = false;
  10232. /**
  10233. * When set to `true`, the 3D object is affected by shadows in the scene.
  10234. *
  10235. * @type {boolean}
  10236. * @default false
  10237. */
  10238. this.receiveShadow = false;
  10239. /**
  10240. * When set to `true`, the 3D object is honored by view frustum culling.
  10241. *
  10242. * @type {boolean}
  10243. * @default true
  10244. */
  10245. this.frustumCulled = true;
  10246. /**
  10247. * This value allows the default rendering order of scene graph objects to be
  10248. * overridden although opaque and transparent objects remain sorted independently.
  10249. * When this property is set for an instance of {@link Group},all descendants
  10250. * objects will be sorted and rendered together. Sorting is from lowest to highest
  10251. * render order.
  10252. *
  10253. * @type {number}
  10254. * @default 0
  10255. */
  10256. this.renderOrder = 0;
  10257. /**
  10258. * An array holding the animation clips of the 3D object.
  10259. *
  10260. * @type {Array<AnimationClip>}
  10261. */
  10262. this.animations = [];
  10263. /**
  10264. * Custom depth material to be used when rendering to the depth map. Can only be used
  10265. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  10266. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  10267. * material for proper shadows.
  10268. *
  10269. * Only relevant in context of {@link WebGLRenderer}.
  10270. *
  10271. * @type {(Material|undefined)}
  10272. * @default undefined
  10273. */
  10274. this.customDepthMaterial = undefined;
  10275. /**
  10276. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  10277. *
  10278. * Only relevant in context of {@link WebGLRenderer}.
  10279. *
  10280. * @type {(Material|undefined)}
  10281. * @default undefined
  10282. */
  10283. this.customDistanceMaterial = undefined;
  10284. /**
  10285. * An object that can be used to store custom data about the 3D object. It
  10286. * should not hold references to functions as these will not be cloned.
  10287. *
  10288. * @type {Object}
  10289. */
  10290. this.userData = {};
  10291. }
  10292. /**
  10293. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  10294. *
  10295. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10296. * @param {Object3D} object - The 3D object.
  10297. * @param {Camera} camera - The camera that is used to render the scene.
  10298. * @param {Camera} shadowCamera - The shadow camera.
  10299. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10300. * @param {Material} depthMaterial - The depth material.
  10301. * @param {Object} group - The geometry group data.
  10302. */
  10303. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10304. /**
  10305. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  10306. *
  10307. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10308. * @param {Object3D} object - The 3D object.
  10309. * @param {Camera} camera - The camera that is used to render the scene.
  10310. * @param {Camera} shadowCamera - The shadow camera.
  10311. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10312. * @param {Material} depthMaterial - The depth material.
  10313. * @param {Object} group - The geometry group data.
  10314. */
  10315. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10316. /**
  10317. * A callback that is executed immediately before a 3D object is rendered.
  10318. *
  10319. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10320. * @param {Object3D} object - The 3D object.
  10321. * @param {Camera} camera - The camera that is used to render the scene.
  10322. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10323. * @param {Material} material - The 3D object's material.
  10324. * @param {Object} group - The geometry group data.
  10325. */
  10326. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10327. /**
  10328. * A callback that is executed immediately after a 3D object is rendered.
  10329. *
  10330. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10331. * @param {Object3D} object - The 3D object.
  10332. * @param {Camera} camera - The camera that is used to render the scene.
  10333. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10334. * @param {Material} material - The 3D object's material.
  10335. * @param {Object} group - The geometry group data.
  10336. */
  10337. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10338. /**
  10339. * Applies the given transformation matrix to the object and updates the object's position,
  10340. * rotation and scale.
  10341. *
  10342. * @param {Matrix4} matrix - The transformation matrix.
  10343. */
  10344. applyMatrix4( matrix ) {
  10345. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10346. this.matrix.premultiply( matrix );
  10347. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10348. }
  10349. /**
  10350. * Applies a rotation represented by given the quaternion to the 3D object.
  10351. *
  10352. * @param {Quaternion} q - The quaternion.
  10353. * @return {Object3D} A reference to this instance.
  10354. */
  10355. applyQuaternion( q ) {
  10356. this.quaternion.premultiply( q );
  10357. return this;
  10358. }
  10359. /**
  10360. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  10361. *
  10362. * @param {Vector3} axis - The (normalized) axis vector.
  10363. * @param {number} angle - The angle in radians.
  10364. */
  10365. setRotationFromAxisAngle( axis, angle ) {
  10366. // assumes axis is normalized
  10367. this.quaternion.setFromAxisAngle( axis, angle );
  10368. }
  10369. /**
  10370. * Sets the given rotation represented as Euler angles to the 3D object.
  10371. *
  10372. * @param {Euler} euler - The Euler angles.
  10373. */
  10374. setRotationFromEuler( euler ) {
  10375. this.quaternion.setFromEuler( euler, true );
  10376. }
  10377. /**
  10378. * Sets the given rotation represented as rotation matrix to the 3D object.
  10379. *
  10380. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  10381. * a pure rotation matrix (i.e, unscaled).
  10382. */
  10383. setRotationFromMatrix( m ) {
  10384. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10385. this.quaternion.setFromRotationMatrix( m );
  10386. }
  10387. /**
  10388. * Sets the given rotation represented as a Quaternion to the 3D object.
  10389. *
  10390. * @param {Quaternion} q - The Quaternion
  10391. */
  10392. setRotationFromQuaternion( q ) {
  10393. // assumes q is normalized
  10394. this.quaternion.copy( q );
  10395. }
  10396. /**
  10397. * Rotates the 3D object along an axis in local space.
  10398. *
  10399. * @param {Vector3} axis - The (normalized) axis vector.
  10400. * @param {number} angle - The angle in radians.
  10401. * @return {Object3D} A reference to this instance.
  10402. */
  10403. rotateOnAxis( axis, angle ) {
  10404. // rotate object on axis in object space
  10405. // axis is assumed to be normalized
  10406. _q1.setFromAxisAngle( axis, angle );
  10407. this.quaternion.multiply( _q1 );
  10408. return this;
  10409. }
  10410. /**
  10411. * Rotates the 3D object along an axis in world space.
  10412. *
  10413. * @param {Vector3} axis - The (normalized) axis vector.
  10414. * @param {number} angle - The angle in radians.
  10415. * @return {Object3D} A reference to this instance.
  10416. */
  10417. rotateOnWorldAxis( axis, angle ) {
  10418. // rotate object on axis in world space
  10419. // axis is assumed to be normalized
  10420. // method assumes no rotated parent
  10421. _q1.setFromAxisAngle( axis, angle );
  10422. this.quaternion.premultiply( _q1 );
  10423. return this;
  10424. }
  10425. /**
  10426. * Rotates the 3D object around its X axis in local space.
  10427. *
  10428. * @param {number} angle - The angle in radians.
  10429. * @return {Object3D} A reference to this instance.
  10430. */
  10431. rotateX( angle ) {
  10432. return this.rotateOnAxis( _xAxis, angle );
  10433. }
  10434. /**
  10435. * Rotates the 3D object around its Y axis in local space.
  10436. *
  10437. * @param {number} angle - The angle in radians.
  10438. * @return {Object3D} A reference to this instance.
  10439. */
  10440. rotateY( angle ) {
  10441. return this.rotateOnAxis( _yAxis, angle );
  10442. }
  10443. /**
  10444. * Rotates the 3D object around its Z axis in local space.
  10445. *
  10446. * @param {number} angle - The angle in radians.
  10447. * @return {Object3D} A reference to this instance.
  10448. */
  10449. rotateZ( angle ) {
  10450. return this.rotateOnAxis( _zAxis, angle );
  10451. }
  10452. /**
  10453. * Translate the 3D object by a distance along the given axis in local space.
  10454. *
  10455. * @param {Vector3} axis - The (normalized) axis vector.
  10456. * @param {number} distance - The distance in world units.
  10457. * @return {Object3D} A reference to this instance.
  10458. */
  10459. translateOnAxis( axis, distance ) {
  10460. // translate object by distance along axis in object space
  10461. // axis is assumed to be normalized
  10462. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  10463. this.position.add( _v1$4.multiplyScalar( distance ) );
  10464. return this;
  10465. }
  10466. /**
  10467. * Translate the 3D object by a distance along its X-axis in local space.
  10468. *
  10469. * @param {number} distance - The distance in world units.
  10470. * @return {Object3D} A reference to this instance.
  10471. */
  10472. translateX( distance ) {
  10473. return this.translateOnAxis( _xAxis, distance );
  10474. }
  10475. /**
  10476. * Translate the 3D object by a distance along its Y-axis in local space.
  10477. *
  10478. * @param {number} distance - The distance in world units.
  10479. * @return {Object3D} A reference to this instance.
  10480. */
  10481. translateY( distance ) {
  10482. return this.translateOnAxis( _yAxis, distance );
  10483. }
  10484. /**
  10485. * Translate the 3D object by a distance along its Z-axis in local space.
  10486. *
  10487. * @param {number} distance - The distance in world units.
  10488. * @return {Object3D} A reference to this instance.
  10489. */
  10490. translateZ( distance ) {
  10491. return this.translateOnAxis( _zAxis, distance );
  10492. }
  10493. /**
  10494. * Converts the given vector from this 3D object's local space to world space.
  10495. *
  10496. * @param {Vector3} vector - The vector to convert.
  10497. * @return {Vector3} The converted vector.
  10498. */
  10499. localToWorld( vector ) {
  10500. this.updateWorldMatrix( true, false );
  10501. return vector.applyMatrix4( this.matrixWorld );
  10502. }
  10503. /**
  10504. * Converts the given vector from this 3D object's word space to local space.
  10505. *
  10506. * @param {Vector3} vector - The vector to convert.
  10507. * @return {Vector3} The converted vector.
  10508. */
  10509. worldToLocal( vector ) {
  10510. this.updateWorldMatrix( true, false );
  10511. return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() );
  10512. }
  10513. /**
  10514. * Rotates the object to face a point in world space.
  10515. *
  10516. * This method does not support objects having non-uniformly-scaled parent(s).
  10517. *
  10518. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  10519. * @param {number} [y] - The y coordinate in world space.
  10520. * @param {number} [z] - The z coordinate in world space.
  10521. */
  10522. lookAt( x, y, z ) {
  10523. // This method does not support objects having non-uniformly-scaled parent(s)
  10524. if ( x.isVector3 ) {
  10525. _target.copy( x );
  10526. } else {
  10527. _target.set( x, y, z );
  10528. }
  10529. const parent = this.parent;
  10530. this.updateWorldMatrix( true, false );
  10531. _position$3.setFromMatrixPosition( this.matrixWorld );
  10532. if ( this.isCamera || this.isLight ) {
  10533. _m1$3.lookAt( _position$3, _target, this.up );
  10534. } else {
  10535. _m1$3.lookAt( _target, _position$3, this.up );
  10536. }
  10537. this.quaternion.setFromRotationMatrix( _m1$3 );
  10538. if ( parent ) {
  10539. _m1$3.extractRotation( parent.matrixWorld );
  10540. _q1.setFromRotationMatrix( _m1$3 );
  10541. this.quaternion.premultiply( _q1.invert() );
  10542. }
  10543. }
  10544. /**
  10545. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  10546. * objects may be added. Any current parent on an object passed in here will be
  10547. * removed, since an object can have at most one parent.
  10548. *
  10549. * @fires Object3D#added
  10550. * @fires Object3D#childadded
  10551. * @param {Object3D} object - The 3D object to add.
  10552. * @return {Object3D} A reference to this instance.
  10553. */
  10554. add( object ) {
  10555. if ( arguments.length > 1 ) {
  10556. for ( let i = 0; i < arguments.length; i ++ ) {
  10557. this.add( arguments[ i ] );
  10558. }
  10559. return this;
  10560. }
  10561. if ( object === this ) {
  10562. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  10563. return this;
  10564. }
  10565. if ( object && object.isObject3D ) {
  10566. object.removeFromParent();
  10567. object.parent = this;
  10568. this.children.push( object );
  10569. object.dispatchEvent( _addedEvent );
  10570. _childaddedEvent.child = object;
  10571. this.dispatchEvent( _childaddedEvent );
  10572. _childaddedEvent.child = null;
  10573. } else {
  10574. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  10575. }
  10576. return this;
  10577. }
  10578. /**
  10579. * Removes the given 3D object as child from this 3D object.
  10580. * An arbitrary number of objects may be removed.
  10581. *
  10582. * @fires Object3D#removed
  10583. * @fires Object3D#childremoved
  10584. * @param {Object3D} object - The 3D object to remove.
  10585. * @return {Object3D} A reference to this instance.
  10586. */
  10587. remove( object ) {
  10588. if ( arguments.length > 1 ) {
  10589. for ( let i = 0; i < arguments.length; i ++ ) {
  10590. this.remove( arguments[ i ] );
  10591. }
  10592. return this;
  10593. }
  10594. const index = this.children.indexOf( object );
  10595. if ( index !== -1 ) {
  10596. object.parent = null;
  10597. this.children.splice( index, 1 );
  10598. object.dispatchEvent( _removedEvent );
  10599. _childremovedEvent.child = object;
  10600. this.dispatchEvent( _childremovedEvent );
  10601. _childremovedEvent.child = null;
  10602. }
  10603. return this;
  10604. }
  10605. /**
  10606. * Removes this 3D object from its current parent.
  10607. *
  10608. * @fires Object3D#removed
  10609. * @fires Object3D#childremoved
  10610. * @return {Object3D} A reference to this instance.
  10611. */
  10612. removeFromParent() {
  10613. const parent = this.parent;
  10614. if ( parent !== null ) {
  10615. parent.remove( this );
  10616. }
  10617. return this;
  10618. }
  10619. /**
  10620. * Removes all child objects.
  10621. *
  10622. * @fires Object3D#removed
  10623. * @fires Object3D#childremoved
  10624. * @return {Object3D} A reference to this instance.
  10625. */
  10626. clear() {
  10627. return this.remove( ... this.children );
  10628. }
  10629. /**
  10630. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  10631. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  10632. *
  10633. * @fires Object3D#added
  10634. * @fires Object3D#childadded
  10635. * @param {Object3D} object - The 3D object to attach.
  10636. * @return {Object3D} A reference to this instance.
  10637. */
  10638. attach( object ) {
  10639. // adds object as a child of this, while maintaining the object's world transform
  10640. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  10641. this.updateWorldMatrix( true, false );
  10642. _m1$3.copy( this.matrixWorld ).invert();
  10643. if ( object.parent !== null ) {
  10644. object.parent.updateWorldMatrix( true, false );
  10645. _m1$3.multiply( object.parent.matrixWorld );
  10646. }
  10647. object.applyMatrix4( _m1$3 );
  10648. object.removeFromParent();
  10649. object.parent = this;
  10650. this.children.push( object );
  10651. object.updateWorldMatrix( false, true );
  10652. object.dispatchEvent( _addedEvent );
  10653. _childaddedEvent.child = object;
  10654. this.dispatchEvent( _childaddedEvent );
  10655. _childaddedEvent.child = null;
  10656. return this;
  10657. }
  10658. /**
  10659. * Searches through the 3D object and its children, starting with the 3D object
  10660. * itself, and returns the first with a matching ID.
  10661. *
  10662. * @param {number} id - The id.
  10663. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10664. */
  10665. getObjectById( id ) {
  10666. return this.getObjectByProperty( 'id', id );
  10667. }
  10668. /**
  10669. * Searches through the 3D object and its children, starting with the 3D object
  10670. * itself, and returns the first with a matching name.
  10671. *
  10672. * @param {string} name - The name.
  10673. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10674. */
  10675. getObjectByName( name ) {
  10676. return this.getObjectByProperty( 'name', name );
  10677. }
  10678. /**
  10679. * Searches through the 3D object and its children, starting with the 3D object
  10680. * itself, and returns the first with a matching property value.
  10681. *
  10682. * @param {string} name - The name of the property.
  10683. * @param {any} value - The value.
  10684. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10685. */
  10686. getObjectByProperty( name, value ) {
  10687. if ( this[ name ] === value ) return this;
  10688. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  10689. const child = this.children[ i ];
  10690. const object = child.getObjectByProperty( name, value );
  10691. if ( object !== undefined ) {
  10692. return object;
  10693. }
  10694. }
  10695. return undefined;
  10696. }
  10697. /**
  10698. * Searches through the 3D object and its children, starting with the 3D object
  10699. * itself, and returns all 3D objects with a matching property value.
  10700. *
  10701. * @param {string} name - The name of the property.
  10702. * @param {any} value - The value.
  10703. * @param {Array<Object3D>} result - The method stores the result in this array.
  10704. * @return {Array<Object3D>} The found 3D objects.
  10705. */
  10706. getObjectsByProperty( name, value, result = [] ) {
  10707. if ( this[ name ] === value ) result.push( this );
  10708. const children = this.children;
  10709. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10710. children[ i ].getObjectsByProperty( name, value, result );
  10711. }
  10712. return result;
  10713. }
  10714. /**
  10715. * Returns a vector representing the position of the 3D object in world space.
  10716. *
  10717. * @param {Vector3} target - The target vector the result is stored to.
  10718. * @return {Vector3} The 3D object's position in world space.
  10719. */
  10720. getWorldPosition( target ) {
  10721. this.updateWorldMatrix( true, false );
  10722. return target.setFromMatrixPosition( this.matrixWorld );
  10723. }
  10724. /**
  10725. * Returns a Quaternion representing the position of the 3D object in world space.
  10726. *
  10727. * @param {Quaternion} target - The target Quaternion the result is stored to.
  10728. * @return {Quaternion} The 3D object's rotation in world space.
  10729. */
  10730. getWorldQuaternion( target ) {
  10731. this.updateWorldMatrix( true, false );
  10732. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  10733. return target;
  10734. }
  10735. /**
  10736. * Returns a vector representing the scale of the 3D object in world space.
  10737. *
  10738. * @param {Vector3} target - The target vector the result is stored to.
  10739. * @return {Vector3} The 3D object's scale in world space.
  10740. */
  10741. getWorldScale( target ) {
  10742. this.updateWorldMatrix( true, false );
  10743. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  10744. return target;
  10745. }
  10746. /**
  10747. * Returns a vector representing the ("look") direction 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 direction in world space.
  10751. */
  10752. getWorldDirection( target ) {
  10753. this.updateWorldMatrix( true, false );
  10754. const e = this.matrixWorld.elements;
  10755. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  10756. }
  10757. /**
  10758. * Abstract method to get intersections between a casted ray and this
  10759. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  10760. * implement this method in order to use raycasting.
  10761. *
  10762. * @abstract
  10763. * @param {Raycaster} raycaster - The raycaster.
  10764. * @param {Array<Object>} intersects - An array holding the result of the method.
  10765. */
  10766. raycast( /* raycaster, intersects */ ) {}
  10767. /**
  10768. * Executes the callback on this 3D object and all descendants.
  10769. *
  10770. * Note: Modifying the scene graph inside the callback is discouraged.
  10771. *
  10772. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10773. */
  10774. traverse( callback ) {
  10775. callback( this );
  10776. const children = this.children;
  10777. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10778. children[ i ].traverse( callback );
  10779. }
  10780. }
  10781. /**
  10782. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  10783. * Descendants of invisible 3D objects are not traversed.
  10784. *
  10785. * Note: Modifying the scene graph inside the callback is discouraged.
  10786. *
  10787. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10788. */
  10789. traverseVisible( callback ) {
  10790. if ( this.visible === false ) return;
  10791. callback( this );
  10792. const children = this.children;
  10793. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10794. children[ i ].traverseVisible( callback );
  10795. }
  10796. }
  10797. /**
  10798. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  10799. *
  10800. * Note: Modifying the scene graph inside the callback is discouraged.
  10801. *
  10802. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10803. */
  10804. traverseAncestors( callback ) {
  10805. const parent = this.parent;
  10806. if ( parent !== null ) {
  10807. callback( parent );
  10808. parent.traverseAncestors( callback );
  10809. }
  10810. }
  10811. /**
  10812. * Updates the transformation matrix in local space by computing it from the current
  10813. * position, rotation and scale values.
  10814. */
  10815. updateMatrix() {
  10816. this.matrix.compose( this.position, this.quaternion, this.scale );
  10817. this.matrixWorldNeedsUpdate = true;
  10818. }
  10819. /**
  10820. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  10821. *
  10822. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  10823. * local space. The computation of the local and world matrix can be controlled with the
  10824. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  10825. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  10826. *
  10827. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  10828. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  10829. */
  10830. updateMatrixWorld( force ) {
  10831. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10832. if ( this.matrixWorldNeedsUpdate || force ) {
  10833. if ( this.matrixWorldAutoUpdate === true ) {
  10834. if ( this.parent === null ) {
  10835. this.matrixWorld.copy( this.matrix );
  10836. } else {
  10837. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10838. }
  10839. }
  10840. this.matrixWorldNeedsUpdate = false;
  10841. force = true;
  10842. }
  10843. // make sure descendants are updated if required
  10844. const children = this.children;
  10845. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10846. const child = children[ i ];
  10847. child.updateMatrixWorld( force );
  10848. }
  10849. }
  10850. /**
  10851. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  10852. * update of ancestor and descendant nodes.
  10853. *
  10854. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  10855. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  10856. */
  10857. updateWorldMatrix( updateParents, updateChildren ) {
  10858. const parent = this.parent;
  10859. if ( updateParents === true && parent !== null ) {
  10860. parent.updateWorldMatrix( true, false );
  10861. }
  10862. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10863. if ( this.matrixWorldAutoUpdate === true ) {
  10864. if ( this.parent === null ) {
  10865. this.matrixWorld.copy( this.matrix );
  10866. } else {
  10867. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10868. }
  10869. }
  10870. // make sure descendants are updated
  10871. if ( updateChildren === true ) {
  10872. const children = this.children;
  10873. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10874. const child = children[ i ];
  10875. child.updateWorldMatrix( false, true );
  10876. }
  10877. }
  10878. }
  10879. /**
  10880. * Serializes the 3D object into JSON.
  10881. *
  10882. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  10883. * @return {Object} A JSON object representing the serialized 3D object.
  10884. * @see {@link ObjectLoader#parse}
  10885. */
  10886. toJSON( meta ) {
  10887. // meta is a string when called from JSON.stringify
  10888. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  10889. const output = {};
  10890. // meta is a hash used to collect geometries, materials.
  10891. // not providing it implies that this is the root object
  10892. // being serialized.
  10893. if ( isRootObject ) {
  10894. // initialize meta obj
  10895. meta = {
  10896. geometries: {},
  10897. materials: {},
  10898. textures: {},
  10899. images: {},
  10900. shapes: {},
  10901. skeletons: {},
  10902. animations: {},
  10903. nodes: {}
  10904. };
  10905. output.metadata = {
  10906. version: 4.7,
  10907. type: 'Object',
  10908. generator: 'Object3D.toJSON'
  10909. };
  10910. }
  10911. // standard Object3D serialization
  10912. const object = {};
  10913. object.uuid = this.uuid;
  10914. object.type = this.type;
  10915. if ( this.name !== '' ) object.name = this.name;
  10916. if ( this.castShadow === true ) object.castShadow = true;
  10917. if ( this.receiveShadow === true ) object.receiveShadow = true;
  10918. if ( this.visible === false ) object.visible = false;
  10919. if ( this.frustumCulled === false ) object.frustumCulled = false;
  10920. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  10921. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  10922. object.layers = this.layers.mask;
  10923. object.matrix = this.matrix.toArray();
  10924. object.up = this.up.toArray();
  10925. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  10926. // object specific properties
  10927. if ( this.isInstancedMesh ) {
  10928. object.type = 'InstancedMesh';
  10929. object.count = this.count;
  10930. object.instanceMatrix = this.instanceMatrix.toJSON();
  10931. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  10932. }
  10933. if ( this.isBatchedMesh ) {
  10934. object.type = 'BatchedMesh';
  10935. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  10936. object.sortObjects = this.sortObjects;
  10937. object.drawRanges = this._drawRanges;
  10938. object.reservedRanges = this._reservedRanges;
  10939. object.geometryInfo = this._geometryInfo.map( info => ( {
  10940. ...info,
  10941. boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
  10942. boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
  10943. } ) );
  10944. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  10945. object.availableInstanceIds = this._availableInstanceIds.slice();
  10946. object.availableGeometryIds = this._availableGeometryIds.slice();
  10947. object.nextIndexStart = this._nextIndexStart;
  10948. object.nextVertexStart = this._nextVertexStart;
  10949. object.geometryCount = this._geometryCount;
  10950. object.maxInstanceCount = this._maxInstanceCount;
  10951. object.maxVertexCount = this._maxVertexCount;
  10952. object.maxIndexCount = this._maxIndexCount;
  10953. object.geometryInitialized = this._geometryInitialized;
  10954. object.matricesTexture = this._matricesTexture.toJSON( meta );
  10955. object.indirectTexture = this._indirectTexture.toJSON( meta );
  10956. if ( this._colorsTexture !== null ) {
  10957. object.colorsTexture = this._colorsTexture.toJSON( meta );
  10958. }
  10959. if ( this.boundingSphere !== null ) {
  10960. object.boundingSphere = this.boundingSphere.toJSON();
  10961. }
  10962. if ( this.boundingBox !== null ) {
  10963. object.boundingBox = this.boundingBox.toJSON();
  10964. }
  10965. }
  10966. //
  10967. function serialize( library, element ) {
  10968. if ( library[ element.uuid ] === undefined ) {
  10969. library[ element.uuid ] = element.toJSON( meta );
  10970. }
  10971. return element.uuid;
  10972. }
  10973. if ( this.isScene ) {
  10974. if ( this.background ) {
  10975. if ( this.background.isColor ) {
  10976. object.background = this.background.toJSON();
  10977. } else if ( this.background.isTexture ) {
  10978. object.background = this.background.toJSON( meta ).uuid;
  10979. }
  10980. }
  10981. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  10982. object.environment = this.environment.toJSON( meta ).uuid;
  10983. }
  10984. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  10985. object.geometry = serialize( meta.geometries, this.geometry );
  10986. const parameters = this.geometry.parameters;
  10987. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  10988. const shapes = parameters.shapes;
  10989. if ( Array.isArray( shapes ) ) {
  10990. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  10991. const shape = shapes[ i ];
  10992. serialize( meta.shapes, shape );
  10993. }
  10994. } else {
  10995. serialize( meta.shapes, shapes );
  10996. }
  10997. }
  10998. }
  10999. if ( this.isSkinnedMesh ) {
  11000. object.bindMode = this.bindMode;
  11001. object.bindMatrix = this.bindMatrix.toArray();
  11002. if ( this.skeleton !== undefined ) {
  11003. serialize( meta.skeletons, this.skeleton );
  11004. object.skeleton = this.skeleton.uuid;
  11005. }
  11006. }
  11007. if ( this.material !== undefined ) {
  11008. if ( Array.isArray( this.material ) ) {
  11009. const uuids = [];
  11010. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  11011. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  11012. }
  11013. object.material = uuids;
  11014. } else {
  11015. object.material = serialize( meta.materials, this.material );
  11016. }
  11017. }
  11018. //
  11019. if ( this.children.length > 0 ) {
  11020. object.children = [];
  11021. for ( let i = 0; i < this.children.length; i ++ ) {
  11022. object.children.push( this.children[ i ].toJSON( meta ).object );
  11023. }
  11024. }
  11025. //
  11026. if ( this.animations.length > 0 ) {
  11027. object.animations = [];
  11028. for ( let i = 0; i < this.animations.length; i ++ ) {
  11029. const animation = this.animations[ i ];
  11030. object.animations.push( serialize( meta.animations, animation ) );
  11031. }
  11032. }
  11033. if ( isRootObject ) {
  11034. const geometries = extractFromCache( meta.geometries );
  11035. const materials = extractFromCache( meta.materials );
  11036. const textures = extractFromCache( meta.textures );
  11037. const images = extractFromCache( meta.images );
  11038. const shapes = extractFromCache( meta.shapes );
  11039. const skeletons = extractFromCache( meta.skeletons );
  11040. const animations = extractFromCache( meta.animations );
  11041. const nodes = extractFromCache( meta.nodes );
  11042. if ( geometries.length > 0 ) output.geometries = geometries;
  11043. if ( materials.length > 0 ) output.materials = materials;
  11044. if ( textures.length > 0 ) output.textures = textures;
  11045. if ( images.length > 0 ) output.images = images;
  11046. if ( shapes.length > 0 ) output.shapes = shapes;
  11047. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  11048. if ( animations.length > 0 ) output.animations = animations;
  11049. if ( nodes.length > 0 ) output.nodes = nodes;
  11050. }
  11051. output.object = object;
  11052. return output;
  11053. // extract data from the cache hash
  11054. // remove metadata on each item
  11055. // and return as array
  11056. function extractFromCache( cache ) {
  11057. const values = [];
  11058. for ( const key in cache ) {
  11059. const data = cache[ key ];
  11060. delete data.metadata;
  11061. values.push( data );
  11062. }
  11063. return values;
  11064. }
  11065. }
  11066. /**
  11067. * Returns a new 3D object with copied values from this instance.
  11068. *
  11069. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  11070. * @return {Object3D} A clone of this instance.
  11071. */
  11072. clone( recursive ) {
  11073. return new this.constructor().copy( this, recursive );
  11074. }
  11075. /**
  11076. * Copies the values of the given 3D object to this instance.
  11077. *
  11078. * @param {Object3D} source - The 3D object to copy.
  11079. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  11080. * @return {Object3D} A reference to this instance.
  11081. */
  11082. copy( source, recursive = true ) {
  11083. this.name = source.name;
  11084. this.up.copy( source.up );
  11085. this.position.copy( source.position );
  11086. this.rotation.order = source.rotation.order;
  11087. this.quaternion.copy( source.quaternion );
  11088. this.scale.copy( source.scale );
  11089. this.matrix.copy( source.matrix );
  11090. this.matrixWorld.copy( source.matrixWorld );
  11091. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11092. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  11093. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  11094. this.layers.mask = source.layers.mask;
  11095. this.visible = source.visible;
  11096. this.castShadow = source.castShadow;
  11097. this.receiveShadow = source.receiveShadow;
  11098. this.frustumCulled = source.frustumCulled;
  11099. this.renderOrder = source.renderOrder;
  11100. this.animations = source.animations.slice();
  11101. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  11102. if ( recursive === true ) {
  11103. for ( let i = 0; i < source.children.length; i ++ ) {
  11104. const child = source.children[ i ];
  11105. this.add( child.clone() );
  11106. }
  11107. }
  11108. return this;
  11109. }
  11110. }
  11111. /**
  11112. * The default up direction for objects, also used as the default
  11113. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  11114. *
  11115. * @static
  11116. * @type {Vector3}
  11117. * @default (0,1,0)
  11118. */
  11119. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  11120. /**
  11121. * The default setting for {@link Object3D#matrixAutoUpdate} for
  11122. * newly created 3D objects.
  11123. *
  11124. * @static
  11125. * @type {boolean}
  11126. * @default true
  11127. */
  11128. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  11129. /**
  11130. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  11131. * newly created 3D objects.
  11132. *
  11133. * @static
  11134. * @type {boolean}
  11135. * @default true
  11136. */
  11137. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  11138. const _v0$2 = /*@__PURE__*/ new Vector3();
  11139. const _v1$3 = /*@__PURE__*/ new Vector3();
  11140. const _v2$2 = /*@__PURE__*/ new Vector3();
  11141. const _v3$2 = /*@__PURE__*/ new Vector3();
  11142. const _vab = /*@__PURE__*/ new Vector3();
  11143. const _vac = /*@__PURE__*/ new Vector3();
  11144. const _vbc = /*@__PURE__*/ new Vector3();
  11145. const _vap = /*@__PURE__*/ new Vector3();
  11146. const _vbp = /*@__PURE__*/ new Vector3();
  11147. const _vcp = /*@__PURE__*/ new Vector3();
  11148. const _v40 = /*@__PURE__*/ new Vector4();
  11149. const _v41 = /*@__PURE__*/ new Vector4();
  11150. const _v42 = /*@__PURE__*/ new Vector4();
  11151. /**
  11152. * A geometric triangle as defined by three vectors representing its three corners.
  11153. */
  11154. class Triangle {
  11155. /**
  11156. * Constructs a new triangle.
  11157. *
  11158. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11159. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11160. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11161. */
  11162. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11163. /**
  11164. * The first corner of the triangle.
  11165. *
  11166. * @type {Vector3}
  11167. */
  11168. this.a = a;
  11169. /**
  11170. * The second corner of the triangle.
  11171. *
  11172. * @type {Vector3}
  11173. */
  11174. this.b = b;
  11175. /**
  11176. * The third corner of the triangle.
  11177. *
  11178. * @type {Vector3}
  11179. */
  11180. this.c = c;
  11181. }
  11182. /**
  11183. * Computes the normal vector of a triangle.
  11184. *
  11185. * @param {Vector3} a - The first corner of the triangle.
  11186. * @param {Vector3} b - The second corner of the triangle.
  11187. * @param {Vector3} c - The third corner of the triangle.
  11188. * @param {Vector3} target - The target vector that is used to store the method's result.
  11189. * @return {Vector3} The triangle's normal.
  11190. */
  11191. static getNormal( a, b, c, target ) {
  11192. target.subVectors( c, b );
  11193. _v0$2.subVectors( a, b );
  11194. target.cross( _v0$2 );
  11195. const targetLengthSq = target.lengthSq();
  11196. if ( targetLengthSq > 0 ) {
  11197. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11198. }
  11199. return target.set( 0, 0, 0 );
  11200. }
  11201. /**
  11202. * Computes a barycentric coordinates from the given vector.
  11203. * Returns `null` if the triangle is degenerate.
  11204. *
  11205. * @param {Vector3} point - A point in 3D space.
  11206. * @param {Vector3} a - The first corner of the triangle.
  11207. * @param {Vector3} b - The second corner of the triangle.
  11208. * @param {Vector3} c - The third corner of the triangle.
  11209. * @param {Vector3} target - The target vector that is used to store the method's result.
  11210. * @return {?Vector3} The barycentric coordinates for the given point
  11211. */
  11212. static getBarycoord( point, a, b, c, target ) {
  11213. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11214. _v0$2.subVectors( c, a );
  11215. _v1$3.subVectors( b, a );
  11216. _v2$2.subVectors( point, a );
  11217. const dot00 = _v0$2.dot( _v0$2 );
  11218. const dot01 = _v0$2.dot( _v1$3 );
  11219. const dot02 = _v0$2.dot( _v2$2 );
  11220. const dot11 = _v1$3.dot( _v1$3 );
  11221. const dot12 = _v1$3.dot( _v2$2 );
  11222. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11223. // collinear or singular triangle
  11224. if ( denom === 0 ) {
  11225. target.set( 0, 0, 0 );
  11226. return null;
  11227. }
  11228. const invDenom = 1 / denom;
  11229. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11230. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11231. // barycentric coordinates must always sum to 1
  11232. return target.set( 1 - u - v, v, u );
  11233. }
  11234. /**
  11235. * Returns `true` if the given point, when projected onto the plane of the
  11236. * triangle, lies within the triangle.
  11237. *
  11238. * @param {Vector3} point - The point in 3D space to test.
  11239. * @param {Vector3} a - The first corner of the triangle.
  11240. * @param {Vector3} b - The second corner of the triangle.
  11241. * @param {Vector3} c - The third corner of the triangle.
  11242. * @return {boolean} Whether the given point, when projected onto the plane of the
  11243. * triangle, lies within the triangle or not.
  11244. */
  11245. static containsPoint( point, a, b, c ) {
  11246. // if the triangle is degenerate then we can't contain a point
  11247. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11248. return false;
  11249. }
  11250. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11251. }
  11252. /**
  11253. * Computes the value barycentrically interpolated for the given point on the
  11254. * triangle. Returns `null` if the triangle is degenerate.
  11255. *
  11256. * @param {Vector3} point - Position of interpolated point.
  11257. * @param {Vector3} p1 - The first corner of the triangle.
  11258. * @param {Vector3} p2 - The second corner of the triangle.
  11259. * @param {Vector3} p3 - The third corner of the triangle.
  11260. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11261. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11262. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11263. * @param {Vector3} target - The target vector that is used to store the method's result.
  11264. * @return {?Vector3} The interpolated value.
  11265. */
  11266. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11267. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11268. target.x = 0;
  11269. target.y = 0;
  11270. if ( 'z' in target ) target.z = 0;
  11271. if ( 'w' in target ) target.w = 0;
  11272. return null;
  11273. }
  11274. target.setScalar( 0 );
  11275. target.addScaledVector( v1, _v3$2.x );
  11276. target.addScaledVector( v2, _v3$2.y );
  11277. target.addScaledVector( v3, _v3$2.z );
  11278. return target;
  11279. }
  11280. /**
  11281. * Computes the value barycentrically interpolated for the given attribute and indices.
  11282. *
  11283. * @param {BufferAttribute} attr - The attribute to interpolate.
  11284. * @param {number} i1 - Index of first vertex.
  11285. * @param {number} i2 - Index of second vertex.
  11286. * @param {number} i3 - Index of third vertex.
  11287. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11288. * @param {Vector3} target - The target vector that is used to store the method's result.
  11289. * @return {Vector3} The interpolated attribute value.
  11290. */
  11291. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11292. _v40.setScalar( 0 );
  11293. _v41.setScalar( 0 );
  11294. _v42.setScalar( 0 );
  11295. _v40.fromBufferAttribute( attr, i1 );
  11296. _v41.fromBufferAttribute( attr, i2 );
  11297. _v42.fromBufferAttribute( attr, i3 );
  11298. target.setScalar( 0 );
  11299. target.addScaledVector( _v40, barycoord.x );
  11300. target.addScaledVector( _v41, barycoord.y );
  11301. target.addScaledVector( _v42, barycoord.z );
  11302. return target;
  11303. }
  11304. /**
  11305. * Returns `true` if the triangle is oriented towards the given direction.
  11306. *
  11307. * @param {Vector3} a - The first corner of the triangle.
  11308. * @param {Vector3} b - The second corner of the triangle.
  11309. * @param {Vector3} c - The third corner of the triangle.
  11310. * @param {Vector3} direction - The (normalized) direction vector.
  11311. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11312. */
  11313. static isFrontFacing( a, b, c, direction ) {
  11314. _v0$2.subVectors( c, b );
  11315. _v1$3.subVectors( a, b );
  11316. // strictly front facing
  11317. return ( _v0$2.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  11318. }
  11319. /**
  11320. * Sets the triangle's vertices by copying the given values.
  11321. *
  11322. * @param {Vector3} a - The first corner of the triangle.
  11323. * @param {Vector3} b - The second corner of the triangle.
  11324. * @param {Vector3} c - The third corner of the triangle.
  11325. * @return {Triangle} A reference to this triangle.
  11326. */
  11327. set( a, b, c ) {
  11328. this.a.copy( a );
  11329. this.b.copy( b );
  11330. this.c.copy( c );
  11331. return this;
  11332. }
  11333. /**
  11334. * Sets the triangle's vertices by copying the given array values.
  11335. *
  11336. * @param {Array<Vector3>} points - An array with 3D points.
  11337. * @param {number} i0 - The array index representing the first corner of the triangle.
  11338. * @param {number} i1 - The array index representing the second corner of the triangle.
  11339. * @param {number} i2 - The array index representing the third corner of the triangle.
  11340. * @return {Triangle} A reference to this triangle.
  11341. */
  11342. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11343. this.a.copy( points[ i0 ] );
  11344. this.b.copy( points[ i1 ] );
  11345. this.c.copy( points[ i2 ] );
  11346. return this;
  11347. }
  11348. /**
  11349. * Sets the triangle's vertices by copying the given attribute values.
  11350. *
  11351. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11352. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11353. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11354. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11355. * @return {Triangle} A reference to this triangle.
  11356. */
  11357. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11358. this.a.fromBufferAttribute( attribute, i0 );
  11359. this.b.fromBufferAttribute( attribute, i1 );
  11360. this.c.fromBufferAttribute( attribute, i2 );
  11361. return this;
  11362. }
  11363. /**
  11364. * Returns a new triangle with copied values from this instance.
  11365. *
  11366. * @return {Triangle} A clone of this instance.
  11367. */
  11368. clone() {
  11369. return new this.constructor().copy( this );
  11370. }
  11371. /**
  11372. * Copies the values of the given triangle to this instance.
  11373. *
  11374. * @param {Triangle} triangle - The triangle to copy.
  11375. * @return {Triangle} A reference to this triangle.
  11376. */
  11377. copy( triangle ) {
  11378. this.a.copy( triangle.a );
  11379. this.b.copy( triangle.b );
  11380. this.c.copy( triangle.c );
  11381. return this;
  11382. }
  11383. /**
  11384. * Computes the area of the triangle.
  11385. *
  11386. * @return {number} The triangle's area.
  11387. */
  11388. getArea() {
  11389. _v0$2.subVectors( this.c, this.b );
  11390. _v1$3.subVectors( this.a, this.b );
  11391. return _v0$2.cross( _v1$3 ).length() * 0.5;
  11392. }
  11393. /**
  11394. * Computes the midpoint of the triangle.
  11395. *
  11396. * @param {Vector3} target - The target vector that is used to store the method's result.
  11397. * @return {Vector3} The triangle's midpoint.
  11398. */
  11399. getMidpoint( target ) {
  11400. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11401. }
  11402. /**
  11403. * Computes the normal of the triangle.
  11404. *
  11405. * @param {Vector3} target - The target vector that is used to store the method's result.
  11406. * @return {Vector3} The triangle's normal.
  11407. */
  11408. getNormal( target ) {
  11409. return Triangle.getNormal( this.a, this.b, this.c, target );
  11410. }
  11411. /**
  11412. * Computes a plane the triangle lies within.
  11413. *
  11414. * @param {Plane} target - The target vector that is used to store the method's result.
  11415. * @return {Plane} The plane the triangle lies within.
  11416. */
  11417. getPlane( target ) {
  11418. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11419. }
  11420. /**
  11421. * Computes a barycentric coordinates from the given vector.
  11422. * Returns `null` if the triangle is degenerate.
  11423. *
  11424. * @param {Vector3} point - A point in 3D space.
  11425. * @param {Vector3} target - The target vector that is used to store the method's result.
  11426. * @return {?Vector3} The barycentric coordinates for the given point
  11427. */
  11428. getBarycoord( point, target ) {
  11429. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11430. }
  11431. /**
  11432. * Computes the value barycentrically interpolated for the given point on the
  11433. * triangle. Returns `null` if the triangle is degenerate.
  11434. *
  11435. * @param {Vector3} point - Position of interpolated point.
  11436. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11437. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11438. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11439. * @param {Vector3} target - The target vector that is used to store the method's result.
  11440. * @return {?Vector3} The interpolated value.
  11441. */
  11442. getInterpolation( point, v1, v2, v3, target ) {
  11443. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11444. }
  11445. /**
  11446. * Returns `true` if the given point, when projected onto the plane of the
  11447. * triangle, lies within the triangle.
  11448. *
  11449. * @param {Vector3} point - The point in 3D space to test.
  11450. * @return {boolean} Whether the given point, when projected onto the plane of the
  11451. * triangle, lies within the triangle or not.
  11452. */
  11453. containsPoint( point ) {
  11454. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11455. }
  11456. /**
  11457. * Returns `true` if the triangle is oriented towards the given direction.
  11458. *
  11459. * @param {Vector3} direction - The (normalized) direction vector.
  11460. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11461. */
  11462. isFrontFacing( direction ) {
  11463. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11464. }
  11465. /**
  11466. * Returns `true` if this triangle intersects with the given box.
  11467. *
  11468. * @param {Box3} box - The box to intersect.
  11469. * @return {boolean} Whether this triangle intersects with the given box or not.
  11470. */
  11471. intersectsBox( box ) {
  11472. return box.intersectsTriangle( this );
  11473. }
  11474. /**
  11475. * Returns the closest point on the triangle to the given point.
  11476. *
  11477. * @param {Vector3} p - The point to compute the closest point for.
  11478. * @param {Vector3} target - The target vector that is used to store the method's result.
  11479. * @return {Vector3} The closest point on the triangle.
  11480. */
  11481. closestPointToPoint( p, target ) {
  11482. const a = this.a, b = this.b, c = this.c;
  11483. let v, w;
  11484. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11485. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11486. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11487. // basically, we're distinguishing which of the voronoi regions of the triangle
  11488. // the point lies in with the minimum amount of redundant computation.
  11489. _vab.subVectors( b, a );
  11490. _vac.subVectors( c, a );
  11491. _vap.subVectors( p, a );
  11492. const d1 = _vab.dot( _vap );
  11493. const d2 = _vac.dot( _vap );
  11494. if ( d1 <= 0 && d2 <= 0 ) {
  11495. // vertex region of A; barycentric coords (1, 0, 0)
  11496. return target.copy( a );
  11497. }
  11498. _vbp.subVectors( p, b );
  11499. const d3 = _vab.dot( _vbp );
  11500. const d4 = _vac.dot( _vbp );
  11501. if ( d3 >= 0 && d4 <= d3 ) {
  11502. // vertex region of B; barycentric coords (0, 1, 0)
  11503. return target.copy( b );
  11504. }
  11505. const vc = d1 * d4 - d3 * d2;
  11506. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11507. v = d1 / ( d1 - d3 );
  11508. // edge region of AB; barycentric coords (1-v, v, 0)
  11509. return target.copy( a ).addScaledVector( _vab, v );
  11510. }
  11511. _vcp.subVectors( p, c );
  11512. const d5 = _vab.dot( _vcp );
  11513. const d6 = _vac.dot( _vcp );
  11514. if ( d6 >= 0 && d5 <= d6 ) {
  11515. // vertex region of C; barycentric coords (0, 0, 1)
  11516. return target.copy( c );
  11517. }
  11518. const vb = d5 * d2 - d1 * d6;
  11519. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11520. w = d2 / ( d2 - d6 );
  11521. // edge region of AC; barycentric coords (1-w, 0, w)
  11522. return target.copy( a ).addScaledVector( _vac, w );
  11523. }
  11524. const va = d3 * d6 - d5 * d4;
  11525. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11526. _vbc.subVectors( c, b );
  11527. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11528. // edge region of BC; barycentric coords (0, 1-w, w)
  11529. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11530. }
  11531. // face region
  11532. const denom = 1 / ( va + vb + vc );
  11533. // u = va * denom
  11534. v = vb * denom;
  11535. w = vc * denom;
  11536. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11537. }
  11538. /**
  11539. * Returns `true` if this triangle is equal with the given one.
  11540. *
  11541. * @param {Triangle} triangle - The triangle to test for equality.
  11542. * @return {boolean} Whether this triangle is equal with the given one.
  11543. */
  11544. equals( triangle ) {
  11545. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11546. }
  11547. }
  11548. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  11549. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  11550. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  11551. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  11552. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  11553. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  11554. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  11555. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  11556. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  11557. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  11558. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  11559. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  11560. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  11561. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  11562. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  11563. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  11564. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  11565. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  11566. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  11567. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  11568. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  11569. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  11570. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  11571. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  11572. const _hslA = { h: 0, s: 0, l: 0 };
  11573. const _hslB = { h: 0, s: 0, l: 0 };
  11574. function hue2rgb( p, q, t ) {
  11575. if ( t < 0 ) t += 1;
  11576. if ( t > 1 ) t -= 1;
  11577. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  11578. if ( t < 1 / 2 ) return q;
  11579. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  11580. return p;
  11581. }
  11582. /**
  11583. * A Color instance is represented by RGB components in the linear <i>working
  11584. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  11585. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  11586. * strings) are converted to the working color space automatically.
  11587. *
  11588. * ```js
  11589. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  11590. * const color = new THREE.Color().setHex( 0x112233 );
  11591. * ```
  11592. * Source color spaces may be specified explicitly, to ensure correct conversions.
  11593. * ```js
  11594. * // assumed already LinearSRGBColorSpace; no conversion
  11595. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  11596. *
  11597. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  11598. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  11599. * ```
  11600. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  11601. * see <i>Color management</i>. Iterating through a Color instance will yield
  11602. * its components (r, g, b) in the corresponding order. A Color can be initialised
  11603. * in any of the following ways:
  11604. * ```js
  11605. * //empty constructor - will default white
  11606. * const color1 = new THREE.Color();
  11607. *
  11608. * //Hexadecimal color (recommended)
  11609. * const color2 = new THREE.Color( 0xff0000 );
  11610. *
  11611. * //RGB string
  11612. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  11613. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  11614. *
  11615. * //X11 color name - all 140 color names are supported.
  11616. * //Note the lack of CamelCase in the name
  11617. * const color5 = new THREE.Color( 'skyblue' );
  11618. * //HSL string
  11619. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  11620. *
  11621. * //Separate RGB values between 0 and 1
  11622. * const color7 = new THREE.Color( 1, 0, 0 );
  11623. * ```
  11624. */
  11625. class Color {
  11626. /**
  11627. * Constructs a new color.
  11628. *
  11629. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  11630. * and that method is used throughout the rest of the documentation.
  11631. *
  11632. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11633. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11634. * @param {number} [g] - The green component.
  11635. * @param {number} [b] - The blue component.
  11636. */
  11637. constructor( r, g, b ) {
  11638. /**
  11639. * This flag can be used for type testing.
  11640. *
  11641. * @type {boolean}
  11642. * @readonly
  11643. * @default true
  11644. */
  11645. this.isColor = true;
  11646. /**
  11647. * The red component.
  11648. *
  11649. * @type {number}
  11650. * @default 1
  11651. */
  11652. this.r = 1;
  11653. /**
  11654. * The green component.
  11655. *
  11656. * @type {number}
  11657. * @default 1
  11658. */
  11659. this.g = 1;
  11660. /**
  11661. * The blue component.
  11662. *
  11663. * @type {number}
  11664. * @default 1
  11665. */
  11666. this.b = 1;
  11667. return this.set( r, g, b );
  11668. }
  11669. /**
  11670. * Sets the colors's components from the given values.
  11671. *
  11672. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11673. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11674. * @param {number} [g] - The green component.
  11675. * @param {number} [b] - The blue component.
  11676. * @return {Color} A reference to this color.
  11677. */
  11678. set( r, g, b ) {
  11679. if ( g === undefined && b === undefined ) {
  11680. // r is THREE.Color, hex or string
  11681. const value = r;
  11682. if ( value && value.isColor ) {
  11683. this.copy( value );
  11684. } else if ( typeof value === 'number' ) {
  11685. this.setHex( value );
  11686. } else if ( typeof value === 'string' ) {
  11687. this.setStyle( value );
  11688. }
  11689. } else {
  11690. this.setRGB( r, g, b );
  11691. }
  11692. return this;
  11693. }
  11694. /**
  11695. * Sets the colors's components to the given scalar value.
  11696. *
  11697. * @param {number} scalar - The scalar value.
  11698. * @return {Color} A reference to this color.
  11699. */
  11700. setScalar( scalar ) {
  11701. this.r = scalar;
  11702. this.g = scalar;
  11703. this.b = scalar;
  11704. return this;
  11705. }
  11706. /**
  11707. * Sets this color from a hexadecimal value.
  11708. *
  11709. * @param {number} hex - The hexadecimal value.
  11710. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11711. * @return {Color} A reference to this color.
  11712. */
  11713. setHex( hex, colorSpace = SRGBColorSpace ) {
  11714. hex = Math.floor( hex );
  11715. this.r = ( hex >> 16 & 255 ) / 255;
  11716. this.g = ( hex >> 8 & 255 ) / 255;
  11717. this.b = ( hex & 255 ) / 255;
  11718. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11719. return this;
  11720. }
  11721. /**
  11722. * Sets this color from RGB values.
  11723. *
  11724. * @param {number} r - Red channel value between `0.0` and `1.0`.
  11725. * @param {number} g - Green channel value between `0.0` and `1.0`.
  11726. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  11727. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11728. * @return {Color} A reference to this color.
  11729. */
  11730. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  11731. this.r = r;
  11732. this.g = g;
  11733. this.b = b;
  11734. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11735. return this;
  11736. }
  11737. /**
  11738. * Sets this color from RGB values.
  11739. *
  11740. * @param {number} h - Hue value between `0.0` and `1.0`.
  11741. * @param {number} s - Saturation value between `0.0` and `1.0`.
  11742. * @param {number} l - Lightness value between `0.0` and `1.0`.
  11743. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11744. * @return {Color} A reference to this color.
  11745. */
  11746. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  11747. // h,s,l ranges are in 0.0 - 1.0
  11748. h = euclideanModulo( h, 1 );
  11749. s = clamp( s, 0, 1 );
  11750. l = clamp( l, 0, 1 );
  11751. if ( s === 0 ) {
  11752. this.r = this.g = this.b = l;
  11753. } else {
  11754. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  11755. const q = ( 2 * l ) - p;
  11756. this.r = hue2rgb( q, p, h + 1 / 3 );
  11757. this.g = hue2rgb( q, p, h );
  11758. this.b = hue2rgb( q, p, h - 1 / 3 );
  11759. }
  11760. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11761. return this;
  11762. }
  11763. /**
  11764. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  11765. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  11766. * any [X11 color name]{@link https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart} -
  11767. * all 140 color names are supported).
  11768. *
  11769. * @param {string} style - Color as a CSS-style string.
  11770. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11771. * @return {Color} A reference to this color.
  11772. */
  11773. setStyle( style, colorSpace = SRGBColorSpace ) {
  11774. function handleAlpha( string ) {
  11775. if ( string === undefined ) return;
  11776. if ( parseFloat( string ) < 1 ) {
  11777. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  11778. }
  11779. }
  11780. let m;
  11781. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  11782. // rgb / hsl
  11783. let color;
  11784. const name = m[ 1 ];
  11785. const components = m[ 2 ];
  11786. switch ( name ) {
  11787. case 'rgb':
  11788. case 'rgba':
  11789. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11790. // rgb(255,0,0) rgba(255,0,0,0.5)
  11791. handleAlpha( color[ 4 ] );
  11792. return this.setRGB(
  11793. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  11794. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  11795. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  11796. colorSpace
  11797. );
  11798. }
  11799. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11800. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  11801. handleAlpha( color[ 4 ] );
  11802. return this.setRGB(
  11803. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  11804. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  11805. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  11806. colorSpace
  11807. );
  11808. }
  11809. break;
  11810. case 'hsl':
  11811. case 'hsla':
  11812. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11813. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  11814. handleAlpha( color[ 4 ] );
  11815. return this.setHSL(
  11816. parseFloat( color[ 1 ] ) / 360,
  11817. parseFloat( color[ 2 ] ) / 100,
  11818. parseFloat( color[ 3 ] ) / 100,
  11819. colorSpace
  11820. );
  11821. }
  11822. break;
  11823. default:
  11824. console.warn( 'THREE.Color: Unknown color model ' + style );
  11825. }
  11826. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  11827. // hex color
  11828. const hex = m[ 1 ];
  11829. const size = hex.length;
  11830. if ( size === 3 ) {
  11831. // #ff0
  11832. return this.setRGB(
  11833. parseInt( hex.charAt( 0 ), 16 ) / 15,
  11834. parseInt( hex.charAt( 1 ), 16 ) / 15,
  11835. parseInt( hex.charAt( 2 ), 16 ) / 15,
  11836. colorSpace
  11837. );
  11838. } else if ( size === 6 ) {
  11839. // #ff0000
  11840. return this.setHex( parseInt( hex, 16 ), colorSpace );
  11841. } else {
  11842. console.warn( 'THREE.Color: Invalid hex color ' + style );
  11843. }
  11844. } else if ( style && style.length > 0 ) {
  11845. return this.setColorName( style, colorSpace );
  11846. }
  11847. return this;
  11848. }
  11849. /**
  11850. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  11851. * you don't need the other CSS-style formats.
  11852. *
  11853. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  11854. * ```js
  11855. * Color.NAMES.aliceblue // returns 0xF0F8FF
  11856. * ```
  11857. *
  11858. * @param {string} style - The color name.
  11859. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11860. * @return {Color} A reference to this color.
  11861. */
  11862. setColorName( style, colorSpace = SRGBColorSpace ) {
  11863. // color keywords
  11864. const hex = _colorKeywords[ style.toLowerCase() ];
  11865. if ( hex !== undefined ) {
  11866. // red
  11867. this.setHex( hex, colorSpace );
  11868. } else {
  11869. // unknown color
  11870. console.warn( 'THREE.Color: Unknown color ' + style );
  11871. }
  11872. return this;
  11873. }
  11874. /**
  11875. * Returns a new color with copied values from this instance.
  11876. *
  11877. * @return {Color} A clone of this instance.
  11878. */
  11879. clone() {
  11880. return new this.constructor( this.r, this.g, this.b );
  11881. }
  11882. /**
  11883. * Copies the values of the given color to this instance.
  11884. *
  11885. * @param {Color} color - The color to copy.
  11886. * @return {Color} A reference to this color.
  11887. */
  11888. copy( color ) {
  11889. this.r = color.r;
  11890. this.g = color.g;
  11891. this.b = color.b;
  11892. return this;
  11893. }
  11894. /**
  11895. * Copies the given color into this color, and then converts this color from
  11896. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11897. *
  11898. * @param {Color} color - The color to copy/convert.
  11899. * @return {Color} A reference to this color.
  11900. */
  11901. copySRGBToLinear( color ) {
  11902. this.r = SRGBToLinear( color.r );
  11903. this.g = SRGBToLinear( color.g );
  11904. this.b = SRGBToLinear( color.b );
  11905. return this;
  11906. }
  11907. /**
  11908. * Copies the given color into this color, and then converts this color from
  11909. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11910. *
  11911. * @param {Color} color - The color to copy/convert.
  11912. * @return {Color} A reference to this color.
  11913. */
  11914. copyLinearToSRGB( color ) {
  11915. this.r = LinearToSRGB( color.r );
  11916. this.g = LinearToSRGB( color.g );
  11917. this.b = LinearToSRGB( color.b );
  11918. return this;
  11919. }
  11920. /**
  11921. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11922. *
  11923. * @return {Color} A reference to this color.
  11924. */
  11925. convertSRGBToLinear() {
  11926. this.copySRGBToLinear( this );
  11927. return this;
  11928. }
  11929. /**
  11930. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11931. *
  11932. * @return {Color} A reference to this color.
  11933. */
  11934. convertLinearToSRGB() {
  11935. this.copyLinearToSRGB( this );
  11936. return this;
  11937. }
  11938. /**
  11939. * Returns the hexadecimal value of this color.
  11940. *
  11941. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11942. * @return {number} The hexadecimal value.
  11943. */
  11944. getHex( colorSpace = SRGBColorSpace ) {
  11945. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  11946. 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 ) );
  11947. }
  11948. /**
  11949. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  11950. *
  11951. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11952. * @return {string} The hexadecimal value as a string.
  11953. */
  11954. getHexString( colorSpace = SRGBColorSpace ) {
  11955. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  11956. }
  11957. /**
  11958. * Converts the colors RGB values into the HSL format and stores them into the
  11959. * given target object.
  11960. *
  11961. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  11962. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11963. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  11964. */
  11965. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  11966. // h,s,l ranges are in 0.0 - 1.0
  11967. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  11968. const r = _color.r, g = _color.g, b = _color.b;
  11969. const max = Math.max( r, g, b );
  11970. const min = Math.min( r, g, b );
  11971. let hue, saturation;
  11972. const lightness = ( min + max ) / 2.0;
  11973. if ( min === max ) {
  11974. hue = 0;
  11975. saturation = 0;
  11976. } else {
  11977. const delta = max - min;
  11978. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  11979. switch ( max ) {
  11980. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  11981. case g: hue = ( b - r ) / delta + 2; break;
  11982. case b: hue = ( r - g ) / delta + 4; break;
  11983. }
  11984. hue /= 6;
  11985. }
  11986. target.h = hue;
  11987. target.s = saturation;
  11988. target.l = lightness;
  11989. return target;
  11990. }
  11991. /**
  11992. * Returns the RGB values of this color and stores them into the given target object.
  11993. *
  11994. * @param {Color} target - The target color that is used to store the method's result.
  11995. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11996. * @return {Color} The RGB representation of this color.
  11997. */
  11998. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  11999. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12000. target.r = _color.r;
  12001. target.g = _color.g;
  12002. target.b = _color.b;
  12003. return target;
  12004. }
  12005. /**
  12006. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  12007. *
  12008. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12009. * @return {string} The CSS representation of this color.
  12010. */
  12011. getStyle( colorSpace = SRGBColorSpace ) {
  12012. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12013. const r = _color.r, g = _color.g, b = _color.b;
  12014. if ( colorSpace !== SRGBColorSpace ) {
  12015. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  12016. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  12017. }
  12018. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  12019. }
  12020. /**
  12021. * Adds the given HSL values to this color's values.
  12022. * Internally, this converts the color's RGB values to HSL, adds HSL
  12023. * and then converts the color back to RGB.
  12024. *
  12025. * @param {number} h - Hue value between `0.0` and `1.0`.
  12026. * @param {number} s - Saturation value between `0.0` and `1.0`.
  12027. * @param {number} l - Lightness value between `0.0` and `1.0`.
  12028. * @return {Color} A reference to this color.
  12029. */
  12030. offsetHSL( h, s, l ) {
  12031. this.getHSL( _hslA );
  12032. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  12033. }
  12034. /**
  12035. * Adds the RGB values of the given color to the RGB values of this color.
  12036. *
  12037. * @param {Color} color - The color to add.
  12038. * @return {Color} A reference to this color.
  12039. */
  12040. add( color ) {
  12041. this.r += color.r;
  12042. this.g += color.g;
  12043. this.b += color.b;
  12044. return this;
  12045. }
  12046. /**
  12047. * Adds the RGB values of the given colors and stores the result in this instance.
  12048. *
  12049. * @param {Color} color1 - The first color.
  12050. * @param {Color} color2 - The second color.
  12051. * @return {Color} A reference to this color.
  12052. */
  12053. addColors( color1, color2 ) {
  12054. this.r = color1.r + color2.r;
  12055. this.g = color1.g + color2.g;
  12056. this.b = color1.b + color2.b;
  12057. return this;
  12058. }
  12059. /**
  12060. * Adds the given scalar value to the RGB values of this color.
  12061. *
  12062. * @param {number} s - The scalar to add.
  12063. * @return {Color} A reference to this color.
  12064. */
  12065. addScalar( s ) {
  12066. this.r += s;
  12067. this.g += s;
  12068. this.b += s;
  12069. return this;
  12070. }
  12071. /**
  12072. * Subtracts the RGB values of the given color from the RGB values of this color.
  12073. *
  12074. * @param {Color} color - The color to subtract.
  12075. * @return {Color} A reference to this color.
  12076. */
  12077. sub( color ) {
  12078. this.r = Math.max( 0, this.r - color.r );
  12079. this.g = Math.max( 0, this.g - color.g );
  12080. this.b = Math.max( 0, this.b - color.b );
  12081. return this;
  12082. }
  12083. /**
  12084. * Multiplies the RGB values of the given color with the RGB values of this color.
  12085. *
  12086. * @param {Color} color - The color to multiply.
  12087. * @return {Color} A reference to this color.
  12088. */
  12089. multiply( color ) {
  12090. this.r *= color.r;
  12091. this.g *= color.g;
  12092. this.b *= color.b;
  12093. return this;
  12094. }
  12095. /**
  12096. * Multiplies the given scalar value with the RGB values of this color.
  12097. *
  12098. * @param {number} s - The scalar to multiply.
  12099. * @return {Color} A reference to this color.
  12100. */
  12101. multiplyScalar( s ) {
  12102. this.r *= s;
  12103. this.g *= s;
  12104. this.b *= s;
  12105. return this;
  12106. }
  12107. /**
  12108. * Linearly interpolates this color's RGB values toward the RGB values of the
  12109. * given color. The alpha argument can be thought of as the ratio between
  12110. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  12111. *
  12112. * @param {Color} color - The color to converge on.
  12113. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12114. * @return {Color} A reference to this color.
  12115. */
  12116. lerp( color, alpha ) {
  12117. this.r += ( color.r - this.r ) * alpha;
  12118. this.g += ( color.g - this.g ) * alpha;
  12119. this.b += ( color.b - this.b ) * alpha;
  12120. return this;
  12121. }
  12122. /**
  12123. * Linearly interpolates between the given colors and stores the result in this instance.
  12124. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  12125. * is the first and `1.0` is the second color.
  12126. *
  12127. * @param {Color} color1 - The first color.
  12128. * @param {Color} color2 - The second color.
  12129. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12130. * @return {Color} A reference to this color.
  12131. */
  12132. lerpColors( color1, color2, alpha ) {
  12133. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  12134. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  12135. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  12136. return this;
  12137. }
  12138. /**
  12139. * Linearly interpolates this color's HSL values toward the HSL values of the
  12140. * given color. It differs from {@link Color#lerp} by not interpolating straight
  12141. * from one color to the other, but instead going through all the hues in between
  12142. * those two colors. The alpha argument can be thought of as the ratio between
  12143. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  12144. *
  12145. * @param {Color} color - The color to converge on.
  12146. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12147. * @return {Color} A reference to this color.
  12148. */
  12149. lerpHSL( color, alpha ) {
  12150. this.getHSL( _hslA );
  12151. color.getHSL( _hslB );
  12152. const h = lerp( _hslA.h, _hslB.h, alpha );
  12153. const s = lerp( _hslA.s, _hslB.s, alpha );
  12154. const l = lerp( _hslA.l, _hslB.l, alpha );
  12155. this.setHSL( h, s, l );
  12156. return this;
  12157. }
  12158. /**
  12159. * Sets the color's RGB components from the given 3D vector.
  12160. *
  12161. * @param {Vector3} v - The vector to set.
  12162. * @return {Color} A reference to this color.
  12163. */
  12164. setFromVector3( v ) {
  12165. this.r = v.x;
  12166. this.g = v.y;
  12167. this.b = v.z;
  12168. return this;
  12169. }
  12170. /**
  12171. * Transforms this color with the given 3x3 matrix.
  12172. *
  12173. * @param {Matrix3} m - The matrix.
  12174. * @return {Color} A reference to this color.
  12175. */
  12176. applyMatrix3( m ) {
  12177. const r = this.r, g = this.g, b = this.b;
  12178. const e = m.elements;
  12179. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  12180. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  12181. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  12182. return this;
  12183. }
  12184. /**
  12185. * Returns `true` if this color is equal with the given one.
  12186. *
  12187. * @param {Color} c - The color to test for equality.
  12188. * @return {boolean} Whether this bounding color is equal with the given one.
  12189. */
  12190. equals( c ) {
  12191. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  12192. }
  12193. /**
  12194. * Sets this color's RGB components from the given array.
  12195. *
  12196. * @param {Array<number>} array - An array holding the RGB values.
  12197. * @param {number} [offset=0] - The offset into the array.
  12198. * @return {Color} A reference to this color.
  12199. */
  12200. fromArray( array, offset = 0 ) {
  12201. this.r = array[ offset ];
  12202. this.g = array[ offset + 1 ];
  12203. this.b = array[ offset + 2 ];
  12204. return this;
  12205. }
  12206. /**
  12207. * Writes the RGB components of this color to the given array. If no array is provided,
  12208. * the method returns a new instance.
  12209. *
  12210. * @param {Array<number>} [array=[]] - The target array holding the color components.
  12211. * @param {number} [offset=0] - Index of the first element in the array.
  12212. * @return {Array<number>} The color components.
  12213. */
  12214. toArray( array = [], offset = 0 ) {
  12215. array[ offset ] = this.r;
  12216. array[ offset + 1 ] = this.g;
  12217. array[ offset + 2 ] = this.b;
  12218. return array;
  12219. }
  12220. /**
  12221. * Sets the components of this color from the given buffer attribute.
  12222. *
  12223. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  12224. * @param {number} index - The index into the attribute.
  12225. * @return {Color} A reference to this color.
  12226. */
  12227. fromBufferAttribute( attribute, index ) {
  12228. this.r = attribute.getX( index );
  12229. this.g = attribute.getY( index );
  12230. this.b = attribute.getZ( index );
  12231. return this;
  12232. }
  12233. /**
  12234. * This methods defines the serialization result of this class. Returns the color
  12235. * as a hexadecimal value.
  12236. *
  12237. * @return {number} The hexadecimal value.
  12238. */
  12239. toJSON() {
  12240. return this.getHex();
  12241. }
  12242. *[ Symbol.iterator ]() {
  12243. yield this.r;
  12244. yield this.g;
  12245. yield this.b;
  12246. }
  12247. }
  12248. const _color = /*@__PURE__*/ new Color();
  12249. /**
  12250. * A dictionary with X11 color names.
  12251. *
  12252. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  12253. *
  12254. * @static
  12255. * @type {Object}
  12256. */
  12257. Color.NAMES = _colorKeywords;
  12258. let _materialId = 0;
  12259. /**
  12260. * Abstract base class for materials.
  12261. *
  12262. * Materials define the appearance of renderable 3D objects.
  12263. *
  12264. * @abstract
  12265. * @augments EventDispatcher
  12266. */
  12267. class Material extends EventDispatcher {
  12268. /**
  12269. * Constructs a new material.
  12270. */
  12271. constructor() {
  12272. super();
  12273. /**
  12274. * This flag can be used for type testing.
  12275. *
  12276. * @type {boolean}
  12277. * @readonly
  12278. * @default true
  12279. */
  12280. this.isMaterial = true;
  12281. /**
  12282. * The ID of the material.
  12283. *
  12284. * @name Material#id
  12285. * @type {number}
  12286. * @readonly
  12287. */
  12288. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  12289. /**
  12290. * The UUID of the material.
  12291. *
  12292. * @type {string}
  12293. * @readonly
  12294. */
  12295. this.uuid = generateUUID();
  12296. /**
  12297. * The name of the material.
  12298. *
  12299. * @type {string}
  12300. */
  12301. this.name = '';
  12302. /**
  12303. * The type property is used for detecting the object type
  12304. * in context of serialization/deserialization.
  12305. *
  12306. * @type {string}
  12307. * @readonly
  12308. */
  12309. this.type = 'Material';
  12310. /**
  12311. * Defines the blending type of the material.
  12312. *
  12313. * It must be set to `CustomBlending` if custom blending properties like
  12314. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  12315. * should have any effect.
  12316. *
  12317. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  12318. * @default NormalBlending
  12319. */
  12320. this.blending = NormalBlending;
  12321. /**
  12322. * Defines which side of faces will be rendered - front, back or both.
  12323. *
  12324. * @type {(FrontSide|BackSide|DoubleSide)}
  12325. * @default FrontSide
  12326. */
  12327. this.side = FrontSide;
  12328. /**
  12329. * If set to `true`, vertex colors should be used.
  12330. *
  12331. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  12332. * four (RGBA) component color buffer attribute is used.
  12333. *
  12334. * @type {boolean}
  12335. * @default false
  12336. */
  12337. this.vertexColors = false;
  12338. /**
  12339. * Defines how transparent the material is.
  12340. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  12341. *
  12342. * If the {@link Material#transparent} is not set to `true`,
  12343. * the material will remain fully opaque and this value will only affect its color.
  12344. *
  12345. * @type {number}
  12346. * @default 1
  12347. */
  12348. this.opacity = 1;
  12349. /**
  12350. * Defines whether this material is transparent. This has an effect on
  12351. * rendering as transparent objects need special treatment and are rendered
  12352. * after non-transparent objects.
  12353. *
  12354. * When set to true, the extent to which the material is transparent is
  12355. * controlled by {@link Material#opacity}.
  12356. *
  12357. * @type {boolean}
  12358. * @default false
  12359. */
  12360. this.transparent = false;
  12361. /**
  12362. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  12363. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  12364. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  12365. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  12366. *
  12367. * @type {boolean}
  12368. * @default false
  12369. */
  12370. this.alphaHash = false;
  12371. /**
  12372. * Defines the blending source factor.
  12373. *
  12374. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12375. * @default SrcAlphaFactor
  12376. */
  12377. this.blendSrc = SrcAlphaFactor;
  12378. /**
  12379. * Defines the blending destination factor.
  12380. *
  12381. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12382. * @default OneMinusSrcAlphaFactor
  12383. */
  12384. this.blendDst = OneMinusSrcAlphaFactor;
  12385. /**
  12386. * Defines the blending equation.
  12387. *
  12388. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12389. * @default AddEquation
  12390. */
  12391. this.blendEquation = AddEquation;
  12392. /**
  12393. * Defines the blending source alpha factor.
  12394. *
  12395. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12396. * @default null
  12397. */
  12398. this.blendSrcAlpha = null;
  12399. /**
  12400. * Defines the blending destination alpha factor.
  12401. *
  12402. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12403. * @default null
  12404. */
  12405. this.blendDstAlpha = null;
  12406. /**
  12407. * Defines the blending equation of the alpha channel.
  12408. *
  12409. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12410. * @default null
  12411. */
  12412. this.blendEquationAlpha = null;
  12413. /**
  12414. * Represents the RGB values of the constant blend color.
  12415. *
  12416. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  12417. *
  12418. * @type {Color}
  12419. * @default (0,0,0)
  12420. */
  12421. this.blendColor = new Color( 0, 0, 0 );
  12422. /**
  12423. * Represents the alpha value of the constant blend color.
  12424. *
  12425. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  12426. *
  12427. * @type {number}
  12428. * @default 0
  12429. */
  12430. this.blendAlpha = 0;
  12431. /**
  12432. * Defines the depth function.
  12433. *
  12434. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  12435. * @default LessEqualDepth
  12436. */
  12437. this.depthFunc = LessEqualDepth;
  12438. /**
  12439. * Whether to have depth test enabled when rendering this material.
  12440. * When the depth test is disabled, the depth write will also be implicitly disabled.
  12441. *
  12442. * @type {boolean}
  12443. * @default true
  12444. */
  12445. this.depthTest = true;
  12446. /**
  12447. * Whether rendering this material has any effect on the depth buffer.
  12448. *
  12449. * When drawing 2D overlays it can be useful to disable the depth writing in
  12450. * order to layer several things together without creating z-index artifacts.
  12451. *
  12452. * @type {boolean}
  12453. * @default true
  12454. */
  12455. this.depthWrite = true;
  12456. /**
  12457. * The bit mask to use when writing to the stencil buffer.
  12458. *
  12459. * @type {number}
  12460. * @default 0xff
  12461. */
  12462. this.stencilWriteMask = 0xff;
  12463. /**
  12464. * The stencil comparison function to use.
  12465. *
  12466. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  12467. * @default AlwaysStencilFunc
  12468. */
  12469. this.stencilFunc = AlwaysStencilFunc;
  12470. /**
  12471. * The value to use when performing stencil comparisons or stencil operations.
  12472. *
  12473. * @type {number}
  12474. * @default 0
  12475. */
  12476. this.stencilRef = 0;
  12477. /**
  12478. * The bit mask to use when comparing against the stencil buffer.
  12479. *
  12480. * @type {number}
  12481. * @default 0xff
  12482. */
  12483. this.stencilFuncMask = 0xff;
  12484. /**
  12485. * Which stencil operation to perform when the comparison function returns `false`.
  12486. *
  12487. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12488. * @default KeepStencilOp
  12489. */
  12490. this.stencilFail = KeepStencilOp;
  12491. /**
  12492. * Which stencil operation to perform when the comparison function returns
  12493. * `true` but the depth test fails.
  12494. *
  12495. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12496. * @default KeepStencilOp
  12497. */
  12498. this.stencilZFail = KeepStencilOp;
  12499. /**
  12500. * Which stencil operation to perform when the comparison function returns
  12501. * `true` and the depth test passes.
  12502. *
  12503. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12504. * @default KeepStencilOp
  12505. */
  12506. this.stencilZPass = KeepStencilOp;
  12507. /**
  12508. * Whether stencil operations are performed against the stencil buffer. In
  12509. * order to perform writes or comparisons against the stencil buffer this
  12510. * value must be `true`.
  12511. *
  12512. * @type {boolean}
  12513. * @default false
  12514. */
  12515. this.stencilWrite = false;
  12516. /**
  12517. * User-defined clipping planes specified as THREE.Plane objects in world
  12518. * space. These planes apply to the objects this material is attached to.
  12519. * Points in space whose signed distance to the plane is negative are clipped
  12520. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  12521. * be `true`.
  12522. *
  12523. * @type {?Array<Plane>}
  12524. * @default null
  12525. */
  12526. this.clippingPlanes = null;
  12527. /**
  12528. * Changes the behavior of clipping planes so that only their intersection is
  12529. * clipped, rather than their union.
  12530. *
  12531. * @type {boolean}
  12532. * @default false
  12533. */
  12534. this.clipIntersection = false;
  12535. /**
  12536. * Defines whether to clip shadows according to the clipping planes specified
  12537. * on this material.
  12538. *
  12539. * @type {boolean}
  12540. * @default false
  12541. */
  12542. this.clipShadows = false;
  12543. /**
  12544. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  12545. * is determined as follows:
  12546. *
  12547. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  12548. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  12549. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  12550. *
  12551. * @type {?(FrontSide|BackSide|DoubleSide)}
  12552. * @default null
  12553. */
  12554. this.shadowSide = null;
  12555. /**
  12556. * Whether to render the material's color.
  12557. *
  12558. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  12559. * objects that occlude other objects.
  12560. *
  12561. * @type {boolean}
  12562. * @default true
  12563. */
  12564. this.colorWrite = true;
  12565. /**
  12566. * Override the renderer's default precision for this material.
  12567. *
  12568. * @type {?('highp'|'mediump'|'lowp')}
  12569. * @default null
  12570. */
  12571. this.precision = null;
  12572. /**
  12573. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  12574. * be offset after it is interpolated from the depth values of the appropriate vertices.
  12575. * The offset is added before the depth test is performed and before the value is written
  12576. * into the depth buffer.
  12577. *
  12578. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  12579. * rendering solids with highlighted edges.
  12580. *
  12581. * @type {boolean}
  12582. * @default false
  12583. */
  12584. this.polygonOffset = false;
  12585. /**
  12586. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  12587. *
  12588. * @type {number}
  12589. * @default 0
  12590. */
  12591. this.polygonOffsetFactor = 0;
  12592. /**
  12593. * Is multiplied by an implementation-specific value to create a constant depth offset.
  12594. *
  12595. * @type {number}
  12596. * @default 0
  12597. */
  12598. this.polygonOffsetUnits = 0;
  12599. /**
  12600. * Whether to apply dithering to the color to remove the appearance of banding.
  12601. *
  12602. * @type {boolean}
  12603. * @default false
  12604. */
  12605. this.dithering = false;
  12606. /**
  12607. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  12608. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  12609. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  12610. *
  12611. * @type {boolean}
  12612. * @default false
  12613. */
  12614. this.alphaToCoverage = false;
  12615. /**
  12616. * Whether to premultiply the alpha (transparency) value.
  12617. *
  12618. * @type {boolean}
  12619. * @default false
  12620. */
  12621. this.premultipliedAlpha = false;
  12622. /**
  12623. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  12624. *
  12625. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  12626. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  12627. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  12628. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  12629. * disable the two pass rendering to avoid performance issues.
  12630. *
  12631. * @type {boolean}
  12632. * @default false
  12633. */
  12634. this.forceSinglePass = false;
  12635. /**
  12636. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  12637. *
  12638. * @type {boolean}
  12639. * @default true
  12640. */
  12641. this.allowOverride = true;
  12642. /**
  12643. * Defines whether 3D objects using this material are visible.
  12644. *
  12645. * @type {boolean}
  12646. * @default true
  12647. */
  12648. this.visible = true;
  12649. /**
  12650. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  12651. *
  12652. * It is ignored when rendering to a render target or using post processing or when using
  12653. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  12654. *
  12655. * @type {boolean}
  12656. * @default true
  12657. */
  12658. this.toneMapped = true;
  12659. /**
  12660. * An object that can be used to store custom data about the Material. It
  12661. * should not hold references to functions as these will not be cloned.
  12662. *
  12663. * @type {Object}
  12664. */
  12665. this.userData = {};
  12666. /**
  12667. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  12668. *
  12669. * @type {number}
  12670. * @readonly
  12671. * @default 0
  12672. */
  12673. this.version = 0;
  12674. this._alphaTest = 0;
  12675. }
  12676. /**
  12677. * Sets the alpha value to be used when running an alpha test. The material
  12678. * will not be rendered if the opacity is lower than this value.
  12679. *
  12680. * @type {number}
  12681. * @readonly
  12682. * @default 0
  12683. */
  12684. get alphaTest() {
  12685. return this._alphaTest;
  12686. }
  12687. set alphaTest( value ) {
  12688. if ( this._alphaTest > 0 !== value > 0 ) {
  12689. this.version ++;
  12690. }
  12691. this._alphaTest = value;
  12692. }
  12693. /**
  12694. * An optional callback that is executed immediately before the material is used to render a 3D object.
  12695. *
  12696. * This method can only be used when rendering with {@link WebGLRenderer}.
  12697. *
  12698. * @param {WebGLRenderer} renderer - The renderer.
  12699. * @param {Scene} scene - The scene.
  12700. * @param {Camera} camera - The camera that is used to render the scene.
  12701. * @param {BufferGeometry} geometry - The 3D object's geometry.
  12702. * @param {Object3D} object - The 3D object.
  12703. * @param {Object} group - The geometry group data.
  12704. */
  12705. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  12706. /**
  12707. * An optional callback that is executed immediately before the shader
  12708. * program is compiled. This function is called with the shader source code
  12709. * as a parameter. Useful for the modification of built-in materials.
  12710. *
  12711. * This method can only be used when rendering with {@link WebGLRenderer}. The
  12712. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  12713. * Node Material system and [TSL]{@link https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language}.
  12714. *
  12715. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  12716. * @param {WebGLRenderer} renderer - A reference to the renderer.
  12717. */
  12718. onBeforeCompile( /* shaderobject, renderer */ ) {}
  12719. /**
  12720. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  12721. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  12722. * shader or recompile the shader for this material as needed.
  12723. *
  12724. * This method can only be used when rendering with {@link WebGLRenderer}.
  12725. *
  12726. * @return {string} The custom program cache key.
  12727. */
  12728. customProgramCacheKey() {
  12729. return this.onBeforeCompile.toString();
  12730. }
  12731. /**
  12732. * This method can be used to set default values from parameter objects.
  12733. * It is a generic implementation so it can be used with different types
  12734. * of materials.
  12735. *
  12736. * @param {Object} [values] - The material values to set.
  12737. */
  12738. setValues( values ) {
  12739. if ( values === undefined ) return;
  12740. for ( const key in values ) {
  12741. const newValue = values[ key ];
  12742. if ( newValue === undefined ) {
  12743. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  12744. continue;
  12745. }
  12746. const currentValue = this[ key ];
  12747. if ( currentValue === undefined ) {
  12748. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  12749. continue;
  12750. }
  12751. if ( currentValue && currentValue.isColor ) {
  12752. currentValue.set( newValue );
  12753. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  12754. currentValue.copy( newValue );
  12755. } else {
  12756. this[ key ] = newValue;
  12757. }
  12758. }
  12759. }
  12760. /**
  12761. * Serializes the material into JSON.
  12762. *
  12763. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  12764. * @return {Object} A JSON object representing the serialized material.
  12765. * @see {@link ObjectLoader#parse}
  12766. */
  12767. toJSON( meta ) {
  12768. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  12769. if ( isRootObject ) {
  12770. meta = {
  12771. textures: {},
  12772. images: {}
  12773. };
  12774. }
  12775. const data = {
  12776. metadata: {
  12777. version: 4.7,
  12778. type: 'Material',
  12779. generator: 'Material.toJSON'
  12780. }
  12781. };
  12782. // standard Material serialization
  12783. data.uuid = this.uuid;
  12784. data.type = this.type;
  12785. if ( this.name !== '' ) data.name = this.name;
  12786. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  12787. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  12788. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  12789. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  12790. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  12791. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  12792. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  12793. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  12794. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  12795. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  12796. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  12797. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  12798. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  12799. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  12800. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  12801. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  12802. }
  12803. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  12804. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  12805. }
  12806. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  12807. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  12808. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  12809. }
  12810. if ( this.sheenColorMap && this.sheenColorMap.isTexture ) {
  12811. data.sheenColorMap = this.sheenColorMap.toJSON( meta ).uuid;
  12812. }
  12813. if ( this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture ) {
  12814. data.sheenRoughnessMap = this.sheenRoughnessMap.toJSON( meta ).uuid;
  12815. }
  12816. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  12817. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  12818. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  12819. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  12820. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  12821. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  12822. }
  12823. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  12824. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  12825. }
  12826. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  12827. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  12828. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  12829. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  12830. }
  12831. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  12832. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  12833. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  12834. if ( this.lightMap && this.lightMap.isTexture ) {
  12835. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  12836. data.lightMapIntensity = this.lightMapIntensity;
  12837. }
  12838. if ( this.aoMap && this.aoMap.isTexture ) {
  12839. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  12840. data.aoMapIntensity = this.aoMapIntensity;
  12841. }
  12842. if ( this.bumpMap && this.bumpMap.isTexture ) {
  12843. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  12844. data.bumpScale = this.bumpScale;
  12845. }
  12846. if ( this.normalMap && this.normalMap.isTexture ) {
  12847. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  12848. data.normalMapType = this.normalMapType;
  12849. data.normalScale = this.normalScale.toArray();
  12850. }
  12851. if ( this.displacementMap && this.displacementMap.isTexture ) {
  12852. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  12853. data.displacementScale = this.displacementScale;
  12854. data.displacementBias = this.displacementBias;
  12855. }
  12856. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  12857. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  12858. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  12859. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  12860. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  12861. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  12862. if ( this.envMap && this.envMap.isTexture ) {
  12863. data.envMap = this.envMap.toJSON( meta ).uuid;
  12864. if ( this.combine !== undefined ) data.combine = this.combine;
  12865. }
  12866. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  12867. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  12868. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  12869. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  12870. if ( this.gradientMap && this.gradientMap.isTexture ) {
  12871. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  12872. }
  12873. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  12874. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  12875. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  12876. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  12877. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  12878. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  12879. if ( this.size !== undefined ) data.size = this.size;
  12880. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  12881. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  12882. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  12883. if ( this.side !== FrontSide ) data.side = this.side;
  12884. if ( this.vertexColors === true ) data.vertexColors = true;
  12885. if ( this.opacity < 1 ) data.opacity = this.opacity;
  12886. if ( this.transparent === true ) data.transparent = true;
  12887. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  12888. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  12889. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  12890. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  12891. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  12892. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  12893. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  12894. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  12895. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  12896. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  12897. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  12898. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  12899. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  12900. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  12901. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  12902. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  12903. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  12904. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  12905. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  12906. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  12907. // rotation (SpriteMaterial)
  12908. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  12909. if ( this.polygonOffset === true ) data.polygonOffset = true;
  12910. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  12911. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  12912. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  12913. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  12914. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  12915. if ( this.scale !== undefined ) data.scale = this.scale;
  12916. if ( this.dithering === true ) data.dithering = true;
  12917. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  12918. if ( this.alphaHash === true ) data.alphaHash = true;
  12919. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  12920. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  12921. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  12922. if ( this.wireframe === true ) data.wireframe = true;
  12923. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  12924. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  12925. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  12926. if ( this.flatShading === true ) data.flatShading = true;
  12927. if ( this.visible === false ) data.visible = false;
  12928. if ( this.toneMapped === false ) data.toneMapped = false;
  12929. if ( this.fog === false ) data.fog = false;
  12930. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  12931. // TODO: Copied from Object3D.toJSON
  12932. function extractFromCache( cache ) {
  12933. const values = [];
  12934. for ( const key in cache ) {
  12935. const data = cache[ key ];
  12936. delete data.metadata;
  12937. values.push( data );
  12938. }
  12939. return values;
  12940. }
  12941. if ( isRootObject ) {
  12942. const textures = extractFromCache( meta.textures );
  12943. const images = extractFromCache( meta.images );
  12944. if ( textures.length > 0 ) data.textures = textures;
  12945. if ( images.length > 0 ) data.images = images;
  12946. }
  12947. return data;
  12948. }
  12949. /**
  12950. * Returns a new material with copied values from this instance.
  12951. *
  12952. * @return {Material} A clone of this instance.
  12953. */
  12954. clone() {
  12955. return new this.constructor().copy( this );
  12956. }
  12957. /**
  12958. * Copies the values of the given material to this instance.
  12959. *
  12960. * @param {Material} source - The material to copy.
  12961. * @return {Material} A reference to this instance.
  12962. */
  12963. copy( source ) {
  12964. this.name = source.name;
  12965. this.blending = source.blending;
  12966. this.side = source.side;
  12967. this.vertexColors = source.vertexColors;
  12968. this.opacity = source.opacity;
  12969. this.transparent = source.transparent;
  12970. this.blendSrc = source.blendSrc;
  12971. this.blendDst = source.blendDst;
  12972. this.blendEquation = source.blendEquation;
  12973. this.blendSrcAlpha = source.blendSrcAlpha;
  12974. this.blendDstAlpha = source.blendDstAlpha;
  12975. this.blendEquationAlpha = source.blendEquationAlpha;
  12976. this.blendColor.copy( source.blendColor );
  12977. this.blendAlpha = source.blendAlpha;
  12978. this.depthFunc = source.depthFunc;
  12979. this.depthTest = source.depthTest;
  12980. this.depthWrite = source.depthWrite;
  12981. this.stencilWriteMask = source.stencilWriteMask;
  12982. this.stencilFunc = source.stencilFunc;
  12983. this.stencilRef = source.stencilRef;
  12984. this.stencilFuncMask = source.stencilFuncMask;
  12985. this.stencilFail = source.stencilFail;
  12986. this.stencilZFail = source.stencilZFail;
  12987. this.stencilZPass = source.stencilZPass;
  12988. this.stencilWrite = source.stencilWrite;
  12989. const srcPlanes = source.clippingPlanes;
  12990. let dstPlanes = null;
  12991. if ( srcPlanes !== null ) {
  12992. const n = srcPlanes.length;
  12993. dstPlanes = new Array( n );
  12994. for ( let i = 0; i !== n; ++ i ) {
  12995. dstPlanes[ i ] = srcPlanes[ i ].clone();
  12996. }
  12997. }
  12998. this.clippingPlanes = dstPlanes;
  12999. this.clipIntersection = source.clipIntersection;
  13000. this.clipShadows = source.clipShadows;
  13001. this.shadowSide = source.shadowSide;
  13002. this.colorWrite = source.colorWrite;
  13003. this.precision = source.precision;
  13004. this.polygonOffset = source.polygonOffset;
  13005. this.polygonOffsetFactor = source.polygonOffsetFactor;
  13006. this.polygonOffsetUnits = source.polygonOffsetUnits;
  13007. this.dithering = source.dithering;
  13008. this.alphaTest = source.alphaTest;
  13009. this.alphaHash = source.alphaHash;
  13010. this.alphaToCoverage = source.alphaToCoverage;
  13011. this.premultipliedAlpha = source.premultipliedAlpha;
  13012. this.forceSinglePass = source.forceSinglePass;
  13013. this.visible = source.visible;
  13014. this.toneMapped = source.toneMapped;
  13015. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  13016. return this;
  13017. }
  13018. /**
  13019. * Frees the GPU-related resources allocated by this instance. Call this
  13020. * method whenever this instance is no longer used in your app.
  13021. *
  13022. * @fires Material#dispose
  13023. */
  13024. dispose() {
  13025. /**
  13026. * Fires when the material has been disposed of.
  13027. *
  13028. * @event Material#dispose
  13029. * @type {Object}
  13030. */
  13031. this.dispatchEvent( { type: 'dispose' } );
  13032. }
  13033. /**
  13034. * Setting this property to `true` indicates the engine the material
  13035. * needs to be recompiled.
  13036. *
  13037. * @type {boolean}
  13038. * @default false
  13039. * @param {boolean} value
  13040. */
  13041. set needsUpdate( value ) {
  13042. if ( value === true ) this.version ++;
  13043. }
  13044. }
  13045. /**
  13046. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  13047. *
  13048. * This material is not affected by lights.
  13049. *
  13050. * @augments Material
  13051. */
  13052. class MeshBasicMaterial extends Material {
  13053. /**
  13054. * Constructs a new mesh basic material.
  13055. *
  13056. * @param {Object} [parameters] - An object with one or more properties
  13057. * defining the material's appearance. Any property of the material
  13058. * (including any property from inherited materials) can be passed
  13059. * in here. Color values can be passed any type of value accepted
  13060. * by {@link Color#set}.
  13061. */
  13062. constructor( parameters ) {
  13063. super();
  13064. /**
  13065. * This flag can be used for type testing.
  13066. *
  13067. * @type {boolean}
  13068. * @readonly
  13069. * @default true
  13070. */
  13071. this.isMeshBasicMaterial = true;
  13072. this.type = 'MeshBasicMaterial';
  13073. /**
  13074. * Color of the material.
  13075. *
  13076. * @type {Color}
  13077. * @default (1,1,1)
  13078. */
  13079. this.color = new Color( 0xffffff ); // diffuse
  13080. /**
  13081. * The color map. May optionally include an alpha channel, typically combined
  13082. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  13083. * color is modulated by the diffuse `color`.
  13084. *
  13085. * @type {?Texture}
  13086. * @default null
  13087. */
  13088. this.map = null;
  13089. /**
  13090. * The light map. Requires a second set of UVs.
  13091. *
  13092. * @type {?Texture}
  13093. * @default null
  13094. */
  13095. this.lightMap = null;
  13096. /**
  13097. * Intensity of the baked light.
  13098. *
  13099. * @type {number}
  13100. * @default 1
  13101. */
  13102. this.lightMapIntensity = 1.0;
  13103. /**
  13104. * The red channel of this texture is used as the ambient occlusion map.
  13105. * Requires a second set of UVs.
  13106. *
  13107. * @type {?Texture}
  13108. * @default null
  13109. */
  13110. this.aoMap = null;
  13111. /**
  13112. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  13113. * disables ambient occlusion. Where intensity is `1` and the AO map's
  13114. * red channel is also `1`, ambient light is fully occluded on a surface.
  13115. *
  13116. * @type {number}
  13117. * @default 1
  13118. */
  13119. this.aoMapIntensity = 1.0;
  13120. /**
  13121. * Specular map used by the material.
  13122. *
  13123. * @type {?Texture}
  13124. * @default null
  13125. */
  13126. this.specularMap = null;
  13127. /**
  13128. * The alpha map is a grayscale texture that controls the opacity across the
  13129. * surface (black: fully transparent; white: fully opaque).
  13130. *
  13131. * Only the color of the texture is used, ignoring the alpha channel if one
  13132. * exists. For RGB and RGBA textures, the renderer will use the green channel
  13133. * when sampling this texture due to the extra bit of precision provided for
  13134. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  13135. * luminance/alpha textures will also still work as expected.
  13136. *
  13137. * @type {?Texture}
  13138. * @default null
  13139. */
  13140. this.alphaMap = null;
  13141. /**
  13142. * The environment map.
  13143. *
  13144. * @type {?Texture}
  13145. * @default null
  13146. */
  13147. this.envMap = null;
  13148. /**
  13149. * The rotation of the environment map in radians.
  13150. *
  13151. * @type {Euler}
  13152. * @default (0,0,0)
  13153. */
  13154. this.envMapRotation = new Euler();
  13155. /**
  13156. * How to combine the result of the surface's color with the environment map, if any.
  13157. *
  13158. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  13159. * blend between the two colors.
  13160. *
  13161. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  13162. * @default MultiplyOperation
  13163. */
  13164. this.combine = MultiplyOperation;
  13165. /**
  13166. * How much the environment map affects the surface.
  13167. * The valid range is between `0` (no reflections) and `1` (full reflections).
  13168. *
  13169. * @type {number}
  13170. * @default 1
  13171. */
  13172. this.reflectivity = 1;
  13173. /**
  13174. * The index of refraction (IOR) of air (approximately 1) divided by the
  13175. * index of refraction of the material. It is used with environment mapping
  13176. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  13177. * The refraction ratio should not exceed `1`.
  13178. *
  13179. * @type {number}
  13180. * @default 0.98
  13181. */
  13182. this.refractionRatio = 0.98;
  13183. /**
  13184. * Renders the geometry as a wireframe.
  13185. *
  13186. * @type {boolean}
  13187. * @default false
  13188. */
  13189. this.wireframe = false;
  13190. /**
  13191. * Controls the thickness of the wireframe.
  13192. *
  13193. * Can only be used with {@link SVGRenderer}.
  13194. *
  13195. * @type {number}
  13196. * @default 1
  13197. */
  13198. this.wireframeLinewidth = 1;
  13199. /**
  13200. * Defines appearance of wireframe ends.
  13201. *
  13202. * Can only be used with {@link SVGRenderer}.
  13203. *
  13204. * @type {('round'|'bevel'|'miter')}
  13205. * @default 'round'
  13206. */
  13207. this.wireframeLinecap = 'round';
  13208. /**
  13209. * Defines appearance of wireframe joints.
  13210. *
  13211. * Can only be used with {@link SVGRenderer}.
  13212. *
  13213. * @type {('round'|'bevel'|'miter')}
  13214. * @default 'round'
  13215. */
  13216. this.wireframeLinejoin = 'round';
  13217. /**
  13218. * Whether the material is affected by fog or not.
  13219. *
  13220. * @type {boolean}
  13221. * @default true
  13222. */
  13223. this.fog = true;
  13224. this.setValues( parameters );
  13225. }
  13226. copy( source ) {
  13227. super.copy( source );
  13228. this.color.copy( source.color );
  13229. this.map = source.map;
  13230. this.lightMap = source.lightMap;
  13231. this.lightMapIntensity = source.lightMapIntensity;
  13232. this.aoMap = source.aoMap;
  13233. this.aoMapIntensity = source.aoMapIntensity;
  13234. this.specularMap = source.specularMap;
  13235. this.alphaMap = source.alphaMap;
  13236. this.envMap = source.envMap;
  13237. this.envMapRotation.copy( source.envMapRotation );
  13238. this.combine = source.combine;
  13239. this.reflectivity = source.reflectivity;
  13240. this.refractionRatio = source.refractionRatio;
  13241. this.wireframe = source.wireframe;
  13242. this.wireframeLinewidth = source.wireframeLinewidth;
  13243. this.wireframeLinecap = source.wireframeLinecap;
  13244. this.wireframeLinejoin = source.wireframeLinejoin;
  13245. this.fog = source.fog;
  13246. return this;
  13247. }
  13248. }
  13249. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  13250. const _tables = /*@__PURE__*/ _generateTables();
  13251. function _generateTables() {
  13252. // float32 to float16 helpers
  13253. const buffer = new ArrayBuffer( 4 );
  13254. const floatView = new Float32Array( buffer );
  13255. const uint32View = new Uint32Array( buffer );
  13256. const baseTable = new Uint32Array( 512 );
  13257. const shiftTable = new Uint32Array( 512 );
  13258. for ( let i = 0; i < 256; ++ i ) {
  13259. const e = i - 127;
  13260. // very small number (0, -0)
  13261. if ( e < -27 ) {
  13262. baseTable[ i ] = 0x0000;
  13263. baseTable[ i | 0x100 ] = 0x8000;
  13264. shiftTable[ i ] = 24;
  13265. shiftTable[ i | 0x100 ] = 24;
  13266. // small number (denorm)
  13267. } else if ( e < -14 ) {
  13268. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  13269. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  13270. shiftTable[ i ] = - e - 1;
  13271. shiftTable[ i | 0x100 ] = - e - 1;
  13272. // normal number
  13273. } else if ( e <= 15 ) {
  13274. baseTable[ i ] = ( e + 15 ) << 10;
  13275. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  13276. shiftTable[ i ] = 13;
  13277. shiftTable[ i | 0x100 ] = 13;
  13278. // large number (Infinity, -Infinity)
  13279. } else if ( e < 128 ) {
  13280. baseTable[ i ] = 0x7c00;
  13281. baseTable[ i | 0x100 ] = 0xfc00;
  13282. shiftTable[ i ] = 24;
  13283. shiftTable[ i | 0x100 ] = 24;
  13284. // stay (NaN, Infinity, -Infinity)
  13285. } else {
  13286. baseTable[ i ] = 0x7c00;
  13287. baseTable[ i | 0x100 ] = 0xfc00;
  13288. shiftTable[ i ] = 13;
  13289. shiftTable[ i | 0x100 ] = 13;
  13290. }
  13291. }
  13292. // float16 to float32 helpers
  13293. const mantissaTable = new Uint32Array( 2048 );
  13294. const exponentTable = new Uint32Array( 64 );
  13295. const offsetTable = new Uint32Array( 64 );
  13296. for ( let i = 1; i < 1024; ++ i ) {
  13297. let m = i << 13; // zero pad mantissa bits
  13298. let e = 0; // zero exponent
  13299. // normalized
  13300. while ( ( m & 0x00800000 ) === 0 ) {
  13301. m <<= 1;
  13302. e -= 0x00800000; // decrement exponent
  13303. }
  13304. m &= -8388609; // clear leading 1 bit
  13305. e += 0x38800000; // adjust bias
  13306. mantissaTable[ i ] = m | e;
  13307. }
  13308. for ( let i = 1024; i < 2048; ++ i ) {
  13309. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  13310. }
  13311. for ( let i = 1; i < 31; ++ i ) {
  13312. exponentTable[ i ] = i << 23;
  13313. }
  13314. exponentTable[ 31 ] = 0x47800000;
  13315. exponentTable[ 32 ] = 0x80000000;
  13316. for ( let i = 33; i < 63; ++ i ) {
  13317. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  13318. }
  13319. exponentTable[ 63 ] = 0xc7800000;
  13320. for ( let i = 1; i < 64; ++ i ) {
  13321. if ( i !== 32 ) {
  13322. offsetTable[ i ] = 1024;
  13323. }
  13324. }
  13325. return {
  13326. floatView: floatView,
  13327. uint32View: uint32View,
  13328. baseTable: baseTable,
  13329. shiftTable: shiftTable,
  13330. mantissaTable: mantissaTable,
  13331. exponentTable: exponentTable,
  13332. offsetTable: offsetTable
  13333. };
  13334. }
  13335. /**
  13336. * Returns a half precision floating point value (FP16) from the given single
  13337. * precision floating point value (FP32).
  13338. *
  13339. * @param {number} val - A single precision floating point value.
  13340. * @return {number} The FP16 value.
  13341. */
  13342. function toHalfFloat( val ) {
  13343. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  13344. val = clamp( val, -65504, 65504 );
  13345. _tables.floatView[ 0 ] = val;
  13346. const f = _tables.uint32View[ 0 ];
  13347. const e = ( f >> 23 ) & 0x1ff;
  13348. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  13349. }
  13350. /**
  13351. * Returns a single precision floating point value (FP32) from the given half
  13352. * precision floating point value (FP16).
  13353. *
  13354. * @param {number} val - A half precision floating point value.
  13355. * @return {number} The FP32 value.
  13356. */
  13357. function fromHalfFloat( val ) {
  13358. const m = val >> 10;
  13359. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  13360. return _tables.floatView[ 0 ];
  13361. }
  13362. /**
  13363. * A class containing utility functions for data.
  13364. *
  13365. * @hideconstructor
  13366. */
  13367. class DataUtils {
  13368. /**
  13369. * Returns a half precision floating point value (FP16) from the given single
  13370. * precision floating point value (FP32).
  13371. *
  13372. * @param {number} val - A single precision floating point value.
  13373. * @return {number} The FP16 value.
  13374. */
  13375. static toHalfFloat( val ) {
  13376. return toHalfFloat( val );
  13377. }
  13378. /**
  13379. * Returns a single precision floating point value (FP32) from the given half
  13380. * precision floating point value (FP16).
  13381. *
  13382. * @param {number} val - A half precision floating point value.
  13383. * @return {number} The FP32 value.
  13384. */
  13385. static fromHalfFloat( val ) {
  13386. return fromHalfFloat( val );
  13387. }
  13388. }
  13389. const _vector$9 = /*@__PURE__*/ new Vector3();
  13390. const _vector2$1 = /*@__PURE__*/ new Vector2();
  13391. let _id$3 = 0;
  13392. /**
  13393. * This class stores data for an attribute (such as vertex positions, face
  13394. * indices, normals, colors, UVs, and any custom attributes ) associated with
  13395. * a geometry, which allows for more efficient passing of data to the GPU.
  13396. *
  13397. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  13398. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  13399. */
  13400. class BufferAttribute {
  13401. /**
  13402. * Constructs a new buffer attribute.
  13403. *
  13404. * @param {TypedArray} array - The array holding the attribute data.
  13405. * @param {number} itemSize - The item size.
  13406. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13407. */
  13408. constructor( array, itemSize, normalized = false ) {
  13409. if ( Array.isArray( array ) ) {
  13410. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  13411. }
  13412. /**
  13413. * This flag can be used for type testing.
  13414. *
  13415. * @type {boolean}
  13416. * @readonly
  13417. * @default true
  13418. */
  13419. this.isBufferAttribute = true;
  13420. /**
  13421. * The ID of the buffer attribute.
  13422. *
  13423. * @name BufferAttribute#id
  13424. * @type {number}
  13425. * @readonly
  13426. */
  13427. Object.defineProperty( this, 'id', { value: _id$3 ++ } );
  13428. /**
  13429. * The name of the buffer attribute.
  13430. *
  13431. * @type {string}
  13432. */
  13433. this.name = '';
  13434. /**
  13435. * The array holding the attribute data. It should have `itemSize * numVertices`
  13436. * elements, where `numVertices` is the number of vertices in the associated geometry.
  13437. *
  13438. * @type {TypedArray}
  13439. */
  13440. this.array = array;
  13441. /**
  13442. * The number of values of the array that should be associated with a particular vertex.
  13443. * For instance, if this attribute is storing a 3-component vector (such as a position,
  13444. * normal, or color), then the value should be `3`.
  13445. *
  13446. * @type {number}
  13447. */
  13448. this.itemSize = itemSize;
  13449. /**
  13450. * Represents the number of items this buffer attribute stores. It is internally computed
  13451. * by dividing the `array` length by the `itemSize`.
  13452. *
  13453. * @type {number}
  13454. * @readonly
  13455. */
  13456. this.count = array !== undefined ? array.length / itemSize : 0;
  13457. /**
  13458. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  13459. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  13460. * and `normalized` is `true`, the values `0 - +65535` in the array data will be mapped to
  13461. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  13462. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  13463. *
  13464. * @type {boolean}
  13465. */
  13466. this.normalized = normalized;
  13467. /**
  13468. * Defines the intended usage pattern of the data store for optimization purposes.
  13469. *
  13470. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  13471. * instantiate a new one and set the desired usage before the next render.
  13472. *
  13473. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  13474. * @default StaticDrawUsage
  13475. */
  13476. this.usage = StaticDrawUsage;
  13477. /**
  13478. * This can be used to only update some components of stored vectors (for example, just the
  13479. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  13480. *
  13481. * @type {Array<Object>}
  13482. */
  13483. this.updateRanges = [];
  13484. /**
  13485. * Configures the bound GPU type for use in shaders.
  13486. *
  13487. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  13488. * For lower precision float types, use `Float16BufferAttribute`.
  13489. *
  13490. * @type {(FloatType|IntType)}
  13491. * @default FloatType
  13492. */
  13493. this.gpuType = FloatType;
  13494. /**
  13495. * A version number, incremented every time the `needsUpdate` is set to `true`.
  13496. *
  13497. * @type {number}
  13498. */
  13499. this.version = 0;
  13500. }
  13501. /**
  13502. * A callback function that is executed after the renderer has transferred the attribute
  13503. * array data to the GPU.
  13504. */
  13505. onUploadCallback() {}
  13506. /**
  13507. * Flag to indicate that this attribute has changed and should be re-sent to
  13508. * the GPU. Set this to `true` when you modify the value of the array.
  13509. *
  13510. * @type {number}
  13511. * @default false
  13512. * @param {boolean} value
  13513. */
  13514. set needsUpdate( value ) {
  13515. if ( value === true ) this.version ++;
  13516. }
  13517. /**
  13518. * Sets the usage of this buffer attribute.
  13519. *
  13520. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  13521. * @return {BufferAttribute} A reference to this buffer attribute.
  13522. */
  13523. setUsage( value ) {
  13524. this.usage = value;
  13525. return this;
  13526. }
  13527. /**
  13528. * Adds a range of data in the data array to be updated on the GPU.
  13529. *
  13530. * @param {number} start - Position at which to start update.
  13531. * @param {number} count - The number of components to update.
  13532. */
  13533. addUpdateRange( start, count ) {
  13534. this.updateRanges.push( { start, count } );
  13535. }
  13536. /**
  13537. * Clears the update ranges.
  13538. */
  13539. clearUpdateRanges() {
  13540. this.updateRanges.length = 0;
  13541. }
  13542. /**
  13543. * Copies the values of the given buffer attribute to this instance.
  13544. *
  13545. * @param {BufferAttribute} source - The buffer attribute to copy.
  13546. * @return {BufferAttribute} A reference to this instance.
  13547. */
  13548. copy( source ) {
  13549. this.name = source.name;
  13550. this.array = new source.array.constructor( source.array );
  13551. this.itemSize = source.itemSize;
  13552. this.count = source.count;
  13553. this.normalized = source.normalized;
  13554. this.usage = source.usage;
  13555. this.gpuType = source.gpuType;
  13556. return this;
  13557. }
  13558. /**
  13559. * Copies a vector from the given buffer attribute to this one. The start
  13560. * and destination position in the attribute buffers are represented by the
  13561. * given indices.
  13562. *
  13563. * @param {number} index1 - The destination index into this buffer attribute.
  13564. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  13565. * @param {number} index2 - The source index into the given buffer attribute.
  13566. * @return {BufferAttribute} A reference to this instance.
  13567. */
  13568. copyAt( index1, attribute, index2 ) {
  13569. index1 *= this.itemSize;
  13570. index2 *= attribute.itemSize;
  13571. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  13572. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13573. }
  13574. return this;
  13575. }
  13576. /**
  13577. * Copies the given array data into this buffer attribute.
  13578. *
  13579. * @param {(TypedArray|Array)} array - The array to copy.
  13580. * @return {BufferAttribute} A reference to this instance.
  13581. */
  13582. copyArray( array ) {
  13583. this.array.set( array );
  13584. return this;
  13585. }
  13586. /**
  13587. * Applies the given 3x3 matrix to the given attribute. Works with
  13588. * item size `2` and `3`.
  13589. *
  13590. * @param {Matrix3} m - The matrix to apply.
  13591. * @return {BufferAttribute} A reference to this instance.
  13592. */
  13593. applyMatrix3( m ) {
  13594. if ( this.itemSize === 2 ) {
  13595. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13596. _vector2$1.fromBufferAttribute( this, i );
  13597. _vector2$1.applyMatrix3( m );
  13598. this.setXY( i, _vector2$1.x, _vector2$1.y );
  13599. }
  13600. } else if ( this.itemSize === 3 ) {
  13601. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13602. _vector$9.fromBufferAttribute( this, i );
  13603. _vector$9.applyMatrix3( m );
  13604. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13605. }
  13606. }
  13607. return this;
  13608. }
  13609. /**
  13610. * Applies the given 4x4 matrix to the given attribute. Only works with
  13611. * item size `3`.
  13612. *
  13613. * @param {Matrix4} m - The matrix to apply.
  13614. * @return {BufferAttribute} A reference to this instance.
  13615. */
  13616. applyMatrix4( m ) {
  13617. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13618. _vector$9.fromBufferAttribute( this, i );
  13619. _vector$9.applyMatrix4( m );
  13620. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13621. }
  13622. return this;
  13623. }
  13624. /**
  13625. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  13626. * item size `3`.
  13627. *
  13628. * @param {Matrix3} m - The normal matrix to apply.
  13629. * @return {BufferAttribute} A reference to this instance.
  13630. */
  13631. applyNormalMatrix( m ) {
  13632. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13633. _vector$9.fromBufferAttribute( this, i );
  13634. _vector$9.applyNormalMatrix( m );
  13635. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13636. }
  13637. return this;
  13638. }
  13639. /**
  13640. * Applies the given 4x4 matrix to the given attribute. Only works with
  13641. * item size `3` and with direction vectors.
  13642. *
  13643. * @param {Matrix4} m - The matrix to apply.
  13644. * @return {BufferAttribute} A reference to this instance.
  13645. */
  13646. transformDirection( m ) {
  13647. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13648. _vector$9.fromBufferAttribute( this, i );
  13649. _vector$9.transformDirection( m );
  13650. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13651. }
  13652. return this;
  13653. }
  13654. /**
  13655. * Sets the given array data in the buffer attribute.
  13656. *
  13657. * @param {(TypedArray|Array)} value - The array data to set.
  13658. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  13659. * @return {BufferAttribute} A reference to this instance.
  13660. */
  13661. set( value, offset = 0 ) {
  13662. // Matching BufferAttribute constructor, do not normalize the array.
  13663. this.array.set( value, offset );
  13664. return this;
  13665. }
  13666. /**
  13667. * Returns the given component of the vector at the given index.
  13668. *
  13669. * @param {number} index - The index into the buffer attribute.
  13670. * @param {number} component - The component index.
  13671. * @return {number} The returned value.
  13672. */
  13673. getComponent( index, component ) {
  13674. let value = this.array[ index * this.itemSize + component ];
  13675. if ( this.normalized ) value = denormalize( value, this.array );
  13676. return value;
  13677. }
  13678. /**
  13679. * Sets the given value to the given component of the vector at the given index.
  13680. *
  13681. * @param {number} index - The index into the buffer attribute.
  13682. * @param {number} component - The component index.
  13683. * @param {number} value - The value to set.
  13684. * @return {BufferAttribute} A reference to this instance.
  13685. */
  13686. setComponent( index, component, value ) {
  13687. if ( this.normalized ) value = normalize( value, this.array );
  13688. this.array[ index * this.itemSize + component ] = value;
  13689. return this;
  13690. }
  13691. /**
  13692. * Returns the x component of the vector at the given index.
  13693. *
  13694. * @param {number} index - The index into the buffer attribute.
  13695. * @return {number} The x component.
  13696. */
  13697. getX( index ) {
  13698. let x = this.array[ index * this.itemSize ];
  13699. if ( this.normalized ) x = denormalize( x, this.array );
  13700. return x;
  13701. }
  13702. /**
  13703. * Sets the x component of the vector at the given index.
  13704. *
  13705. * @param {number} index - The index into the buffer attribute.
  13706. * @param {number} x - The value to set.
  13707. * @return {BufferAttribute} A reference to this instance.
  13708. */
  13709. setX( index, x ) {
  13710. if ( this.normalized ) x = normalize( x, this.array );
  13711. this.array[ index * this.itemSize ] = x;
  13712. return this;
  13713. }
  13714. /**
  13715. * Returns the y component of the vector at the given index.
  13716. *
  13717. * @param {number} index - The index into the buffer attribute.
  13718. * @return {number} The y component.
  13719. */
  13720. getY( index ) {
  13721. let y = this.array[ index * this.itemSize + 1 ];
  13722. if ( this.normalized ) y = denormalize( y, this.array );
  13723. return y;
  13724. }
  13725. /**
  13726. * Sets the y component of the vector at the given index.
  13727. *
  13728. * @param {number} index - The index into the buffer attribute.
  13729. * @param {number} y - The value to set.
  13730. * @return {BufferAttribute} A reference to this instance.
  13731. */
  13732. setY( index, y ) {
  13733. if ( this.normalized ) y = normalize( y, this.array );
  13734. this.array[ index * this.itemSize + 1 ] = y;
  13735. return this;
  13736. }
  13737. /**
  13738. * Returns the z component of the vector at the given index.
  13739. *
  13740. * @param {number} index - The index into the buffer attribute.
  13741. * @return {number} The z component.
  13742. */
  13743. getZ( index ) {
  13744. let z = this.array[ index * this.itemSize + 2 ];
  13745. if ( this.normalized ) z = denormalize( z, this.array );
  13746. return z;
  13747. }
  13748. /**
  13749. * Sets the z component of the vector at the given index.
  13750. *
  13751. * @param {number} index - The index into the buffer attribute.
  13752. * @param {number} z - The value to set.
  13753. * @return {BufferAttribute} A reference to this instance.
  13754. */
  13755. setZ( index, z ) {
  13756. if ( this.normalized ) z = normalize( z, this.array );
  13757. this.array[ index * this.itemSize + 2 ] = z;
  13758. return this;
  13759. }
  13760. /**
  13761. * Returns the w component of the vector at the given index.
  13762. *
  13763. * @param {number} index - The index into the buffer attribute.
  13764. * @return {number} The w component.
  13765. */
  13766. getW( index ) {
  13767. let w = this.array[ index * this.itemSize + 3 ];
  13768. if ( this.normalized ) w = denormalize( w, this.array );
  13769. return w;
  13770. }
  13771. /**
  13772. * Sets the w component of the vector at the given index.
  13773. *
  13774. * @param {number} index - The index into the buffer attribute.
  13775. * @param {number} w - The value to set.
  13776. * @return {BufferAttribute} A reference to this instance.
  13777. */
  13778. setW( index, w ) {
  13779. if ( this.normalized ) w = normalize( w, this.array );
  13780. this.array[ index * this.itemSize + 3 ] = w;
  13781. return this;
  13782. }
  13783. /**
  13784. * Sets the x and y component of the vector at the given index.
  13785. *
  13786. * @param {number} index - The index into the buffer attribute.
  13787. * @param {number} x - The value for the x component to set.
  13788. * @param {number} y - The value for the y component to set.
  13789. * @return {BufferAttribute} A reference to this instance.
  13790. */
  13791. setXY( index, x, y ) {
  13792. index *= this.itemSize;
  13793. if ( this.normalized ) {
  13794. x = normalize( x, this.array );
  13795. y = normalize( y, this.array );
  13796. }
  13797. this.array[ index + 0 ] = x;
  13798. this.array[ index + 1 ] = y;
  13799. return this;
  13800. }
  13801. /**
  13802. * Sets the x, y and z component of the vector at the given index.
  13803. *
  13804. * @param {number} index - The index into the buffer attribute.
  13805. * @param {number} x - The value for the x component to set.
  13806. * @param {number} y - The value for the y component to set.
  13807. * @param {number} z - The value for the z component to set.
  13808. * @return {BufferAttribute} A reference to this instance.
  13809. */
  13810. setXYZ( index, x, y, z ) {
  13811. index *= this.itemSize;
  13812. if ( this.normalized ) {
  13813. x = normalize( x, this.array );
  13814. y = normalize( y, this.array );
  13815. z = normalize( z, this.array );
  13816. }
  13817. this.array[ index + 0 ] = x;
  13818. this.array[ index + 1 ] = y;
  13819. this.array[ index + 2 ] = z;
  13820. return this;
  13821. }
  13822. /**
  13823. * Sets the x, y, z and w component of the vector at the given index.
  13824. *
  13825. * @param {number} index - The index into the buffer attribute.
  13826. * @param {number} x - The value for the x component to set.
  13827. * @param {number} y - The value for the y component to set.
  13828. * @param {number} z - The value for the z component to set.
  13829. * @param {number} w - The value for the w component to set.
  13830. * @return {BufferAttribute} A reference to this instance.
  13831. */
  13832. setXYZW( index, x, y, z, w ) {
  13833. index *= this.itemSize;
  13834. if ( this.normalized ) {
  13835. x = normalize( x, this.array );
  13836. y = normalize( y, this.array );
  13837. z = normalize( z, this.array );
  13838. w = normalize( w, this.array );
  13839. }
  13840. this.array[ index + 0 ] = x;
  13841. this.array[ index + 1 ] = y;
  13842. this.array[ index + 2 ] = z;
  13843. this.array[ index + 3 ] = w;
  13844. return this;
  13845. }
  13846. /**
  13847. * Sets the given callback function that is executed after the Renderer has transferred
  13848. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  13849. * the upload when attribute data are not needed anymore on the CPU side.
  13850. *
  13851. * @param {Function} callback - The `onUpload()` callback.
  13852. * @return {BufferAttribute} A reference to this instance.
  13853. */
  13854. onUpload( callback ) {
  13855. this.onUploadCallback = callback;
  13856. return this;
  13857. }
  13858. /**
  13859. * Returns a new buffer attribute with copied values from this instance.
  13860. *
  13861. * @return {BufferAttribute} A clone of this instance.
  13862. */
  13863. clone() {
  13864. return new this.constructor( this.array, this.itemSize ).copy( this );
  13865. }
  13866. /**
  13867. * Serializes the buffer attribute into JSON.
  13868. *
  13869. * @return {Object} A JSON object representing the serialized buffer attribute.
  13870. */
  13871. toJSON() {
  13872. const data = {
  13873. itemSize: this.itemSize,
  13874. type: this.array.constructor.name,
  13875. array: Array.from( this.array ),
  13876. normalized: this.normalized
  13877. };
  13878. if ( this.name !== '' ) data.name = this.name;
  13879. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  13880. return data;
  13881. }
  13882. }
  13883. /**
  13884. * Convenient class that can be used when creating a `Int8` buffer attribute with
  13885. * a plain `Array` instance.
  13886. *
  13887. * @augments BufferAttribute
  13888. */
  13889. class Int8BufferAttribute extends BufferAttribute {
  13890. /**
  13891. * Constructs a new buffer attribute.
  13892. *
  13893. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  13894. * @param {number} itemSize - The item size.
  13895. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13896. */
  13897. constructor( array, itemSize, normalized ) {
  13898. super( new Int8Array( array ), itemSize, normalized );
  13899. }
  13900. }
  13901. /**
  13902. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  13903. * a plain `Array` instance.
  13904. *
  13905. * @augments BufferAttribute
  13906. */
  13907. class Uint8BufferAttribute extends BufferAttribute {
  13908. /**
  13909. * Constructs a new buffer attribute.
  13910. *
  13911. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  13912. * @param {number} itemSize - The item size.
  13913. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13914. */
  13915. constructor( array, itemSize, normalized ) {
  13916. super( new Uint8Array( array ), itemSize, normalized );
  13917. }
  13918. }
  13919. /**
  13920. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  13921. * a plain `Array` instance.
  13922. *
  13923. * @augments BufferAttribute
  13924. */
  13925. class Uint8ClampedBufferAttribute extends BufferAttribute {
  13926. /**
  13927. * Constructs a new buffer attribute.
  13928. *
  13929. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  13930. * @param {number} itemSize - The item size.
  13931. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13932. */
  13933. constructor( array, itemSize, normalized ) {
  13934. super( new Uint8ClampedArray( array ), itemSize, normalized );
  13935. }
  13936. }
  13937. /**
  13938. * Convenient class that can be used when creating a `Int16` buffer attribute with
  13939. * a plain `Array` instance.
  13940. *
  13941. * @augments BufferAttribute
  13942. */
  13943. class Int16BufferAttribute extends BufferAttribute {
  13944. /**
  13945. * Constructs a new buffer attribute.
  13946. *
  13947. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  13948. * @param {number} itemSize - The item size.
  13949. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13950. */
  13951. constructor( array, itemSize, normalized ) {
  13952. super( new Int16Array( array ), itemSize, normalized );
  13953. }
  13954. }
  13955. /**
  13956. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  13957. * a plain `Array` instance.
  13958. *
  13959. * @augments BufferAttribute
  13960. */
  13961. class Uint16BufferAttribute extends BufferAttribute {
  13962. /**
  13963. * Constructs a new buffer attribute.
  13964. *
  13965. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13966. * @param {number} itemSize - The item size.
  13967. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13968. */
  13969. constructor( array, itemSize, normalized ) {
  13970. super( new Uint16Array( array ), itemSize, normalized );
  13971. }
  13972. }
  13973. /**
  13974. * Convenient class that can be used when creating a `Int32` buffer attribute with
  13975. * a plain `Array` instance.
  13976. *
  13977. * @augments BufferAttribute
  13978. */
  13979. class Int32BufferAttribute extends BufferAttribute {
  13980. /**
  13981. * Constructs a new buffer attribute.
  13982. *
  13983. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  13984. * @param {number} itemSize - The item size.
  13985. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13986. */
  13987. constructor( array, itemSize, normalized ) {
  13988. super( new Int32Array( array ), itemSize, normalized );
  13989. }
  13990. }
  13991. /**
  13992. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  13993. * a plain `Array` instance.
  13994. *
  13995. * @augments BufferAttribute
  13996. */
  13997. class Uint32BufferAttribute extends BufferAttribute {
  13998. /**
  13999. * Constructs a new buffer attribute.
  14000. *
  14001. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  14002. * @param {number} itemSize - The item size.
  14003. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14004. */
  14005. constructor( array, itemSize, normalized ) {
  14006. super( new Uint32Array( array ), itemSize, normalized );
  14007. }
  14008. }
  14009. /**
  14010. * Convenient class that can be used when creating a `Float16` buffer attribute with
  14011. * a plain `Array` instance.
  14012. *
  14013. * This class automatically converts to and from FP16 via `Uint16Array` since `Float16Array`
  14014. * browser support is still problematic.
  14015. *
  14016. * @augments BufferAttribute
  14017. */
  14018. class Float16BufferAttribute extends BufferAttribute {
  14019. /**
  14020. * Constructs a new buffer attribute.
  14021. *
  14022. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14023. * @param {number} itemSize - The item size.
  14024. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14025. */
  14026. constructor( array, itemSize, normalized ) {
  14027. super( new Uint16Array( array ), itemSize, normalized );
  14028. this.isFloat16BufferAttribute = true;
  14029. }
  14030. getX( index ) {
  14031. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  14032. if ( this.normalized ) x = denormalize( x, this.array );
  14033. return x;
  14034. }
  14035. setX( index, x ) {
  14036. if ( this.normalized ) x = normalize( x, this.array );
  14037. this.array[ index * this.itemSize ] = toHalfFloat( x );
  14038. return this;
  14039. }
  14040. getY( index ) {
  14041. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  14042. if ( this.normalized ) y = denormalize( y, this.array );
  14043. return y;
  14044. }
  14045. setY( index, y ) {
  14046. if ( this.normalized ) y = normalize( y, this.array );
  14047. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  14048. return this;
  14049. }
  14050. getZ( index ) {
  14051. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  14052. if ( this.normalized ) z = denormalize( z, this.array );
  14053. return z;
  14054. }
  14055. setZ( index, z ) {
  14056. if ( this.normalized ) z = normalize( z, this.array );
  14057. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  14058. return this;
  14059. }
  14060. getW( index ) {
  14061. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  14062. if ( this.normalized ) w = denormalize( w, this.array );
  14063. return w;
  14064. }
  14065. setW( index, w ) {
  14066. if ( this.normalized ) w = normalize( w, this.array );
  14067. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  14068. return this;
  14069. }
  14070. setXY( index, x, y ) {
  14071. index *= this.itemSize;
  14072. if ( this.normalized ) {
  14073. x = normalize( x, this.array );
  14074. y = normalize( y, this.array );
  14075. }
  14076. this.array[ index + 0 ] = toHalfFloat( x );
  14077. this.array[ index + 1 ] = toHalfFloat( y );
  14078. return this;
  14079. }
  14080. setXYZ( index, x, y, z ) {
  14081. index *= this.itemSize;
  14082. if ( this.normalized ) {
  14083. x = normalize( x, this.array );
  14084. y = normalize( y, this.array );
  14085. z = normalize( z, this.array );
  14086. }
  14087. this.array[ index + 0 ] = toHalfFloat( x );
  14088. this.array[ index + 1 ] = toHalfFloat( y );
  14089. this.array[ index + 2 ] = toHalfFloat( z );
  14090. return this;
  14091. }
  14092. setXYZW( index, x, y, z, w ) {
  14093. index *= this.itemSize;
  14094. if ( this.normalized ) {
  14095. x = normalize( x, this.array );
  14096. y = normalize( y, this.array );
  14097. z = normalize( z, this.array );
  14098. w = normalize( w, this.array );
  14099. }
  14100. this.array[ index + 0 ] = toHalfFloat( x );
  14101. this.array[ index + 1 ] = toHalfFloat( y );
  14102. this.array[ index + 2 ] = toHalfFloat( z );
  14103. this.array[ index + 3 ] = toHalfFloat( w );
  14104. return this;
  14105. }
  14106. }
  14107. /**
  14108. * Convenient class that can be used when creating a `Float32` buffer attribute with
  14109. * a plain `Array` instance.
  14110. *
  14111. * @augments BufferAttribute
  14112. */
  14113. class Float32BufferAttribute extends BufferAttribute {
  14114. /**
  14115. * Constructs a new buffer attribute.
  14116. *
  14117. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  14118. * @param {number} itemSize - The item size.
  14119. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14120. */
  14121. constructor( array, itemSize, normalized ) {
  14122. super( new Float32Array( array ), itemSize, normalized );
  14123. }
  14124. }
  14125. let _id$2 = 0;
  14126. const _m1$2 = /*@__PURE__*/ new Matrix4();
  14127. const _obj = /*@__PURE__*/ new Object3D();
  14128. const _offset = /*@__PURE__*/ new Vector3();
  14129. const _box$2 = /*@__PURE__*/ new Box3();
  14130. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  14131. const _vector$8 = /*@__PURE__*/ new Vector3();
  14132. /**
  14133. * A representation of mesh, line, or point geometry. Includes vertex
  14134. * positions, face indices, normals, colors, UVs, and custom attributes
  14135. * within buffers, reducing the cost of passing all this data to the GPU.
  14136. *
  14137. * ```js
  14138. * const geometry = new THREE.BufferGeometry();
  14139. * // create a simple square shape. We duplicate the top left and bottom right
  14140. * // vertices because each vertex needs to appear once per triangle.
  14141. * const vertices = new Float32Array( [
  14142. * -1.0, -1.0, 1.0, // v0
  14143. * 1.0, -1.0, 1.0, // v1
  14144. * 1.0, 1.0, 1.0, // v2
  14145. *
  14146. * 1.0, 1.0, 1.0, // v3
  14147. * -1.0, 1.0, 1.0, // v4
  14148. * -1.0, -1.0, 1.0 // v5
  14149. * ] );
  14150. * // itemSize = 3 because there are 3 values (components) per vertex
  14151. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  14152. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  14153. * const mesh = new THREE.Mesh( geometry, material );
  14154. * ```
  14155. *
  14156. * @augments EventDispatcher
  14157. */
  14158. class BufferGeometry extends EventDispatcher {
  14159. /**
  14160. * Constructs a new geometry.
  14161. */
  14162. constructor() {
  14163. super();
  14164. /**
  14165. * This flag can be used for type testing.
  14166. *
  14167. * @type {boolean}
  14168. * @readonly
  14169. * @default true
  14170. */
  14171. this.isBufferGeometry = true;
  14172. /**
  14173. * The ID of the geometry.
  14174. *
  14175. * @name BufferGeometry#id
  14176. * @type {number}
  14177. * @readonly
  14178. */
  14179. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  14180. /**
  14181. * The UUID of the geometry.
  14182. *
  14183. * @type {string}
  14184. * @readonly
  14185. */
  14186. this.uuid = generateUUID();
  14187. /**
  14188. * The name of the geometry.
  14189. *
  14190. * @type {string}
  14191. */
  14192. this.name = '';
  14193. this.type = 'BufferGeometry';
  14194. /**
  14195. * Allows for vertices to be re-used across multiple triangles; this is
  14196. * called using "indexed triangles". Each triangle is associated with the
  14197. * indices of three vertices. This attribute therefore stores the index of
  14198. * each vertex for each triangular face. If this attribute is not set, the
  14199. * renderer assumes that each three contiguous positions represent a single triangle.
  14200. *
  14201. * @type {?BufferAttribute}
  14202. * @default null
  14203. */
  14204. this.index = null;
  14205. /**
  14206. * A (storage) buffer attribute which was generated with a compute shader and
  14207. * now defines indirect draw calls.
  14208. *
  14209. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14210. *
  14211. * @type {?BufferAttribute}
  14212. * @default null
  14213. */
  14214. this.indirect = null;
  14215. /**
  14216. * This dictionary has as id the name of the attribute to be set and as value
  14217. * the buffer attribute to set it to. Rather than accessing this property directly,
  14218. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  14219. *
  14220. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  14221. */
  14222. this.attributes = {};
  14223. /**
  14224. * This dictionary holds the morph targets of the geometry.
  14225. *
  14226. * Note: Once the geometry has been rendered, the morph attribute data cannot
  14227. * be changed. You will have to call `dispose()?, and create a new geometry instance.
  14228. *
  14229. * @type {Object}
  14230. */
  14231. this.morphAttributes = {};
  14232. /**
  14233. * Used to control the morph target behavior; when set to `true`, the morph
  14234. * target data is treated as relative offsets, rather than as absolute
  14235. * positions/normals.
  14236. *
  14237. * @type {boolean}
  14238. * @default false
  14239. */
  14240. this.morphTargetsRelative = false;
  14241. /**
  14242. * Split the geometry into groups, each of which will be rendered in a
  14243. * separate draw call. This allows an array of materials to be used with the geometry.
  14244. *
  14245. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  14246. *
  14247. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  14248. * indices, and must not leave vertices or indices unused.
  14249. *
  14250. * @type {Array<Object>}
  14251. */
  14252. this.groups = [];
  14253. /**
  14254. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  14255. *
  14256. * @type {Box3}
  14257. * @default null
  14258. */
  14259. this.boundingBox = null;
  14260. /**
  14261. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  14262. *
  14263. * @type {Sphere}
  14264. * @default null
  14265. */
  14266. this.boundingSphere = null;
  14267. /**
  14268. * Determines the part of the geometry to render. This should not be set directly,
  14269. * instead use `setDrawRange()`.
  14270. *
  14271. * @type {{start:number,count:number}}
  14272. */
  14273. this.drawRange = { start: 0, count: Infinity };
  14274. /**
  14275. * An object that can be used to store custom data about the geometry.
  14276. * It should not hold references to functions as these will not be cloned.
  14277. *
  14278. * @type {Object}
  14279. */
  14280. this.userData = {};
  14281. }
  14282. /**
  14283. * Returns the index of this geometry.
  14284. *
  14285. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  14286. */
  14287. getIndex() {
  14288. return this.index;
  14289. }
  14290. /**
  14291. * Sets the given index to this geometry.
  14292. *
  14293. * @param {Array<number>|BufferAttribute} index - The index to set.
  14294. * @return {BufferGeometry} A reference to this instance.
  14295. */
  14296. setIndex( index ) {
  14297. if ( Array.isArray( index ) ) {
  14298. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  14299. } else {
  14300. this.index = index;
  14301. }
  14302. return this;
  14303. }
  14304. /**
  14305. * Sets the given indirect attribute to this geometry.
  14306. *
  14307. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  14308. * @return {BufferGeometry} A reference to this instance.
  14309. */
  14310. setIndirect( indirect ) {
  14311. this.indirect = indirect;
  14312. return this;
  14313. }
  14314. /**
  14315. * Returns the indirect attribute of this geometry.
  14316. *
  14317. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  14318. */
  14319. getIndirect() {
  14320. return this.indirect;
  14321. }
  14322. /**
  14323. * Returns the buffer attribute for the given name.
  14324. *
  14325. * @param {string} name - The attribute name.
  14326. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  14327. * Returns `undefined` if not attribute has been found.
  14328. */
  14329. getAttribute( name ) {
  14330. return this.attributes[ name ];
  14331. }
  14332. /**
  14333. * Sets the given attribute for the given name.
  14334. *
  14335. * @param {string} name - The attribute name.
  14336. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  14337. * @return {BufferGeometry} A reference to this instance.
  14338. */
  14339. setAttribute( name, attribute ) {
  14340. this.attributes[ name ] = attribute;
  14341. return this;
  14342. }
  14343. /**
  14344. * Deletes the attribute for the given name.
  14345. *
  14346. * @param {string} name - The attribute name to delete.
  14347. * @return {BufferGeometry} A reference to this instance.
  14348. */
  14349. deleteAttribute( name ) {
  14350. delete this.attributes[ name ];
  14351. return this;
  14352. }
  14353. /**
  14354. * Returns `true` if this geometry has an attribute for the given name.
  14355. *
  14356. * @param {string} name - The attribute name.
  14357. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  14358. */
  14359. hasAttribute( name ) {
  14360. return this.attributes[ name ] !== undefined;
  14361. }
  14362. /**
  14363. * Adds a group to this geometry.
  14364. *
  14365. * @param {number} start - The first element in this draw call. That is the first
  14366. * vertex for non-indexed geometry, otherwise the first triangle index.
  14367. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  14368. * @param {number} [materialIndex=0] - The material array index to use.
  14369. */
  14370. addGroup( start, count, materialIndex = 0 ) {
  14371. this.groups.push( {
  14372. start: start,
  14373. count: count,
  14374. materialIndex: materialIndex
  14375. } );
  14376. }
  14377. /**
  14378. * Clears all groups.
  14379. */
  14380. clearGroups() {
  14381. this.groups = [];
  14382. }
  14383. /**
  14384. * Sets the draw range for this geometry.
  14385. *
  14386. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  14387. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  14388. * For indexed BufferGeometry, `count` is the number of indices to render.
  14389. */
  14390. setDrawRange( start, count ) {
  14391. this.drawRange.start = start;
  14392. this.drawRange.count = count;
  14393. }
  14394. /**
  14395. * Applies the given 4x4 transformation matrix to the geometry.
  14396. *
  14397. * @param {Matrix4} matrix - The matrix to apply.
  14398. * @return {BufferGeometry} A reference to this instance.
  14399. */
  14400. applyMatrix4( matrix ) {
  14401. const position = this.attributes.position;
  14402. if ( position !== undefined ) {
  14403. position.applyMatrix4( matrix );
  14404. position.needsUpdate = true;
  14405. }
  14406. const normal = this.attributes.normal;
  14407. if ( normal !== undefined ) {
  14408. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  14409. normal.applyNormalMatrix( normalMatrix );
  14410. normal.needsUpdate = true;
  14411. }
  14412. const tangent = this.attributes.tangent;
  14413. if ( tangent !== undefined ) {
  14414. tangent.transformDirection( matrix );
  14415. tangent.needsUpdate = true;
  14416. }
  14417. if ( this.boundingBox !== null ) {
  14418. this.computeBoundingBox();
  14419. }
  14420. if ( this.boundingSphere !== null ) {
  14421. this.computeBoundingSphere();
  14422. }
  14423. return this;
  14424. }
  14425. /**
  14426. * Applies the rotation represented by the Quaternion to the geometry.
  14427. *
  14428. * @param {Quaternion} q - The Quaternion to apply.
  14429. * @return {BufferGeometry} A reference to this instance.
  14430. */
  14431. applyQuaternion( q ) {
  14432. _m1$2.makeRotationFromQuaternion( q );
  14433. this.applyMatrix4( _m1$2 );
  14434. return this;
  14435. }
  14436. /**
  14437. * Rotates the geometry about the X axis. This is typically done as a one time
  14438. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14439. * real-time mesh rotation.
  14440. *
  14441. * @param {number} angle - The angle in radians.
  14442. * @return {BufferGeometry} A reference to this instance.
  14443. */
  14444. rotateX( angle ) {
  14445. // rotate geometry around world x-axis
  14446. _m1$2.makeRotationX( angle );
  14447. this.applyMatrix4( _m1$2 );
  14448. return this;
  14449. }
  14450. /**
  14451. * Rotates the geometry about the Y axis. This is typically done as a one time
  14452. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14453. * real-time mesh rotation.
  14454. *
  14455. * @param {number} angle - The angle in radians.
  14456. * @return {BufferGeometry} A reference to this instance.
  14457. */
  14458. rotateY( angle ) {
  14459. // rotate geometry around world y-axis
  14460. _m1$2.makeRotationY( angle );
  14461. this.applyMatrix4( _m1$2 );
  14462. return this;
  14463. }
  14464. /**
  14465. * Rotates the geometry about the Z axis. This is typically done as a one time
  14466. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14467. * real-time mesh rotation.
  14468. *
  14469. * @param {number} angle - The angle in radians.
  14470. * @return {BufferGeometry} A reference to this instance.
  14471. */
  14472. rotateZ( angle ) {
  14473. // rotate geometry around world z-axis
  14474. _m1$2.makeRotationZ( angle );
  14475. this.applyMatrix4( _m1$2 );
  14476. return this;
  14477. }
  14478. /**
  14479. * Translates the geometry. This is typically done as a one time
  14480. * operation, and not during a loop. Use {@link Object3D#position} for typical
  14481. * real-time mesh rotation.
  14482. *
  14483. * @param {number} x - The x offset.
  14484. * @param {number} y - The y offset.
  14485. * @param {number} z - The z offset.
  14486. * @return {BufferGeometry} A reference to this instance.
  14487. */
  14488. translate( x, y, z ) {
  14489. // translate geometry
  14490. _m1$2.makeTranslation( x, y, z );
  14491. this.applyMatrix4( _m1$2 );
  14492. return this;
  14493. }
  14494. /**
  14495. * Scales the geometry. This is typically done as a one time
  14496. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14497. * real-time mesh rotation.
  14498. *
  14499. * @param {number} x - The x scale.
  14500. * @param {number} y - The y scale.
  14501. * @param {number} z - The z scale.
  14502. * @return {BufferGeometry} A reference to this instance.
  14503. */
  14504. scale( x, y, z ) {
  14505. // scale geometry
  14506. _m1$2.makeScale( x, y, z );
  14507. this.applyMatrix4( _m1$2 );
  14508. return this;
  14509. }
  14510. /**
  14511. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14512. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14513. * real-time mesh rotation.
  14514. *
  14515. * @param {Vector3} vector - The target point.
  14516. * @return {BufferGeometry} A reference to this instance.
  14517. */
  14518. lookAt( vector ) {
  14519. _obj.lookAt( vector );
  14520. _obj.updateMatrix();
  14521. this.applyMatrix4( _obj.matrix );
  14522. return this;
  14523. }
  14524. /**
  14525. * Center the geometry based on its bounding box.
  14526. *
  14527. * @return {BufferGeometry} A reference to this instance.
  14528. */
  14529. center() {
  14530. this.computeBoundingBox();
  14531. this.boundingBox.getCenter( _offset ).negate();
  14532. this.translate( _offset.x, _offset.y, _offset.z );
  14533. return this;
  14534. }
  14535. /**
  14536. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14537. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14538. * set to `0`.
  14539. *
  14540. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14541. * data from the array. The length of the array must match the vertex count.
  14542. *
  14543. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14544. * @return {BufferGeometry} A reference to this instance.
  14545. */
  14546. setFromPoints( points ) {
  14547. const positionAttribute = this.getAttribute( 'position' );
  14548. if ( positionAttribute === undefined ) {
  14549. const position = [];
  14550. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14551. const point = points[ i ];
  14552. position.push( point.x, point.y, point.z || 0 );
  14553. }
  14554. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14555. } else {
  14556. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14557. for ( let i = 0; i < l; i ++ ) {
  14558. const point = points[ i ];
  14559. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14560. }
  14561. if ( points.length > positionAttribute.count ) {
  14562. console.warn( 'THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14563. }
  14564. positionAttribute.needsUpdate = true;
  14565. }
  14566. return this;
  14567. }
  14568. /**
  14569. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14570. * The bounding box is not computed by the engine; it must be computed by your app.
  14571. * You may need to recompute the bounding box if the geometry vertices are modified.
  14572. */
  14573. computeBoundingBox() {
  14574. if ( this.boundingBox === null ) {
  14575. this.boundingBox = new Box3();
  14576. }
  14577. const position = this.attributes.position;
  14578. const morphAttributesPosition = this.morphAttributes.position;
  14579. if ( position && position.isGLBufferAttribute ) {
  14580. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14581. this.boundingBox.set(
  14582. new Vector3( - Infinity, - Infinity, - Infinity ),
  14583. new Vector3( + Infinity, + Infinity, + Infinity )
  14584. );
  14585. return;
  14586. }
  14587. if ( position !== undefined ) {
  14588. this.boundingBox.setFromBufferAttribute( position );
  14589. // process morph attributes if present
  14590. if ( morphAttributesPosition ) {
  14591. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14592. const morphAttribute = morphAttributesPosition[ i ];
  14593. _box$2.setFromBufferAttribute( morphAttribute );
  14594. if ( this.morphTargetsRelative ) {
  14595. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  14596. this.boundingBox.expandByPoint( _vector$8 );
  14597. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  14598. this.boundingBox.expandByPoint( _vector$8 );
  14599. } else {
  14600. this.boundingBox.expandByPoint( _box$2.min );
  14601. this.boundingBox.expandByPoint( _box$2.max );
  14602. }
  14603. }
  14604. }
  14605. } else {
  14606. this.boundingBox.makeEmpty();
  14607. }
  14608. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14609. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14610. }
  14611. }
  14612. /**
  14613. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14614. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14615. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14616. */
  14617. computeBoundingSphere() {
  14618. if ( this.boundingSphere === null ) {
  14619. this.boundingSphere = new Sphere();
  14620. }
  14621. const position = this.attributes.position;
  14622. const morphAttributesPosition = this.morphAttributes.position;
  14623. if ( position && position.isGLBufferAttribute ) {
  14624. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14625. this.boundingSphere.set( new Vector3(), Infinity );
  14626. return;
  14627. }
  14628. if ( position ) {
  14629. // first, find the center of the bounding sphere
  14630. const center = this.boundingSphere.center;
  14631. _box$2.setFromBufferAttribute( position );
  14632. // process morph attributes if present
  14633. if ( morphAttributesPosition ) {
  14634. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14635. const morphAttribute = morphAttributesPosition[ i ];
  14636. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14637. if ( this.morphTargetsRelative ) {
  14638. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  14639. _box$2.expandByPoint( _vector$8 );
  14640. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  14641. _box$2.expandByPoint( _vector$8 );
  14642. } else {
  14643. _box$2.expandByPoint( _boxMorphTargets.min );
  14644. _box$2.expandByPoint( _boxMorphTargets.max );
  14645. }
  14646. }
  14647. }
  14648. _box$2.getCenter( center );
  14649. // second, try to find a boundingSphere with a radius smaller than the
  14650. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14651. let maxRadiusSq = 0;
  14652. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14653. _vector$8.fromBufferAttribute( position, i );
  14654. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14655. }
  14656. // process morph attributes if present
  14657. if ( morphAttributesPosition ) {
  14658. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14659. const morphAttribute = morphAttributesPosition[ i ];
  14660. const morphTargetsRelative = this.morphTargetsRelative;
  14661. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14662. _vector$8.fromBufferAttribute( morphAttribute, j );
  14663. if ( morphTargetsRelative ) {
  14664. _offset.fromBufferAttribute( position, j );
  14665. _vector$8.add( _offset );
  14666. }
  14667. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14668. }
  14669. }
  14670. }
  14671. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14672. if ( isNaN( this.boundingSphere.radius ) ) {
  14673. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14674. }
  14675. }
  14676. }
  14677. /**
  14678. * Calculates and adds a tangent attribute to this geometry.
  14679. *
  14680. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14681. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14682. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14683. */
  14684. computeTangents() {
  14685. const index = this.index;
  14686. const attributes = this.attributes;
  14687. // based on http://www.terathon.com/code/tangent.html
  14688. // (per vertex tangents)
  14689. if ( index === null ||
  14690. attributes.position === undefined ||
  14691. attributes.normal === undefined ||
  14692. attributes.uv === undefined ) {
  14693. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14694. return;
  14695. }
  14696. const positionAttribute = attributes.position;
  14697. const normalAttribute = attributes.normal;
  14698. const uvAttribute = attributes.uv;
  14699. if ( this.hasAttribute( 'tangent' ) === false ) {
  14700. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14701. }
  14702. const tangentAttribute = this.getAttribute( 'tangent' );
  14703. const tan1 = [], tan2 = [];
  14704. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14705. tan1[ i ] = new Vector3();
  14706. tan2[ i ] = new Vector3();
  14707. }
  14708. const vA = new Vector3(),
  14709. vB = new Vector3(),
  14710. vC = new Vector3(),
  14711. uvA = new Vector2(),
  14712. uvB = new Vector2(),
  14713. uvC = new Vector2(),
  14714. sdir = new Vector3(),
  14715. tdir = new Vector3();
  14716. function handleTriangle( a, b, c ) {
  14717. vA.fromBufferAttribute( positionAttribute, a );
  14718. vB.fromBufferAttribute( positionAttribute, b );
  14719. vC.fromBufferAttribute( positionAttribute, c );
  14720. uvA.fromBufferAttribute( uvAttribute, a );
  14721. uvB.fromBufferAttribute( uvAttribute, b );
  14722. uvC.fromBufferAttribute( uvAttribute, c );
  14723. vB.sub( vA );
  14724. vC.sub( vA );
  14725. uvB.sub( uvA );
  14726. uvC.sub( uvA );
  14727. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14728. // silently ignore degenerate uv triangles having coincident or colinear vertices
  14729. if ( ! isFinite( r ) ) return;
  14730. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  14731. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  14732. tan1[ a ].add( sdir );
  14733. tan1[ b ].add( sdir );
  14734. tan1[ c ].add( sdir );
  14735. tan2[ a ].add( tdir );
  14736. tan2[ b ].add( tdir );
  14737. tan2[ c ].add( tdir );
  14738. }
  14739. let groups = this.groups;
  14740. if ( groups.length === 0 ) {
  14741. groups = [ {
  14742. start: 0,
  14743. count: index.count
  14744. } ];
  14745. }
  14746. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14747. const group = groups[ i ];
  14748. const start = group.start;
  14749. const count = group.count;
  14750. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14751. handleTriangle(
  14752. index.getX( j + 0 ),
  14753. index.getX( j + 1 ),
  14754. index.getX( j + 2 )
  14755. );
  14756. }
  14757. }
  14758. const tmp = new Vector3(), tmp2 = new Vector3();
  14759. const n = new Vector3(), n2 = new Vector3();
  14760. function handleVertex( v ) {
  14761. n.fromBufferAttribute( normalAttribute, v );
  14762. n2.copy( n );
  14763. const t = tan1[ v ];
  14764. // Gram-Schmidt orthogonalize
  14765. tmp.copy( t );
  14766. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  14767. // Calculate handedness
  14768. tmp2.crossVectors( n2, t );
  14769. const test = tmp2.dot( tan2[ v ] );
  14770. const w = ( test < 0.0 ) ? -1 : 1.0;
  14771. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  14772. }
  14773. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14774. const group = groups[ i ];
  14775. const start = group.start;
  14776. const count = group.count;
  14777. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14778. handleVertex( index.getX( j + 0 ) );
  14779. handleVertex( index.getX( j + 1 ) );
  14780. handleVertex( index.getX( j + 2 ) );
  14781. }
  14782. }
  14783. }
  14784. /**
  14785. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  14786. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  14787. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  14788. * to be the same as the face normal.
  14789. */
  14790. computeVertexNormals() {
  14791. const index = this.index;
  14792. const positionAttribute = this.getAttribute( 'position' );
  14793. if ( positionAttribute !== undefined ) {
  14794. let normalAttribute = this.getAttribute( 'normal' );
  14795. if ( normalAttribute === undefined ) {
  14796. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  14797. this.setAttribute( 'normal', normalAttribute );
  14798. } else {
  14799. // reset existing normals to zero
  14800. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  14801. normalAttribute.setXYZ( i, 0, 0, 0 );
  14802. }
  14803. }
  14804. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  14805. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  14806. const cb = new Vector3(), ab = new Vector3();
  14807. // indexed elements
  14808. if ( index ) {
  14809. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  14810. const vA = index.getX( i + 0 );
  14811. const vB = index.getX( i + 1 );
  14812. const vC = index.getX( i + 2 );
  14813. pA.fromBufferAttribute( positionAttribute, vA );
  14814. pB.fromBufferAttribute( positionAttribute, vB );
  14815. pC.fromBufferAttribute( positionAttribute, vC );
  14816. cb.subVectors( pC, pB );
  14817. ab.subVectors( pA, pB );
  14818. cb.cross( ab );
  14819. nA.fromBufferAttribute( normalAttribute, vA );
  14820. nB.fromBufferAttribute( normalAttribute, vB );
  14821. nC.fromBufferAttribute( normalAttribute, vC );
  14822. nA.add( cb );
  14823. nB.add( cb );
  14824. nC.add( cb );
  14825. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  14826. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  14827. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  14828. }
  14829. } else {
  14830. // non-indexed elements (unconnected triangle soup)
  14831. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  14832. pA.fromBufferAttribute( positionAttribute, i + 0 );
  14833. pB.fromBufferAttribute( positionAttribute, i + 1 );
  14834. pC.fromBufferAttribute( positionAttribute, i + 2 );
  14835. cb.subVectors( pC, pB );
  14836. ab.subVectors( pA, pB );
  14837. cb.cross( ab );
  14838. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  14839. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  14840. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  14841. }
  14842. }
  14843. this.normalizeNormals();
  14844. normalAttribute.needsUpdate = true;
  14845. }
  14846. }
  14847. /**
  14848. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  14849. * correct lighting on the geometry surfaces.
  14850. */
  14851. normalizeNormals() {
  14852. const normals = this.attributes.normal;
  14853. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  14854. _vector$8.fromBufferAttribute( normals, i );
  14855. _vector$8.normalize();
  14856. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14857. }
  14858. }
  14859. /**
  14860. * Return a new non-index version of this indexed geometry. If the geometry
  14861. * is already non-indexed, the method is a NOOP.
  14862. *
  14863. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  14864. */
  14865. toNonIndexed() {
  14866. function convertBufferAttribute( attribute, indices ) {
  14867. const array = attribute.array;
  14868. const itemSize = attribute.itemSize;
  14869. const normalized = attribute.normalized;
  14870. const array2 = new array.constructor( indices.length * itemSize );
  14871. let index = 0, index2 = 0;
  14872. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  14873. if ( attribute.isInterleavedBufferAttribute ) {
  14874. index = indices[ i ] * attribute.data.stride + attribute.offset;
  14875. } else {
  14876. index = indices[ i ] * itemSize;
  14877. }
  14878. for ( let j = 0; j < itemSize; j ++ ) {
  14879. array2[ index2 ++ ] = array[ index ++ ];
  14880. }
  14881. }
  14882. return new BufferAttribute( array2, itemSize, normalized );
  14883. }
  14884. //
  14885. if ( this.index === null ) {
  14886. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  14887. return this;
  14888. }
  14889. const geometry2 = new BufferGeometry();
  14890. const indices = this.index.array;
  14891. const attributes = this.attributes;
  14892. // attributes
  14893. for ( const name in attributes ) {
  14894. const attribute = attributes[ name ];
  14895. const newAttribute = convertBufferAttribute( attribute, indices );
  14896. geometry2.setAttribute( name, newAttribute );
  14897. }
  14898. // morph attributes
  14899. const morphAttributes = this.morphAttributes;
  14900. for ( const name in morphAttributes ) {
  14901. const morphArray = [];
  14902. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14903. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  14904. const attribute = morphAttribute[ i ];
  14905. const newAttribute = convertBufferAttribute( attribute, indices );
  14906. morphArray.push( newAttribute );
  14907. }
  14908. geometry2.morphAttributes[ name ] = morphArray;
  14909. }
  14910. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  14911. // groups
  14912. const groups = this.groups;
  14913. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14914. const group = groups[ i ];
  14915. geometry2.addGroup( group.start, group.count, group.materialIndex );
  14916. }
  14917. return geometry2;
  14918. }
  14919. /**
  14920. * Serializes the geometry into JSON.
  14921. *
  14922. * @return {Object} A JSON object representing the serialized geometry.
  14923. */
  14924. toJSON() {
  14925. const data = {
  14926. metadata: {
  14927. version: 4.7,
  14928. type: 'BufferGeometry',
  14929. generator: 'BufferGeometry.toJSON'
  14930. }
  14931. };
  14932. // standard BufferGeometry serialization
  14933. data.uuid = this.uuid;
  14934. data.type = this.type;
  14935. if ( this.name !== '' ) data.name = this.name;
  14936. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  14937. if ( this.parameters !== undefined ) {
  14938. const parameters = this.parameters;
  14939. for ( const key in parameters ) {
  14940. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  14941. }
  14942. return data;
  14943. }
  14944. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  14945. data.data = { attributes: {} };
  14946. const index = this.index;
  14947. if ( index !== null ) {
  14948. data.data.index = {
  14949. type: index.array.constructor.name,
  14950. array: Array.prototype.slice.call( index.array )
  14951. };
  14952. }
  14953. const attributes = this.attributes;
  14954. for ( const key in attributes ) {
  14955. const attribute = attributes[ key ];
  14956. data.data.attributes[ key ] = attribute.toJSON( data.data );
  14957. }
  14958. const morphAttributes = {};
  14959. let hasMorphAttributes = false;
  14960. for ( const key in this.morphAttributes ) {
  14961. const attributeArray = this.morphAttributes[ key ];
  14962. const array = [];
  14963. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  14964. const attribute = attributeArray[ i ];
  14965. array.push( attribute.toJSON( data.data ) );
  14966. }
  14967. if ( array.length > 0 ) {
  14968. morphAttributes[ key ] = array;
  14969. hasMorphAttributes = true;
  14970. }
  14971. }
  14972. if ( hasMorphAttributes ) {
  14973. data.data.morphAttributes = morphAttributes;
  14974. data.data.morphTargetsRelative = this.morphTargetsRelative;
  14975. }
  14976. const groups = this.groups;
  14977. if ( groups.length > 0 ) {
  14978. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  14979. }
  14980. const boundingSphere = this.boundingSphere;
  14981. if ( boundingSphere !== null ) {
  14982. data.data.boundingSphere = boundingSphere.toJSON();
  14983. }
  14984. return data;
  14985. }
  14986. /**
  14987. * Returns a new geometry with copied values from this instance.
  14988. *
  14989. * @return {BufferGeometry} A clone of this instance.
  14990. */
  14991. clone() {
  14992. return new this.constructor().copy( this );
  14993. }
  14994. /**
  14995. * Copies the values of the given geometry to this instance.
  14996. *
  14997. * @param {BufferGeometry} source - The geometry to copy.
  14998. * @return {BufferGeometry} A reference to this instance.
  14999. */
  15000. copy( source ) {
  15001. // reset
  15002. this.index = null;
  15003. this.attributes = {};
  15004. this.morphAttributes = {};
  15005. this.groups = [];
  15006. this.boundingBox = null;
  15007. this.boundingSphere = null;
  15008. // used for storing cloned, shared data
  15009. const data = {};
  15010. // name
  15011. this.name = source.name;
  15012. // index
  15013. const index = source.index;
  15014. if ( index !== null ) {
  15015. this.setIndex( index.clone() );
  15016. }
  15017. // attributes
  15018. const attributes = source.attributes;
  15019. for ( const name in attributes ) {
  15020. const attribute = attributes[ name ];
  15021. this.setAttribute( name, attribute.clone( data ) );
  15022. }
  15023. // morph attributes
  15024. const morphAttributes = source.morphAttributes;
  15025. for ( const name in morphAttributes ) {
  15026. const array = [];
  15027. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  15028. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  15029. array.push( morphAttribute[ i ].clone( data ) );
  15030. }
  15031. this.morphAttributes[ name ] = array;
  15032. }
  15033. this.morphTargetsRelative = source.morphTargetsRelative;
  15034. // groups
  15035. const groups = source.groups;
  15036. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15037. const group = groups[ i ];
  15038. this.addGroup( group.start, group.count, group.materialIndex );
  15039. }
  15040. // bounding box
  15041. const boundingBox = source.boundingBox;
  15042. if ( boundingBox !== null ) {
  15043. this.boundingBox = boundingBox.clone();
  15044. }
  15045. // bounding sphere
  15046. const boundingSphere = source.boundingSphere;
  15047. if ( boundingSphere !== null ) {
  15048. this.boundingSphere = boundingSphere.clone();
  15049. }
  15050. // draw range
  15051. this.drawRange.start = source.drawRange.start;
  15052. this.drawRange.count = source.drawRange.count;
  15053. // user data
  15054. this.userData = source.userData;
  15055. return this;
  15056. }
  15057. /**
  15058. * Frees the GPU-related resources allocated by this instance. Call this
  15059. * method whenever this instance is no longer used in your app.
  15060. *
  15061. * @fires BufferGeometry#dispose
  15062. */
  15063. dispose() {
  15064. this.dispatchEvent( { type: 'dispose' } );
  15065. }
  15066. }
  15067. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  15068. const _ray$3 = /*@__PURE__*/ new Ray();
  15069. const _sphere$6 = /*@__PURE__*/ new Sphere();
  15070. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  15071. const _vA$1 = /*@__PURE__*/ new Vector3();
  15072. const _vB$1 = /*@__PURE__*/ new Vector3();
  15073. const _vC$1 = /*@__PURE__*/ new Vector3();
  15074. const _tempA = /*@__PURE__*/ new Vector3();
  15075. const _morphA = /*@__PURE__*/ new Vector3();
  15076. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  15077. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  15078. /**
  15079. * Class representing triangular polygon mesh based objects.
  15080. *
  15081. * ```js
  15082. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15083. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  15084. * const mesh = new THREE.Mesh( geometry, material );
  15085. * scene.add( mesh );
  15086. * ```
  15087. *
  15088. * @augments Object3D
  15089. */
  15090. class Mesh extends Object3D {
  15091. /**
  15092. * Constructs a new mesh.
  15093. *
  15094. * @param {BufferGeometry} [geometry] - The mesh geometry.
  15095. * @param {Material|Array<Material>} [material] - The mesh material.
  15096. */
  15097. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  15098. super();
  15099. /**
  15100. * This flag can be used for type testing.
  15101. *
  15102. * @type {boolean}
  15103. * @readonly
  15104. * @default true
  15105. */
  15106. this.isMesh = true;
  15107. this.type = 'Mesh';
  15108. /**
  15109. * The mesh geometry.
  15110. *
  15111. * @type {BufferGeometry}
  15112. */
  15113. this.geometry = geometry;
  15114. /**
  15115. * The mesh material.
  15116. *
  15117. * @type {Material|Array<Material>}
  15118. * @default MeshBasicMaterial
  15119. */
  15120. this.material = material;
  15121. /**
  15122. * A dictionary representing the morph targets in the geometry. The key is the
  15123. * morph targets name, the value its attribute index. This member is `undefined`
  15124. * by default and only set when morph targets are detected in the geometry.
  15125. *
  15126. * @type {Object<String,number>|undefined}
  15127. * @default undefined
  15128. */
  15129. this.morphTargetDictionary = undefined;
  15130. /**
  15131. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  15132. * is applied. This member is `undefined` by default and only set when morph targets are
  15133. * detected in the geometry.
  15134. *
  15135. * @type {Array<number>|undefined}
  15136. * @default undefined
  15137. */
  15138. this.morphTargetInfluences = undefined;
  15139. /**
  15140. * The number of instances of this mesh.
  15141. * Can only be used with {@link WebGPURenderer}.
  15142. *
  15143. * @type {number}
  15144. * @default 1
  15145. */
  15146. this.count = 1;
  15147. this.updateMorphTargets();
  15148. }
  15149. copy( source, recursive ) {
  15150. super.copy( source, recursive );
  15151. if ( source.morphTargetInfluences !== undefined ) {
  15152. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  15153. }
  15154. if ( source.morphTargetDictionary !== undefined ) {
  15155. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  15156. }
  15157. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  15158. this.geometry = source.geometry;
  15159. return this;
  15160. }
  15161. /**
  15162. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  15163. * to make sure existing morph targets can influence this 3D object.
  15164. */
  15165. updateMorphTargets() {
  15166. const geometry = this.geometry;
  15167. const morphAttributes = geometry.morphAttributes;
  15168. const keys = Object.keys( morphAttributes );
  15169. if ( keys.length > 0 ) {
  15170. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  15171. if ( morphAttribute !== undefined ) {
  15172. this.morphTargetInfluences = [];
  15173. this.morphTargetDictionary = {};
  15174. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  15175. const name = morphAttribute[ m ].name || String( m );
  15176. this.morphTargetInfluences.push( 0 );
  15177. this.morphTargetDictionary[ name ] = m;
  15178. }
  15179. }
  15180. }
  15181. }
  15182. /**
  15183. * Returns the local-space position of the vertex at the given index, taking into
  15184. * account the current animation state of both morph targets and skinning.
  15185. *
  15186. * @param {number} index - The vertex index.
  15187. * @param {Vector3} target - The target object that is used to store the method's result.
  15188. * @return {Vector3} The vertex position in local space.
  15189. */
  15190. getVertexPosition( index, target ) {
  15191. const geometry = this.geometry;
  15192. const position = geometry.attributes.position;
  15193. const morphPosition = geometry.morphAttributes.position;
  15194. const morphTargetsRelative = geometry.morphTargetsRelative;
  15195. target.fromBufferAttribute( position, index );
  15196. const morphInfluences = this.morphTargetInfluences;
  15197. if ( morphPosition && morphInfluences ) {
  15198. _morphA.set( 0, 0, 0 );
  15199. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  15200. const influence = morphInfluences[ i ];
  15201. const morphAttribute = morphPosition[ i ];
  15202. if ( influence === 0 ) continue;
  15203. _tempA.fromBufferAttribute( morphAttribute, index );
  15204. if ( morphTargetsRelative ) {
  15205. _morphA.addScaledVector( _tempA, influence );
  15206. } else {
  15207. _morphA.addScaledVector( _tempA.sub( target ), influence );
  15208. }
  15209. }
  15210. target.add( _morphA );
  15211. }
  15212. return target;
  15213. }
  15214. /**
  15215. * Computes intersection points between a casted ray and this line.
  15216. *
  15217. * @param {Raycaster} raycaster - The raycaster.
  15218. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  15219. */
  15220. raycast( raycaster, intersects ) {
  15221. const geometry = this.geometry;
  15222. const material = this.material;
  15223. const matrixWorld = this.matrixWorld;
  15224. if ( material === undefined ) return;
  15225. // test with bounding sphere in world space
  15226. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15227. _sphere$6.copy( geometry.boundingSphere );
  15228. _sphere$6.applyMatrix4( matrixWorld );
  15229. // check distance from ray origin to bounding sphere
  15230. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  15231. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  15232. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  15233. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  15234. }
  15235. // convert ray to local space of mesh
  15236. _inverseMatrix$3.copy( matrixWorld ).invert();
  15237. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  15238. // test with bounding box in local space
  15239. if ( geometry.boundingBox !== null ) {
  15240. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  15241. }
  15242. // test for intersections with geometry
  15243. this._computeIntersections( raycaster, intersects, _ray$3 );
  15244. }
  15245. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  15246. let intersection;
  15247. const geometry = this.geometry;
  15248. const material = this.material;
  15249. const index = geometry.index;
  15250. const position = geometry.attributes.position;
  15251. const uv = geometry.attributes.uv;
  15252. const uv1 = geometry.attributes.uv1;
  15253. const normal = geometry.attributes.normal;
  15254. const groups = geometry.groups;
  15255. const drawRange = geometry.drawRange;
  15256. if ( index !== null ) {
  15257. // indexed buffer geometry
  15258. if ( Array.isArray( material ) ) {
  15259. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15260. const group = groups[ i ];
  15261. const groupMaterial = material[ group.materialIndex ];
  15262. const start = Math.max( group.start, drawRange.start );
  15263. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15264. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15265. const a = index.getX( j );
  15266. const b = index.getX( j + 1 );
  15267. const c = index.getX( j + 2 );
  15268. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15269. if ( intersection ) {
  15270. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  15271. intersection.face.materialIndex = group.materialIndex;
  15272. intersects.push( intersection );
  15273. }
  15274. }
  15275. }
  15276. } else {
  15277. const start = Math.max( 0, drawRange.start );
  15278. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15279. for ( let i = start, il = end; i < il; i += 3 ) {
  15280. const a = index.getX( i );
  15281. const b = index.getX( i + 1 );
  15282. const c = index.getX( i + 2 );
  15283. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15284. if ( intersection ) {
  15285. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  15286. intersects.push( intersection );
  15287. }
  15288. }
  15289. }
  15290. } else if ( position !== undefined ) {
  15291. // non-indexed buffer geometry
  15292. if ( Array.isArray( material ) ) {
  15293. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15294. const group = groups[ i ];
  15295. const groupMaterial = material[ group.materialIndex ];
  15296. const start = Math.max( group.start, drawRange.start );
  15297. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15298. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15299. const a = j;
  15300. const b = j + 1;
  15301. const c = j + 2;
  15302. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15303. if ( intersection ) {
  15304. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  15305. intersection.face.materialIndex = group.materialIndex;
  15306. intersects.push( intersection );
  15307. }
  15308. }
  15309. }
  15310. } else {
  15311. const start = Math.max( 0, drawRange.start );
  15312. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  15313. for ( let i = start, il = end; i < il; i += 3 ) {
  15314. const a = i;
  15315. const b = i + 1;
  15316. const c = i + 2;
  15317. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15318. if ( intersection ) {
  15319. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  15320. intersects.push( intersection );
  15321. }
  15322. }
  15323. }
  15324. }
  15325. }
  15326. }
  15327. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  15328. let intersect;
  15329. if ( material.side === BackSide ) {
  15330. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  15331. } else {
  15332. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  15333. }
  15334. if ( intersect === null ) return null;
  15335. _intersectionPointWorld.copy( point );
  15336. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  15337. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  15338. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  15339. return {
  15340. distance: distance,
  15341. point: _intersectionPointWorld.clone(),
  15342. object: object
  15343. };
  15344. }
  15345. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  15346. object.getVertexPosition( a, _vA$1 );
  15347. object.getVertexPosition( b, _vB$1 );
  15348. object.getVertexPosition( c, _vC$1 );
  15349. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  15350. if ( intersection ) {
  15351. const barycoord = new Vector3();
  15352. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  15353. if ( uv ) {
  15354. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  15355. }
  15356. if ( uv1 ) {
  15357. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  15358. }
  15359. if ( normal ) {
  15360. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  15361. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  15362. intersection.normal.multiplyScalar( -1 );
  15363. }
  15364. }
  15365. const face = {
  15366. a: a,
  15367. b: b,
  15368. c: c,
  15369. normal: new Vector3(),
  15370. materialIndex: 0
  15371. };
  15372. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  15373. intersection.face = face;
  15374. intersection.barycoord = barycoord;
  15375. }
  15376. return intersection;
  15377. }
  15378. /**
  15379. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  15380. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  15381. * of the axes.
  15382. *
  15383. * ```js
  15384. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15385. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  15386. * const cube = new THREE.Mesh( geometry, material );
  15387. * scene.add( cube );
  15388. * ```
  15389. *
  15390. * @augments BufferGeometry
  15391. */
  15392. class BoxGeometry extends BufferGeometry {
  15393. /**
  15394. * Constructs a new box geometry.
  15395. *
  15396. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  15397. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  15398. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  15399. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  15400. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  15401. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  15402. */
  15403. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  15404. super();
  15405. this.type = 'BoxGeometry';
  15406. /**
  15407. * Holds the constructor parameters that have been
  15408. * used to generate the geometry. Any modification
  15409. * after instantiation does not change the geometry.
  15410. *
  15411. * @type {Object}
  15412. */
  15413. this.parameters = {
  15414. width: width,
  15415. height: height,
  15416. depth: depth,
  15417. widthSegments: widthSegments,
  15418. heightSegments: heightSegments,
  15419. depthSegments: depthSegments
  15420. };
  15421. const scope = this;
  15422. // segments
  15423. widthSegments = Math.floor( widthSegments );
  15424. heightSegments = Math.floor( heightSegments );
  15425. depthSegments = Math.floor( depthSegments );
  15426. // buffers
  15427. const indices = [];
  15428. const vertices = [];
  15429. const normals = [];
  15430. const uvs = [];
  15431. // helper variables
  15432. let numberOfVertices = 0;
  15433. let groupStart = 0;
  15434. // build each side of the box geometry
  15435. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  15436. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  15437. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  15438. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  15439. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  15440. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  15441. // build geometry
  15442. this.setIndex( indices );
  15443. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15444. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15445. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15446. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  15447. const segmentWidth = width / gridX;
  15448. const segmentHeight = height / gridY;
  15449. const widthHalf = width / 2;
  15450. const heightHalf = height / 2;
  15451. const depthHalf = depth / 2;
  15452. const gridX1 = gridX + 1;
  15453. const gridY1 = gridY + 1;
  15454. let vertexCounter = 0;
  15455. let groupCount = 0;
  15456. const vector = new Vector3();
  15457. // generate vertices, normals and uvs
  15458. for ( let iy = 0; iy < gridY1; iy ++ ) {
  15459. const y = iy * segmentHeight - heightHalf;
  15460. for ( let ix = 0; ix < gridX1; ix ++ ) {
  15461. const x = ix * segmentWidth - widthHalf;
  15462. // set values to correct vector component
  15463. vector[ u ] = x * udir;
  15464. vector[ v ] = y * vdir;
  15465. vector[ w ] = depthHalf;
  15466. // now apply vector to vertex buffer
  15467. vertices.push( vector.x, vector.y, vector.z );
  15468. // set values to correct vector component
  15469. vector[ u ] = 0;
  15470. vector[ v ] = 0;
  15471. vector[ w ] = depth > 0 ? 1 : -1;
  15472. // now apply vector to normal buffer
  15473. normals.push( vector.x, vector.y, vector.z );
  15474. // uvs
  15475. uvs.push( ix / gridX );
  15476. uvs.push( 1 - ( iy / gridY ) );
  15477. // counters
  15478. vertexCounter += 1;
  15479. }
  15480. }
  15481. // indices
  15482. // 1. you need three indices to draw a single face
  15483. // 2. a single segment consists of two faces
  15484. // 3. so we need to generate six (2*3) indices per segment
  15485. for ( let iy = 0; iy < gridY; iy ++ ) {
  15486. for ( let ix = 0; ix < gridX; ix ++ ) {
  15487. const a = numberOfVertices + ix + gridX1 * iy;
  15488. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  15489. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  15490. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  15491. // faces
  15492. indices.push( a, b, d );
  15493. indices.push( b, c, d );
  15494. // increase counter
  15495. groupCount += 6;
  15496. }
  15497. }
  15498. // add a group to the geometry. this will ensure multi material support
  15499. scope.addGroup( groupStart, groupCount, materialIndex );
  15500. // calculate new start value for groups
  15501. groupStart += groupCount;
  15502. // update total number of vertices
  15503. numberOfVertices += vertexCounter;
  15504. }
  15505. }
  15506. copy( source ) {
  15507. super.copy( source );
  15508. this.parameters = Object.assign( {}, source.parameters );
  15509. return this;
  15510. }
  15511. /**
  15512. * Factory method for creating an instance of this class from the given
  15513. * JSON object.
  15514. *
  15515. * @param {Object} data - A JSON object representing the serialized geometry.
  15516. * @return {BoxGeometry} A new instance.
  15517. */
  15518. static fromJSON( data ) {
  15519. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  15520. }
  15521. }
  15522. // Uniform Utilities
  15523. function cloneUniforms( src ) {
  15524. const dst = {};
  15525. for ( const u in src ) {
  15526. dst[ u ] = {};
  15527. for ( const p in src[ u ] ) {
  15528. const property = src[ u ][ p ];
  15529. if ( property && ( property.isColor ||
  15530. property.isMatrix3 || property.isMatrix4 ||
  15531. property.isVector2 || property.isVector3 || property.isVector4 ||
  15532. property.isTexture || property.isQuaternion ) ) {
  15533. if ( property.isRenderTargetTexture ) {
  15534. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  15535. dst[ u ][ p ] = null;
  15536. } else {
  15537. dst[ u ][ p ] = property.clone();
  15538. }
  15539. } else if ( Array.isArray( property ) ) {
  15540. dst[ u ][ p ] = property.slice();
  15541. } else {
  15542. dst[ u ][ p ] = property;
  15543. }
  15544. }
  15545. }
  15546. return dst;
  15547. }
  15548. function mergeUniforms( uniforms ) {
  15549. const merged = {};
  15550. for ( let u = 0; u < uniforms.length; u ++ ) {
  15551. const tmp = cloneUniforms( uniforms[ u ] );
  15552. for ( const p in tmp ) {
  15553. merged[ p ] = tmp[ p ];
  15554. }
  15555. }
  15556. return merged;
  15557. }
  15558. function cloneUniformsGroups( src ) {
  15559. const dst = [];
  15560. for ( let u = 0; u < src.length; u ++ ) {
  15561. dst.push( src[ u ].clone() );
  15562. }
  15563. return dst;
  15564. }
  15565. function getUnlitUniformColorSpace( renderer ) {
  15566. const currentRenderTarget = renderer.getRenderTarget();
  15567. if ( currentRenderTarget === null ) {
  15568. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  15569. return renderer.outputColorSpace;
  15570. }
  15571. // https://github.com/mrdoob/three.js/issues/27868
  15572. if ( currentRenderTarget.isXRRenderTarget === true ) {
  15573. return currentRenderTarget.texture.colorSpace;
  15574. }
  15575. return ColorManagement.workingColorSpace;
  15576. }
  15577. // Legacy
  15578. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  15579. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  15580. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  15581. /**
  15582. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  15583. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  15584. * effect not included with any of the built-in materials.
  15585. *
  15586. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  15587. *
  15588. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  15589. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  15590. * you don't want that, use {@link RawShaderMaterial} instead.
  15591. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  15592. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  15593. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  15594. * - The loop has to be [normalized]{@link https://en.wikipedia.org/wiki/Normalized_loop}.
  15595. * - The loop variable has to be *i*.
  15596. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  15597. * value of *i* for the given iteration and can be used in preprocessor
  15598. * statements.
  15599. *
  15600. * ```js
  15601. * const material = new THREE.ShaderMaterial( {
  15602. * uniforms: {
  15603. * time: { value: 1.0 },
  15604. * resolution: { value: new THREE.Vector2() }
  15605. * },
  15606. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  15607. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  15608. * } );
  15609. * ```
  15610. *
  15611. * @augments Material
  15612. */
  15613. class ShaderMaterial extends Material {
  15614. /**
  15615. * Constructs a new shader material.
  15616. *
  15617. * @param {Object} [parameters] - An object with one or more properties
  15618. * defining the material's appearance. Any property of the material
  15619. * (including any property from inherited materials) can be passed
  15620. * in here. Color values can be passed any type of value accepted
  15621. * by {@link Color#set}.
  15622. */
  15623. constructor( parameters ) {
  15624. super();
  15625. /**
  15626. * This flag can be used for type testing.
  15627. *
  15628. * @type {boolean}
  15629. * @readonly
  15630. * @default true
  15631. */
  15632. this.isShaderMaterial = true;
  15633. this.type = 'ShaderMaterial';
  15634. /**
  15635. * Defines custom constants using `#define` directives within the GLSL code
  15636. * for both the vertex shader and the fragment shader; each key/value pair
  15637. * yields another directive.
  15638. * ```js
  15639. * defines: {
  15640. * FOO: 15,
  15641. * BAR: true
  15642. * }
  15643. * ```
  15644. * Yields the lines:
  15645. * ```
  15646. * #define FOO 15
  15647. * #define BAR true
  15648. * ```
  15649. *
  15650. * @type {Object}
  15651. */
  15652. this.defines = {};
  15653. /**
  15654. * An object of the form:
  15655. * ```js
  15656. * {
  15657. * "uniform1": { value: 1.0 },
  15658. * "uniform2": { value: 2 }
  15659. * }
  15660. * ```
  15661. * specifying the uniforms to be passed to the shader code; keys are uniform
  15662. * names, values are definitions of the form
  15663. * ```
  15664. * {
  15665. * value: 1.0
  15666. * }
  15667. * ```
  15668. * where `value` is the value of the uniform. Names must match the name of
  15669. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  15670. * on every frame, so updating the value of the uniform will immediately
  15671. * update the value available to the GLSL code.
  15672. *
  15673. * @type {Object}
  15674. */
  15675. this.uniforms = {};
  15676. /**
  15677. * An array holding uniforms groups for configuring UBOs.
  15678. *
  15679. * @type {Array<UniformsGroup>}
  15680. */
  15681. this.uniformsGroups = [];
  15682. /**
  15683. * Vertex shader GLSL code. This is the actual code for the shader.
  15684. *
  15685. * @type {string}
  15686. */
  15687. this.vertexShader = default_vertex;
  15688. /**
  15689. * Fragment shader GLSL code. This is the actual code for the shader.
  15690. *
  15691. * @type {string}
  15692. */
  15693. this.fragmentShader = default_fragment;
  15694. /**
  15695. * Controls line thickness or lines.
  15696. *
  15697. * WebGL and WebGPU ignore this setting and always render line primitives with a
  15698. * width of one pixel.
  15699. *
  15700. * @type {number}
  15701. * @default 1
  15702. */
  15703. this.linewidth = 1;
  15704. /**
  15705. * Renders the geometry as a wireframe.
  15706. *
  15707. * @type {boolean}
  15708. * @default false
  15709. */
  15710. this.wireframe = false;
  15711. /**
  15712. * Controls the thickness of the wireframe.
  15713. *
  15714. * WebGL and WebGPU ignore this property and always render
  15715. * 1 pixel wide lines.
  15716. *
  15717. * @type {number}
  15718. * @default 1
  15719. */
  15720. this.wireframeLinewidth = 1;
  15721. /**
  15722. * Define whether the material color is affected by global fog settings; `true`
  15723. * to pass fog uniforms to the shader.
  15724. *
  15725. * @type {boolean}
  15726. * @default false
  15727. */
  15728. this.fog = false;
  15729. /**
  15730. * Defines whether this material uses lighting; `true` to pass uniform data
  15731. * related to lighting to this shader.
  15732. *
  15733. * @type {boolean}
  15734. * @default false
  15735. */
  15736. this.lights = false;
  15737. /**
  15738. * Defines whether this material supports clipping; `true` to let the renderer
  15739. * pass the clippingPlanes uniform.
  15740. *
  15741. * @type {boolean}
  15742. * @default false
  15743. */
  15744. this.clipping = false;
  15745. /**
  15746. * Overwritten and set to `true` by default.
  15747. *
  15748. * @type {boolean}
  15749. * @default true
  15750. */
  15751. this.forceSinglePass = true;
  15752. /**
  15753. * This object allows to enable certain WebGL 2 extensions.
  15754. *
  15755. * - clipCullDistance: set to `true` to use vertex shader clipping
  15756. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  15757. *
  15758. * @type {{clipCullDistance:false,multiDraw:false}}
  15759. */
  15760. this.extensions = {
  15761. clipCullDistance: false, // set to use vertex shader clipping
  15762. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  15763. };
  15764. /**
  15765. * When the rendered geometry doesn't include these attributes but the
  15766. * material does, these default values will be passed to the shaders. This
  15767. * avoids errors when buffer data is missing.
  15768. *
  15769. * - color: [ 1, 1, 1 ]
  15770. * - uv: [ 0, 0 ]
  15771. * - uv1: [ 0, 0 ]
  15772. *
  15773. * @type {Object}
  15774. */
  15775. this.defaultAttributeValues = {
  15776. 'color': [ 1, 1, 1 ],
  15777. 'uv': [ 0, 0 ],
  15778. 'uv1': [ 0, 0 ]
  15779. };
  15780. /**
  15781. * If set, this calls [gl.bindAttribLocation]{@link https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation}
  15782. * to bind a generic vertex index to an attribute variable.
  15783. *
  15784. * @type {string|undefined}
  15785. * @default undefined
  15786. */
  15787. this.index0AttributeName = undefined;
  15788. /**
  15789. * Can be used to force a uniform update while changing uniforms in
  15790. * {@link Object3D#onBeforeRender}.
  15791. *
  15792. * @type {boolean}
  15793. * @default false
  15794. */
  15795. this.uniformsNeedUpdate = false;
  15796. /**
  15797. * Defines the GLSL version of custom shader code.
  15798. *
  15799. * @type {?(GLSL1|GLSL3)}
  15800. * @default null
  15801. */
  15802. this.glslVersion = null;
  15803. if ( parameters !== undefined ) {
  15804. this.setValues( parameters );
  15805. }
  15806. }
  15807. copy( source ) {
  15808. super.copy( source );
  15809. this.fragmentShader = source.fragmentShader;
  15810. this.vertexShader = source.vertexShader;
  15811. this.uniforms = cloneUniforms( source.uniforms );
  15812. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  15813. this.defines = Object.assign( {}, source.defines );
  15814. this.wireframe = source.wireframe;
  15815. this.wireframeLinewidth = source.wireframeLinewidth;
  15816. this.fog = source.fog;
  15817. this.lights = source.lights;
  15818. this.clipping = source.clipping;
  15819. this.extensions = Object.assign( {}, source.extensions );
  15820. this.glslVersion = source.glslVersion;
  15821. return this;
  15822. }
  15823. toJSON( meta ) {
  15824. const data = super.toJSON( meta );
  15825. data.glslVersion = this.glslVersion;
  15826. data.uniforms = {};
  15827. for ( const name in this.uniforms ) {
  15828. const uniform = this.uniforms[ name ];
  15829. const value = uniform.value;
  15830. if ( value && value.isTexture ) {
  15831. data.uniforms[ name ] = {
  15832. type: 't',
  15833. value: value.toJSON( meta ).uuid
  15834. };
  15835. } else if ( value && value.isColor ) {
  15836. data.uniforms[ name ] = {
  15837. type: 'c',
  15838. value: value.getHex()
  15839. };
  15840. } else if ( value && value.isVector2 ) {
  15841. data.uniforms[ name ] = {
  15842. type: 'v2',
  15843. value: value.toArray()
  15844. };
  15845. } else if ( value && value.isVector3 ) {
  15846. data.uniforms[ name ] = {
  15847. type: 'v3',
  15848. value: value.toArray()
  15849. };
  15850. } else if ( value && value.isVector4 ) {
  15851. data.uniforms[ name ] = {
  15852. type: 'v4',
  15853. value: value.toArray()
  15854. };
  15855. } else if ( value && value.isMatrix3 ) {
  15856. data.uniforms[ name ] = {
  15857. type: 'm3',
  15858. value: value.toArray()
  15859. };
  15860. } else if ( value && value.isMatrix4 ) {
  15861. data.uniforms[ name ] = {
  15862. type: 'm4',
  15863. value: value.toArray()
  15864. };
  15865. } else {
  15866. data.uniforms[ name ] = {
  15867. value: value
  15868. };
  15869. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  15870. }
  15871. }
  15872. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  15873. data.vertexShader = this.vertexShader;
  15874. data.fragmentShader = this.fragmentShader;
  15875. data.lights = this.lights;
  15876. data.clipping = this.clipping;
  15877. const extensions = {};
  15878. for ( const key in this.extensions ) {
  15879. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  15880. }
  15881. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  15882. return data;
  15883. }
  15884. }
  15885. /**
  15886. * Abstract base class for cameras. This class should always be inherited
  15887. * when you build a new camera.
  15888. *
  15889. * @abstract
  15890. * @augments Object3D
  15891. */
  15892. class Camera extends Object3D {
  15893. /**
  15894. * Constructs a new camera.
  15895. */
  15896. constructor() {
  15897. super();
  15898. /**
  15899. * This flag can be used for type testing.
  15900. *
  15901. * @type {boolean}
  15902. * @readonly
  15903. * @default true
  15904. */
  15905. this.isCamera = true;
  15906. this.type = 'Camera';
  15907. /**
  15908. * The inverse of the camera's world matrix.
  15909. *
  15910. * @type {Matrix4}
  15911. */
  15912. this.matrixWorldInverse = new Matrix4();
  15913. /**
  15914. * The camera's projection matrix.
  15915. *
  15916. * @type {Matrix4}
  15917. */
  15918. this.projectionMatrix = new Matrix4();
  15919. /**
  15920. * The inverse of the camera's projection matrix.
  15921. *
  15922. * @type {Matrix4}
  15923. */
  15924. this.projectionMatrixInverse = new Matrix4();
  15925. /**
  15926. * The coordinate system in which the camera is used.
  15927. *
  15928. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  15929. */
  15930. this.coordinateSystem = WebGLCoordinateSystem;
  15931. this._reversedDepth = false;
  15932. }
  15933. /**
  15934. * The flag that indicates whether the camera uses a reversed depth buffer.
  15935. *
  15936. * @type {boolean}
  15937. * @default false
  15938. */
  15939. get reversedDepth() {
  15940. return this._reversedDepth;
  15941. }
  15942. copy( source, recursive ) {
  15943. super.copy( source, recursive );
  15944. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  15945. this.projectionMatrix.copy( source.projectionMatrix );
  15946. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  15947. this.coordinateSystem = source.coordinateSystem;
  15948. return this;
  15949. }
  15950. /**
  15951. * Returns a vector representing the ("look") direction of the 3D object in world space.
  15952. *
  15953. * This method is overwritten since cameras have a different forward vector compared to other
  15954. * 3D objects. A camera looks down its local, negative z-axis by default.
  15955. *
  15956. * @param {Vector3} target - The target vector the result is stored to.
  15957. * @return {Vector3} The 3D object's direction in world space.
  15958. */
  15959. getWorldDirection( target ) {
  15960. return super.getWorldDirection( target ).negate();
  15961. }
  15962. updateMatrixWorld( force ) {
  15963. super.updateMatrixWorld( force );
  15964. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  15965. }
  15966. updateWorldMatrix( updateParents, updateChildren ) {
  15967. super.updateWorldMatrix( updateParents, updateChildren );
  15968. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  15969. }
  15970. clone() {
  15971. return new this.constructor().copy( this );
  15972. }
  15973. }
  15974. const _v3$1 = /*@__PURE__*/ new Vector3();
  15975. const _minTarget = /*@__PURE__*/ new Vector2();
  15976. const _maxTarget = /*@__PURE__*/ new Vector2();
  15977. /**
  15978. * Camera that uses [perspective projection]{@link https://en.wikipedia.org/wiki/Perspective_(graphical)}.
  15979. *
  15980. * This projection mode is designed to mimic the way the human eye sees. It
  15981. * is the most common projection mode used for rendering a 3D scene.
  15982. *
  15983. * ```js
  15984. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  15985. * scene.add( camera );
  15986. * ```
  15987. *
  15988. * @augments Camera
  15989. */
  15990. class PerspectiveCamera extends Camera {
  15991. /**
  15992. * Constructs a new perspective camera.
  15993. *
  15994. * @param {number} [fov=50] - The vertical field of view.
  15995. * @param {number} [aspect=1] - The aspect ratio.
  15996. * @param {number} [near=0.1] - The camera's near plane.
  15997. * @param {number} [far=2000] - The camera's far plane.
  15998. */
  15999. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  16000. super();
  16001. /**
  16002. * This flag can be used for type testing.
  16003. *
  16004. * @type {boolean}
  16005. * @readonly
  16006. * @default true
  16007. */
  16008. this.isPerspectiveCamera = true;
  16009. this.type = 'PerspectiveCamera';
  16010. /**
  16011. * The vertical field of view, from bottom to top of view,
  16012. * in degrees.
  16013. *
  16014. * @type {number}
  16015. * @default 50
  16016. */
  16017. this.fov = fov;
  16018. /**
  16019. * The zoom factor of the camera.
  16020. *
  16021. * @type {number}
  16022. * @default 1
  16023. */
  16024. this.zoom = 1;
  16025. /**
  16026. * The camera's near plane. The valid range is greater than `0`
  16027. * and less than the current value of {@link PerspectiveCamera#far}.
  16028. *
  16029. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  16030. * valid value for a perspective camera's near plane.
  16031. *
  16032. * @type {number}
  16033. * @default 0.1
  16034. */
  16035. this.near = near;
  16036. /**
  16037. * The camera's far plane. Must be greater than the
  16038. * current value of {@link PerspectiveCamera#near}.
  16039. *
  16040. * @type {number}
  16041. * @default 2000
  16042. */
  16043. this.far = far;
  16044. /**
  16045. * Object distance used for stereoscopy and depth-of-field effects. This
  16046. * parameter does not influence the projection matrix unless a
  16047. * {@link StereoCamera} is being used.
  16048. *
  16049. * @type {number}
  16050. * @default 10
  16051. */
  16052. this.focus = 10;
  16053. /**
  16054. * The aspect ratio, usually the canvas width / canvas height.
  16055. *
  16056. * @type {number}
  16057. * @default 1
  16058. */
  16059. this.aspect = aspect;
  16060. /**
  16061. * Represents the frustum window specification. This property should not be edited
  16062. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  16063. *
  16064. * @type {?Object}
  16065. * @default null
  16066. */
  16067. this.view = null;
  16068. /**
  16069. * Film size used for the larger axis. Default is `35` (millimeters). This
  16070. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  16071. * is set to a nonzero value.
  16072. *
  16073. * @type {number}
  16074. * @default 35
  16075. */
  16076. this.filmGauge = 35;
  16077. /**
  16078. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  16079. *
  16080. * @type {number}
  16081. * @default 0
  16082. */
  16083. this.filmOffset = 0;
  16084. this.updateProjectionMatrix();
  16085. }
  16086. copy( source, recursive ) {
  16087. super.copy( source, recursive );
  16088. this.fov = source.fov;
  16089. this.zoom = source.zoom;
  16090. this.near = source.near;
  16091. this.far = source.far;
  16092. this.focus = source.focus;
  16093. this.aspect = source.aspect;
  16094. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16095. this.filmGauge = source.filmGauge;
  16096. this.filmOffset = source.filmOffset;
  16097. return this;
  16098. }
  16099. /**
  16100. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  16101. *
  16102. * The default film gauge is 35, so that the focal length can be specified for
  16103. * a 35mm (full frame) camera.
  16104. *
  16105. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  16106. */
  16107. setFocalLength( focalLength ) {
  16108. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  16109. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  16110. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  16111. this.updateProjectionMatrix();
  16112. }
  16113. /**
  16114. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  16115. * {@link PerspectiveCamera#filmGauge}.
  16116. *
  16117. * @return {number} The computed focal length.
  16118. */
  16119. getFocalLength() {
  16120. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  16121. return 0.5 * this.getFilmHeight() / vExtentSlope;
  16122. }
  16123. /**
  16124. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  16125. *
  16126. * @return {number} The effective FOV.
  16127. */
  16128. getEffectiveFOV() {
  16129. return RAD2DEG * 2 * Math.atan(
  16130. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  16131. }
  16132. /**
  16133. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16134. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16135. *
  16136. * @return {number} The film width.
  16137. */
  16138. getFilmWidth() {
  16139. // film not completely covered in portrait format (aspect < 1)
  16140. return this.filmGauge * Math.min( this.aspect, 1 );
  16141. }
  16142. /**
  16143. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16144. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16145. *
  16146. * @return {number} The film width.
  16147. */
  16148. getFilmHeight() {
  16149. // film not completely covered in landscape format (aspect > 1)
  16150. return this.filmGauge / Math.max( this.aspect, 1 );
  16151. }
  16152. /**
  16153. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  16154. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  16155. *
  16156. * @param {number} distance - The viewing distance.
  16157. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  16158. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  16159. */
  16160. getViewBounds( distance, minTarget, maxTarget ) {
  16161. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16162. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16163. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16164. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16165. }
  16166. /**
  16167. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  16168. *
  16169. * @param {number} distance - The viewing distance.
  16170. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  16171. * @returns {Vector2} The view size.
  16172. */
  16173. getViewSize( distance, target ) {
  16174. this.getViewBounds( distance, _minTarget, _maxTarget );
  16175. return target.subVectors( _maxTarget, _minTarget );
  16176. }
  16177. /**
  16178. * Sets an offset in a larger frustum. This is useful for multi-window or
  16179. * multi-monitor/multi-machine setups.
  16180. *
  16181. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  16182. * the monitors are in grid like this
  16183. *```
  16184. * +---+---+---+
  16185. * | A | B | C |
  16186. * +---+---+---+
  16187. * | D | E | F |
  16188. * +---+---+---+
  16189. *```
  16190. * then for each monitor you would call it like this:
  16191. *```js
  16192. * const w = 1920;
  16193. * const h = 1080;
  16194. * const fullWidth = w * 3;
  16195. * const fullHeight = h * 2;
  16196. *
  16197. * // --A--
  16198. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  16199. * // --B--
  16200. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  16201. * // --C--
  16202. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  16203. * // --D--
  16204. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  16205. * // --E--
  16206. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  16207. * // --F--
  16208. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  16209. * ```
  16210. *
  16211. * Note there is no reason monitors have to be the same size or in a grid.
  16212. *
  16213. * @param {number} fullWidth - The full width of multiview setup.
  16214. * @param {number} fullHeight - The full height of multiview setup.
  16215. * @param {number} x - The horizontal offset of the subcamera.
  16216. * @param {number} y - The vertical offset of the subcamera.
  16217. * @param {number} width - The width of subcamera.
  16218. * @param {number} height - The height of subcamera.
  16219. */
  16220. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16221. this.aspect = fullWidth / fullHeight;
  16222. if ( this.view === null ) {
  16223. this.view = {
  16224. enabled: true,
  16225. fullWidth: 1,
  16226. fullHeight: 1,
  16227. offsetX: 0,
  16228. offsetY: 0,
  16229. width: 1,
  16230. height: 1
  16231. };
  16232. }
  16233. this.view.enabled = true;
  16234. this.view.fullWidth = fullWidth;
  16235. this.view.fullHeight = fullHeight;
  16236. this.view.offsetX = x;
  16237. this.view.offsetY = y;
  16238. this.view.width = width;
  16239. this.view.height = height;
  16240. this.updateProjectionMatrix();
  16241. }
  16242. /**
  16243. * Removes the view offset from the projection matrix.
  16244. */
  16245. clearViewOffset() {
  16246. if ( this.view !== null ) {
  16247. this.view.enabled = false;
  16248. }
  16249. this.updateProjectionMatrix();
  16250. }
  16251. /**
  16252. * Updates the camera's projection matrix. Must be called after any change of
  16253. * camera properties.
  16254. */
  16255. updateProjectionMatrix() {
  16256. const near = this.near;
  16257. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  16258. let height = 2 * top;
  16259. let width = this.aspect * height;
  16260. let left = -0.5 * width;
  16261. const view = this.view;
  16262. if ( this.view !== null && this.view.enabled ) {
  16263. const fullWidth = view.fullWidth,
  16264. fullHeight = view.fullHeight;
  16265. left += view.offsetX * width / fullWidth;
  16266. top -= view.offsetY * height / fullHeight;
  16267. width *= view.width / fullWidth;
  16268. height *= view.height / fullHeight;
  16269. }
  16270. const skew = this.filmOffset;
  16271. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16272. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth );
  16273. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16274. }
  16275. toJSON( meta ) {
  16276. const data = super.toJSON( meta );
  16277. data.object.fov = this.fov;
  16278. data.object.zoom = this.zoom;
  16279. data.object.near = this.near;
  16280. data.object.far = this.far;
  16281. data.object.focus = this.focus;
  16282. data.object.aspect = this.aspect;
  16283. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16284. data.object.filmGauge = this.filmGauge;
  16285. data.object.filmOffset = this.filmOffset;
  16286. return data;
  16287. }
  16288. }
  16289. const fov = -90; // negative fov is not an error
  16290. const aspect = 1;
  16291. /**
  16292. * A special type of camera that is positioned in 3D space to render its surroundings into a
  16293. * cube render target. The render target can then be used as an environment map for rendering
  16294. * realtime reflections in your scene.
  16295. *
  16296. * ```js
  16297. * // Create cube render target
  16298. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  16299. *
  16300. * // Create cube camera
  16301. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  16302. * scene.add( cubeCamera );
  16303. *
  16304. * // Create car
  16305. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  16306. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  16307. * scene.add( car );
  16308. *
  16309. * // Update the render target cube
  16310. * car.visible = false;
  16311. * cubeCamera.position.copy( car.position );
  16312. * cubeCamera.update( renderer, scene );
  16313. *
  16314. * // Render the scene
  16315. * car.visible = true;
  16316. * renderer.render( scene, camera );
  16317. * ```
  16318. *
  16319. * @augments Object3D
  16320. */
  16321. class CubeCamera extends Object3D {
  16322. /**
  16323. * Constructs a new cube camera.
  16324. *
  16325. * @param {number} near - The camera's near plane.
  16326. * @param {number} far - The camera's far plane.
  16327. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  16328. */
  16329. constructor( near, far, renderTarget ) {
  16330. super();
  16331. this.type = 'CubeCamera';
  16332. /**
  16333. * A reference to the cube render target.
  16334. *
  16335. * @type {WebGLCubeRenderTarget}
  16336. */
  16337. this.renderTarget = renderTarget;
  16338. /**
  16339. * The current active coordinate system.
  16340. *
  16341. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16342. * @default null
  16343. */
  16344. this.coordinateSystem = null;
  16345. /**
  16346. * The current active mipmap level
  16347. *
  16348. * @type {number}
  16349. * @default 0
  16350. */
  16351. this.activeMipmapLevel = 0;
  16352. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  16353. cameraPX.layers = this.layers;
  16354. this.add( cameraPX );
  16355. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  16356. cameraNX.layers = this.layers;
  16357. this.add( cameraNX );
  16358. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  16359. cameraPY.layers = this.layers;
  16360. this.add( cameraPY );
  16361. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  16362. cameraNY.layers = this.layers;
  16363. this.add( cameraNY );
  16364. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  16365. cameraPZ.layers = this.layers;
  16366. this.add( cameraPZ );
  16367. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  16368. cameraNZ.layers = this.layers;
  16369. this.add( cameraNZ );
  16370. }
  16371. /**
  16372. * Must be called when the coordinate system of the cube camera is changed.
  16373. */
  16374. updateCoordinateSystem() {
  16375. const coordinateSystem = this.coordinateSystem;
  16376. const cameras = this.children.concat();
  16377. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  16378. for ( const camera of cameras ) this.remove( camera );
  16379. if ( coordinateSystem === WebGLCoordinateSystem ) {
  16380. cameraPX.up.set( 0, 1, 0 );
  16381. cameraPX.lookAt( 1, 0, 0 );
  16382. cameraNX.up.set( 0, 1, 0 );
  16383. cameraNX.lookAt( -1, 0, 0 );
  16384. cameraPY.up.set( 0, 0, -1 );
  16385. cameraPY.lookAt( 0, 1, 0 );
  16386. cameraNY.up.set( 0, 0, 1 );
  16387. cameraNY.lookAt( 0, -1, 0 );
  16388. cameraPZ.up.set( 0, 1, 0 );
  16389. cameraPZ.lookAt( 0, 0, 1 );
  16390. cameraNZ.up.set( 0, 1, 0 );
  16391. cameraNZ.lookAt( 0, 0, -1 );
  16392. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  16393. cameraPX.up.set( 0, -1, 0 );
  16394. cameraPX.lookAt( -1, 0, 0 );
  16395. cameraNX.up.set( 0, -1, 0 );
  16396. cameraNX.lookAt( 1, 0, 0 );
  16397. cameraPY.up.set( 0, 0, 1 );
  16398. cameraPY.lookAt( 0, 1, 0 );
  16399. cameraNY.up.set( 0, 0, -1 );
  16400. cameraNY.lookAt( 0, -1, 0 );
  16401. cameraPZ.up.set( 0, -1, 0 );
  16402. cameraPZ.lookAt( 0, 0, 1 );
  16403. cameraNZ.up.set( 0, -1, 0 );
  16404. cameraNZ.lookAt( 0, 0, -1 );
  16405. } else {
  16406. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  16407. }
  16408. for ( const camera of cameras ) {
  16409. this.add( camera );
  16410. camera.updateMatrixWorld();
  16411. }
  16412. }
  16413. /**
  16414. * Calling this method will render the given scene with the given renderer
  16415. * into the cube render target of the camera.
  16416. *
  16417. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  16418. * @param {Scene} scene - The scene to render.
  16419. */
  16420. update( renderer, scene ) {
  16421. if ( this.parent === null ) this.updateMatrixWorld();
  16422. const { renderTarget, activeMipmapLevel } = this;
  16423. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  16424. this.coordinateSystem = renderer.coordinateSystem;
  16425. this.updateCoordinateSystem();
  16426. }
  16427. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  16428. const currentRenderTarget = renderer.getRenderTarget();
  16429. const currentActiveCubeFace = renderer.getActiveCubeFace();
  16430. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  16431. const currentXrEnabled = renderer.xr.enabled;
  16432. renderer.xr.enabled = false;
  16433. const generateMipmaps = renderTarget.texture.generateMipmaps;
  16434. renderTarget.texture.generateMipmaps = false;
  16435. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  16436. renderer.render( scene, cameraPX );
  16437. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  16438. renderer.render( scene, cameraNX );
  16439. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  16440. renderer.render( scene, cameraPY );
  16441. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  16442. renderer.render( scene, cameraNY );
  16443. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  16444. renderer.render( scene, cameraPZ );
  16445. // mipmaps are generated during the last call of render()
  16446. // at this point, all sides of the cube render target are defined
  16447. renderTarget.texture.generateMipmaps = generateMipmaps;
  16448. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  16449. renderer.render( scene, cameraNZ );
  16450. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  16451. renderer.xr.enabled = currentXrEnabled;
  16452. renderTarget.texture.needsPMREMUpdate = true;
  16453. }
  16454. }
  16455. /**
  16456. * Creates a cube texture made up of six images.
  16457. *
  16458. * ```js
  16459. * const loader = new THREE.CubeTextureLoader();
  16460. * loader.setPath( 'textures/cube/pisa/' );
  16461. *
  16462. * const textureCube = loader.load( [
  16463. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  16464. * ] );
  16465. *
  16466. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  16467. * ```
  16468. *
  16469. * @augments Texture
  16470. */
  16471. class CubeTexture extends Texture {
  16472. /**
  16473. * Constructs a new cube texture.
  16474. *
  16475. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  16476. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  16477. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  16478. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  16479. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  16480. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  16481. * @param {number} [format=RGBAFormat] - The texture format.
  16482. * @param {number} [type=UnsignedByteType] - The texture type.
  16483. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  16484. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  16485. */
  16486. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  16487. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  16488. /**
  16489. * This flag can be used for type testing.
  16490. *
  16491. * @type {boolean}
  16492. * @readonly
  16493. * @default true
  16494. */
  16495. this.isCubeTexture = true;
  16496. /**
  16497. * If set to `true`, the texture is flipped along the vertical axis when
  16498. * uploaded to the GPU.
  16499. *
  16500. * Overwritten and set to `false` by default.
  16501. *
  16502. * @type {boolean}
  16503. * @default false
  16504. */
  16505. this.flipY = false;
  16506. }
  16507. /**
  16508. * Alias for {@link CubeTexture#image}.
  16509. *
  16510. * @type {Array<Image>}
  16511. */
  16512. get images() {
  16513. return this.image;
  16514. }
  16515. set images( value ) {
  16516. this.image = value;
  16517. }
  16518. }
  16519. /**
  16520. * A cube render target used in context of {@link WebGLRenderer}.
  16521. *
  16522. * @augments WebGLRenderTarget
  16523. */
  16524. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  16525. /**
  16526. * Constructs a new cube render target.
  16527. *
  16528. * @param {number} [size=1] - The size of the render target.
  16529. * @param {RenderTarget~Options} [options] - The configuration object.
  16530. */
  16531. constructor( size = 1, options = {} ) {
  16532. super( size, size, options );
  16533. /**
  16534. * This flag can be used for type testing.
  16535. *
  16536. * @type {boolean}
  16537. * @readonly
  16538. * @default true
  16539. */
  16540. this.isWebGLCubeRenderTarget = true;
  16541. const image = { width: size, height: size, depth: 1 };
  16542. const images = [ image, image, image, image, image, image ];
  16543. /**
  16544. * Overwritten with a different texture type.
  16545. *
  16546. * @type {DataArrayTexture}
  16547. */
  16548. this.texture = new CubeTexture( images );
  16549. this._setTextureOptions( options );
  16550. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16551. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16552. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16553. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16554. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16555. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16556. this.texture.isRenderTargetTexture = true;
  16557. }
  16558. /**
  16559. * Converts the given equirectangular texture to a cube map.
  16560. *
  16561. * @param {WebGLRenderer} renderer - The renderer.
  16562. * @param {Texture} texture - The equirectangular texture.
  16563. * @return {WebGLCubeRenderTarget} A reference to this cube render target.
  16564. */
  16565. fromEquirectangularTexture( renderer, texture ) {
  16566. this.texture.type = texture.type;
  16567. this.texture.colorSpace = texture.colorSpace;
  16568. this.texture.generateMipmaps = texture.generateMipmaps;
  16569. this.texture.minFilter = texture.minFilter;
  16570. this.texture.magFilter = texture.magFilter;
  16571. const shader = {
  16572. uniforms: {
  16573. tEquirect: { value: null },
  16574. },
  16575. vertexShader: /* glsl */`
  16576. varying vec3 vWorldDirection;
  16577. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  16578. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  16579. }
  16580. void main() {
  16581. vWorldDirection = transformDirection( position, modelMatrix );
  16582. #include <begin_vertex>
  16583. #include <project_vertex>
  16584. }
  16585. `,
  16586. fragmentShader: /* glsl */`
  16587. uniform sampler2D tEquirect;
  16588. varying vec3 vWorldDirection;
  16589. #include <common>
  16590. void main() {
  16591. vec3 direction = normalize( vWorldDirection );
  16592. vec2 sampleUV = equirectUv( direction );
  16593. gl_FragColor = texture2D( tEquirect, sampleUV );
  16594. }
  16595. `
  16596. };
  16597. const geometry = new BoxGeometry( 5, 5, 5 );
  16598. const material = new ShaderMaterial( {
  16599. name: 'CubemapFromEquirect',
  16600. uniforms: cloneUniforms( shader.uniforms ),
  16601. vertexShader: shader.vertexShader,
  16602. fragmentShader: shader.fragmentShader,
  16603. side: BackSide,
  16604. blending: NoBlending
  16605. } );
  16606. material.uniforms.tEquirect.value = texture;
  16607. const mesh = new Mesh( geometry, material );
  16608. const currentMinFilter = texture.minFilter;
  16609. // Avoid blurred poles
  16610. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  16611. const camera = new CubeCamera( 1, 10, this );
  16612. camera.update( renderer, mesh );
  16613. texture.minFilter = currentMinFilter;
  16614. mesh.geometry.dispose();
  16615. mesh.material.dispose();
  16616. return this;
  16617. }
  16618. /**
  16619. * Clears this cube render target.
  16620. *
  16621. * @param {WebGLRenderer} renderer - The renderer.
  16622. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16623. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16624. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16625. */
  16626. clear( renderer, color = true, depth = true, stencil = true ) {
  16627. const currentRenderTarget = renderer.getRenderTarget();
  16628. for ( let i = 0; i < 6; i ++ ) {
  16629. renderer.setRenderTarget( this, i );
  16630. renderer.clear( color, depth, stencil );
  16631. }
  16632. renderer.setRenderTarget( currentRenderTarget );
  16633. }
  16634. }
  16635. /**
  16636. * This is almost identical to an {@link Object3D}. Its purpose is to
  16637. * make working with groups of objects syntactically clearer.
  16638. *
  16639. * ```js
  16640. * // Create a group and add the two cubes.
  16641. * // These cubes can now be rotated / scaled etc as a group.
  16642. * const group = new THREE.Group();
  16643. *
  16644. * group.add( meshA );
  16645. * group.add( meshB );
  16646. *
  16647. * scene.add( group );
  16648. * ```
  16649. *
  16650. * @augments Object3D
  16651. */
  16652. class Group extends Object3D {
  16653. constructor() {
  16654. super();
  16655. /**
  16656. * This flag can be used for type testing.
  16657. *
  16658. * @type {boolean}
  16659. * @readonly
  16660. * @default true
  16661. */
  16662. this.isGroup = true;
  16663. this.type = 'Group';
  16664. }
  16665. }
  16666. const _moveEvent = { type: 'move' };
  16667. /**
  16668. * Class for representing a XR controller with its
  16669. * different coordinate systems.
  16670. *
  16671. * @private
  16672. */
  16673. class WebXRController {
  16674. /**
  16675. * Constructs a new XR controller.
  16676. */
  16677. constructor() {
  16678. /**
  16679. * A group representing the target ray space
  16680. * of the XR controller.
  16681. *
  16682. * @private
  16683. * @type {?Group}
  16684. * @default null
  16685. */
  16686. this._targetRay = null;
  16687. /**
  16688. * A group representing the grip space
  16689. * of the XR controller.
  16690. *
  16691. * @private
  16692. * @type {?Group}
  16693. * @default null
  16694. */
  16695. this._grip = null;
  16696. /**
  16697. * A group representing the hand space
  16698. * of the XR controller.
  16699. *
  16700. * @private
  16701. * @type {?Group}
  16702. * @default null
  16703. */
  16704. this._hand = null;
  16705. }
  16706. /**
  16707. * Returns a group representing the hand space of the XR controller.
  16708. *
  16709. * @return {Group} A group representing the hand space of the XR controller.
  16710. */
  16711. getHandSpace() {
  16712. if ( this._hand === null ) {
  16713. this._hand = new Group();
  16714. this._hand.matrixAutoUpdate = false;
  16715. this._hand.visible = false;
  16716. this._hand.joints = {};
  16717. this._hand.inputState = { pinching: false };
  16718. }
  16719. return this._hand;
  16720. }
  16721. /**
  16722. * Returns a group representing the target ray space of the XR controller.
  16723. *
  16724. * @return {Group} A group representing the target ray space of the XR controller.
  16725. */
  16726. getTargetRaySpace() {
  16727. if ( this._targetRay === null ) {
  16728. this._targetRay = new Group();
  16729. this._targetRay.matrixAutoUpdate = false;
  16730. this._targetRay.visible = false;
  16731. this._targetRay.hasLinearVelocity = false;
  16732. this._targetRay.linearVelocity = new Vector3();
  16733. this._targetRay.hasAngularVelocity = false;
  16734. this._targetRay.angularVelocity = new Vector3();
  16735. }
  16736. return this._targetRay;
  16737. }
  16738. /**
  16739. * Returns a group representing the grip space of the XR controller.
  16740. *
  16741. * @return {Group} A group representing the grip space of the XR controller.
  16742. */
  16743. getGripSpace() {
  16744. if ( this._grip === null ) {
  16745. this._grip = new Group();
  16746. this._grip.matrixAutoUpdate = false;
  16747. this._grip.visible = false;
  16748. this._grip.hasLinearVelocity = false;
  16749. this._grip.linearVelocity = new Vector3();
  16750. this._grip.hasAngularVelocity = false;
  16751. this._grip.angularVelocity = new Vector3();
  16752. }
  16753. return this._grip;
  16754. }
  16755. /**
  16756. * Dispatches the given event to the groups representing
  16757. * the different coordinate spaces of the XR controller.
  16758. *
  16759. * @param {Object} event - The event to dispatch.
  16760. * @return {WebXRController} A reference to this instance.
  16761. */
  16762. dispatchEvent( event ) {
  16763. if ( this._targetRay !== null ) {
  16764. this._targetRay.dispatchEvent( event );
  16765. }
  16766. if ( this._grip !== null ) {
  16767. this._grip.dispatchEvent( event );
  16768. }
  16769. if ( this._hand !== null ) {
  16770. this._hand.dispatchEvent( event );
  16771. }
  16772. return this;
  16773. }
  16774. /**
  16775. * Connects the controller with the given XR input source.
  16776. *
  16777. * @param {XRInputSource} inputSource - The input source.
  16778. * @return {WebXRController} A reference to this instance.
  16779. */
  16780. connect( inputSource ) {
  16781. if ( inputSource && inputSource.hand ) {
  16782. const hand = this._hand;
  16783. if ( hand ) {
  16784. for ( const inputjoint of inputSource.hand.values() ) {
  16785. // Initialize hand with joints when connected
  16786. this._getHandJoint( hand, inputjoint );
  16787. }
  16788. }
  16789. }
  16790. this.dispatchEvent( { type: 'connected', data: inputSource } );
  16791. return this;
  16792. }
  16793. /**
  16794. * Disconnects the controller from the given XR input source.
  16795. *
  16796. * @param {XRInputSource} inputSource - The input source.
  16797. * @return {WebXRController} A reference to this instance.
  16798. */
  16799. disconnect( inputSource ) {
  16800. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  16801. if ( this._targetRay !== null ) {
  16802. this._targetRay.visible = false;
  16803. }
  16804. if ( this._grip !== null ) {
  16805. this._grip.visible = false;
  16806. }
  16807. if ( this._hand !== null ) {
  16808. this._hand.visible = false;
  16809. }
  16810. return this;
  16811. }
  16812. /**
  16813. * Updates the controller with the given input source, XR frame and reference space.
  16814. * This updates the transformations of the groups that represent the different
  16815. * coordinate systems of the controller.
  16816. *
  16817. * @param {XRInputSource} inputSource - The input source.
  16818. * @param {XRFrame} frame - The XR frame.
  16819. * @param {XRReferenceSpace} referenceSpace - The reference space.
  16820. * @return {WebXRController} A reference to this instance.
  16821. */
  16822. update( inputSource, frame, referenceSpace ) {
  16823. let inputPose = null;
  16824. let gripPose = null;
  16825. let handPose = null;
  16826. const targetRay = this._targetRay;
  16827. const grip = this._grip;
  16828. const hand = this._hand;
  16829. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  16830. if ( hand && inputSource.hand ) {
  16831. handPose = true;
  16832. for ( const inputjoint of inputSource.hand.values() ) {
  16833. // Update the joints groups with the XRJoint poses
  16834. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  16835. // The transform of this joint will be updated with the joint pose on each frame
  16836. const joint = this._getHandJoint( hand, inputjoint );
  16837. if ( jointPose !== null ) {
  16838. joint.matrix.fromArray( jointPose.transform.matrix );
  16839. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  16840. joint.matrixWorldNeedsUpdate = true;
  16841. joint.jointRadius = jointPose.radius;
  16842. }
  16843. joint.visible = jointPose !== null;
  16844. }
  16845. // Custom events
  16846. // Check pinchz
  16847. const indexTip = hand.joints[ 'index-finger-tip' ];
  16848. const thumbTip = hand.joints[ 'thumb-tip' ];
  16849. const distance = indexTip.position.distanceTo( thumbTip.position );
  16850. const distanceToPinch = 0.02;
  16851. const threshold = 0.005;
  16852. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  16853. hand.inputState.pinching = false;
  16854. this.dispatchEvent( {
  16855. type: 'pinchend',
  16856. handedness: inputSource.handedness,
  16857. target: this
  16858. } );
  16859. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  16860. hand.inputState.pinching = true;
  16861. this.dispatchEvent( {
  16862. type: 'pinchstart',
  16863. handedness: inputSource.handedness,
  16864. target: this
  16865. } );
  16866. }
  16867. } else {
  16868. if ( grip !== null && inputSource.gripSpace ) {
  16869. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  16870. if ( gripPose !== null ) {
  16871. grip.matrix.fromArray( gripPose.transform.matrix );
  16872. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  16873. grip.matrixWorldNeedsUpdate = true;
  16874. if ( gripPose.linearVelocity ) {
  16875. grip.hasLinearVelocity = true;
  16876. grip.linearVelocity.copy( gripPose.linearVelocity );
  16877. } else {
  16878. grip.hasLinearVelocity = false;
  16879. }
  16880. if ( gripPose.angularVelocity ) {
  16881. grip.hasAngularVelocity = true;
  16882. grip.angularVelocity.copy( gripPose.angularVelocity );
  16883. } else {
  16884. grip.hasAngularVelocity = false;
  16885. }
  16886. }
  16887. }
  16888. }
  16889. if ( targetRay !== null ) {
  16890. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  16891. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  16892. if ( inputPose === null && gripPose !== null ) {
  16893. inputPose = gripPose;
  16894. }
  16895. if ( inputPose !== null ) {
  16896. targetRay.matrix.fromArray( inputPose.transform.matrix );
  16897. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  16898. targetRay.matrixWorldNeedsUpdate = true;
  16899. if ( inputPose.linearVelocity ) {
  16900. targetRay.hasLinearVelocity = true;
  16901. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  16902. } else {
  16903. targetRay.hasLinearVelocity = false;
  16904. }
  16905. if ( inputPose.angularVelocity ) {
  16906. targetRay.hasAngularVelocity = true;
  16907. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  16908. } else {
  16909. targetRay.hasAngularVelocity = false;
  16910. }
  16911. this.dispatchEvent( _moveEvent );
  16912. }
  16913. }
  16914. }
  16915. if ( targetRay !== null ) {
  16916. targetRay.visible = ( inputPose !== null );
  16917. }
  16918. if ( grip !== null ) {
  16919. grip.visible = ( gripPose !== null );
  16920. }
  16921. if ( hand !== null ) {
  16922. hand.visible = ( handPose !== null );
  16923. }
  16924. return this;
  16925. }
  16926. /**
  16927. * Returns a group representing the hand joint for the given input joint.
  16928. *
  16929. * @private
  16930. * @param {Group} hand - The group representing the hand space.
  16931. * @param {XRJointSpace} inputjoint - The hand joint data.
  16932. * @return {Group} A group representing the hand joint for the given input joint.
  16933. */
  16934. _getHandJoint( hand, inputjoint ) {
  16935. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  16936. const joint = new Group();
  16937. joint.matrixAutoUpdate = false;
  16938. joint.visible = false;
  16939. hand.joints[ inputjoint.jointName ] = joint;
  16940. hand.add( joint );
  16941. }
  16942. return hand.joints[ inputjoint.jointName ];
  16943. }
  16944. }
  16945. /**
  16946. * This class can be used to define an exponential squared fog,
  16947. * which gives a clear view near the camera and a faster than exponentially
  16948. * densening fog farther from the camera.
  16949. *
  16950. * ```js
  16951. * const scene = new THREE.Scene();
  16952. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  16953. * ```
  16954. */
  16955. class FogExp2 {
  16956. /**
  16957. * Constructs a new fog.
  16958. *
  16959. * @param {number|Color} color - The fog's color.
  16960. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  16961. */
  16962. constructor( color, density = 0.00025 ) {
  16963. /**
  16964. * This flag can be used for type testing.
  16965. *
  16966. * @type {boolean}
  16967. * @readonly
  16968. * @default true
  16969. */
  16970. this.isFogExp2 = true;
  16971. /**
  16972. * The name of the fog.
  16973. *
  16974. * @type {string}
  16975. */
  16976. this.name = '';
  16977. /**
  16978. * The fog's color.
  16979. *
  16980. * @type {Color}
  16981. */
  16982. this.color = new Color( color );
  16983. /**
  16984. * Defines how fast the fog will grow dense.
  16985. *
  16986. * @type {number}
  16987. * @default 0.00025
  16988. */
  16989. this.density = density;
  16990. }
  16991. /**
  16992. * Returns a new fog with copied values from this instance.
  16993. *
  16994. * @return {FogExp2} A clone of this instance.
  16995. */
  16996. clone() {
  16997. return new FogExp2( this.color, this.density );
  16998. }
  16999. /**
  17000. * Serializes the fog into JSON.
  17001. *
  17002. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17003. * @return {Object} A JSON object representing the serialized fog
  17004. */
  17005. toJSON( /* meta */ ) {
  17006. return {
  17007. type: 'FogExp2',
  17008. name: this.name,
  17009. color: this.color.getHex(),
  17010. density: this.density
  17011. };
  17012. }
  17013. }
  17014. /**
  17015. * This class can be used to define a linear fog that grows linearly denser
  17016. * with the distance.
  17017. *
  17018. * ```js
  17019. * const scene = new THREE.Scene();
  17020. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  17021. * ```
  17022. */
  17023. class Fog {
  17024. /**
  17025. * Constructs a new fog.
  17026. *
  17027. * @param {number|Color} color - The fog's color.
  17028. * @param {number} [near=1] - The minimum distance to start applying fog.
  17029. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  17030. */
  17031. constructor( color, near = 1, far = 1000 ) {
  17032. /**
  17033. * This flag can be used for type testing.
  17034. *
  17035. * @type {boolean}
  17036. * @readonly
  17037. * @default true
  17038. */
  17039. this.isFog = true;
  17040. /**
  17041. * The name of the fog.
  17042. *
  17043. * @type {string}
  17044. */
  17045. this.name = '';
  17046. /**
  17047. * The fog's color.
  17048. *
  17049. * @type {Color}
  17050. */
  17051. this.color = new Color( color );
  17052. /**
  17053. * The minimum distance to start applying fog. Objects that are less than
  17054. * `near` units from the active camera won't be affected by fog.
  17055. *
  17056. * @type {number}
  17057. * @default 1
  17058. */
  17059. this.near = near;
  17060. /**
  17061. * The maximum distance at which fog stops being calculated and applied.
  17062. * Objects that are more than `far` units away from the active camera won't
  17063. * be affected by fog.
  17064. *
  17065. * @type {number}
  17066. * @default 1000
  17067. */
  17068. this.far = far;
  17069. }
  17070. /**
  17071. * Returns a new fog with copied values from this instance.
  17072. *
  17073. * @return {Fog} A clone of this instance.
  17074. */
  17075. clone() {
  17076. return new Fog( this.color, this.near, this.far );
  17077. }
  17078. /**
  17079. * Serializes the fog into JSON.
  17080. *
  17081. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17082. * @return {Object} A JSON object representing the serialized fog
  17083. */
  17084. toJSON( /* meta */ ) {
  17085. return {
  17086. type: 'Fog',
  17087. name: this.name,
  17088. color: this.color.getHex(),
  17089. near: this.near,
  17090. far: this.far
  17091. };
  17092. }
  17093. }
  17094. /**
  17095. * Scenes allow you to set up what is to be rendered and where by three.js.
  17096. * This is where you place 3D objects like meshes, lines or lights.
  17097. *
  17098. * @augments Object3D
  17099. */
  17100. class Scene extends Object3D {
  17101. /**
  17102. * Constructs a new scene.
  17103. */
  17104. constructor() {
  17105. super();
  17106. /**
  17107. * This flag can be used for type testing.
  17108. *
  17109. * @type {boolean}
  17110. * @readonly
  17111. * @default true
  17112. */
  17113. this.isScene = true;
  17114. this.type = 'Scene';
  17115. /**
  17116. * Defines the background of the scene. Valid inputs are:
  17117. *
  17118. * - A color for defining a uniform colored background.
  17119. * - A texture for defining a (flat) textured background.
  17120. * - Cube textures or equirectangular textures for defining a skybox.
  17121. *
  17122. * @type {?(Color|Texture)}
  17123. * @default null
  17124. */
  17125. this.background = null;
  17126. /**
  17127. * Sets the environment map for all physical materials in the scene. However,
  17128. * it's not possible to overwrite an existing texture assigned to the `envMap`
  17129. * material property.
  17130. *
  17131. * @type {?Texture}
  17132. * @default null
  17133. */
  17134. this.environment = null;
  17135. /**
  17136. * A fog instance defining the type of fog that affects everything
  17137. * rendered in the scene.
  17138. *
  17139. * @type {?(Fog|FogExp2)}
  17140. * @default null
  17141. */
  17142. this.fog = null;
  17143. /**
  17144. * Sets the blurriness of the background. Only influences environment maps
  17145. * assigned to {@link Scene#background}. Valid input is a float between `0`
  17146. * and `1`.
  17147. *
  17148. * @type {number}
  17149. * @default 0
  17150. */
  17151. this.backgroundBlurriness = 0;
  17152. /**
  17153. * Attenuates the color of the background. Only applies to background textures.
  17154. *
  17155. * @type {number}
  17156. * @default 1
  17157. */
  17158. this.backgroundIntensity = 1;
  17159. /**
  17160. * The rotation of the background in radians. Only influences environment maps
  17161. * assigned to {@link Scene#background}.
  17162. *
  17163. * @type {Euler}
  17164. * @default (0,0,0)
  17165. */
  17166. this.backgroundRotation = new Euler();
  17167. /**
  17168. * Attenuates the color of the environment. Only influences environment maps
  17169. * assigned to {@link Scene#environment}.
  17170. *
  17171. * @type {number}
  17172. * @default 1
  17173. */
  17174. this.environmentIntensity = 1;
  17175. /**
  17176. * The rotation of the environment map in radians. Only influences physical materials
  17177. * in the scene when {@link Scene#environment} is used.
  17178. *
  17179. * @type {Euler}
  17180. * @default (0,0,0)
  17181. */
  17182. this.environmentRotation = new Euler();
  17183. /**
  17184. * Forces everything in the scene to be rendered with the defined material. It is possible
  17185. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  17186. *
  17187. * @type {?Material}
  17188. * @default null
  17189. */
  17190. this.overrideMaterial = null;
  17191. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17192. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17193. }
  17194. }
  17195. copy( source, recursive ) {
  17196. super.copy( source, recursive );
  17197. if ( source.background !== null ) this.background = source.background.clone();
  17198. if ( source.environment !== null ) this.environment = source.environment.clone();
  17199. if ( source.fog !== null ) this.fog = source.fog.clone();
  17200. this.backgroundBlurriness = source.backgroundBlurriness;
  17201. this.backgroundIntensity = source.backgroundIntensity;
  17202. this.backgroundRotation.copy( source.backgroundRotation );
  17203. this.environmentIntensity = source.environmentIntensity;
  17204. this.environmentRotation.copy( source.environmentRotation );
  17205. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17206. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17207. return this;
  17208. }
  17209. toJSON( meta ) {
  17210. const data = super.toJSON( meta );
  17211. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17212. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17213. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17214. data.object.backgroundRotation = this.backgroundRotation.toArray();
  17215. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  17216. data.object.environmentRotation = this.environmentRotation.toArray();
  17217. return data;
  17218. }
  17219. }
  17220. /**
  17221. * "Interleaved" means that multiple attributes, possibly of different types,
  17222. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  17223. *
  17224. * An introduction into interleaved arrays can be found here: [Interleaved array basics]{@link https://blog.tojicode.com/2011/05/interleaved-array-basics.html}
  17225. */
  17226. class InterleavedBuffer {
  17227. /**
  17228. * Constructs a new interleaved buffer.
  17229. *
  17230. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  17231. * @param {number} stride - The number of typed-array elements per vertex.
  17232. */
  17233. constructor( array, stride ) {
  17234. /**
  17235. * This flag can be used for type testing.
  17236. *
  17237. * @type {boolean}
  17238. * @readonly
  17239. * @default true
  17240. */
  17241. this.isInterleavedBuffer = true;
  17242. /**
  17243. * A typed array with a shared buffer storing attribute data.
  17244. *
  17245. * @type {TypedArray}
  17246. */
  17247. this.array = array;
  17248. /**
  17249. * The number of typed-array elements per vertex.
  17250. *
  17251. * @type {number}
  17252. */
  17253. this.stride = stride;
  17254. /**
  17255. * The total number of elements in the array
  17256. *
  17257. * @type {number}
  17258. * @readonly
  17259. */
  17260. this.count = array !== undefined ? array.length / stride : 0;
  17261. /**
  17262. * Defines the intended usage pattern of the data store for optimization purposes.
  17263. *
  17264. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  17265. * instantiate a new one and set the desired usage before the next render.
  17266. *
  17267. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  17268. * @default StaticDrawUsage
  17269. */
  17270. this.usage = StaticDrawUsage;
  17271. /**
  17272. * This can be used to only update some components of stored vectors (for example, just the
  17273. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  17274. *
  17275. * @type {Array<Object>}
  17276. */
  17277. this.updateRanges = [];
  17278. /**
  17279. * A version number, incremented every time the `needsUpdate` is set to `true`.
  17280. *
  17281. * @type {number}
  17282. */
  17283. this.version = 0;
  17284. /**
  17285. * The UUID of the interleaved buffer.
  17286. *
  17287. * @type {string}
  17288. * @readonly
  17289. */
  17290. this.uuid = generateUUID();
  17291. }
  17292. /**
  17293. * A callback function that is executed after the renderer has transferred the attribute array
  17294. * data to the GPU.
  17295. */
  17296. onUploadCallback() {}
  17297. /**
  17298. * Flag to indicate that this attribute has changed and should be re-sent to
  17299. * the GPU. Set this to `true` when you modify the value of the array.
  17300. *
  17301. * @type {number}
  17302. * @default false
  17303. * @param {boolean} value
  17304. */
  17305. set needsUpdate( value ) {
  17306. if ( value === true ) this.version ++;
  17307. }
  17308. /**
  17309. * Sets the usage of this interleaved buffer.
  17310. *
  17311. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  17312. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  17313. */
  17314. setUsage( value ) {
  17315. this.usage = value;
  17316. return this;
  17317. }
  17318. /**
  17319. * Adds a range of data in the data array to be updated on the GPU.
  17320. *
  17321. * @param {number} start - Position at which to start update.
  17322. * @param {number} count - The number of components to update.
  17323. */
  17324. addUpdateRange( start, count ) {
  17325. this.updateRanges.push( { start, count } );
  17326. }
  17327. /**
  17328. * Clears the update ranges.
  17329. */
  17330. clearUpdateRanges() {
  17331. this.updateRanges.length = 0;
  17332. }
  17333. /**
  17334. * Copies the values of the given interleaved buffer to this instance.
  17335. *
  17336. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  17337. * @return {InterleavedBuffer} A reference to this instance.
  17338. */
  17339. copy( source ) {
  17340. this.array = new source.array.constructor( source.array );
  17341. this.count = source.count;
  17342. this.stride = source.stride;
  17343. this.usage = source.usage;
  17344. return this;
  17345. }
  17346. /**
  17347. * Copies a vector from the given interleaved buffer to this one. The start
  17348. * and destination position in the attribute buffers are represented by the
  17349. * given indices.
  17350. *
  17351. * @param {number} index1 - The destination index into this interleaved buffer.
  17352. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  17353. * @param {number} index2 - The source index into the given interleaved buffer.
  17354. * @return {InterleavedBuffer} A reference to this instance.
  17355. */
  17356. copyAt( index1, interleavedBuffer, index2 ) {
  17357. index1 *= this.stride;
  17358. index2 *= interleavedBuffer.stride;
  17359. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17360. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  17361. }
  17362. return this;
  17363. }
  17364. /**
  17365. * Sets the given array data in the interleaved buffer.
  17366. *
  17367. * @param {(TypedArray|Array)} value - The array data to set.
  17368. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  17369. * @return {InterleavedBuffer} A reference to this instance.
  17370. */
  17371. set( value, offset = 0 ) {
  17372. this.array.set( value, offset );
  17373. return this;
  17374. }
  17375. /**
  17376. * Returns a new interleaved buffer with copied values from this instance.
  17377. *
  17378. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  17379. * @return {InterleavedBuffer} A clone of this instance.
  17380. */
  17381. clone( data ) {
  17382. if ( data.arrayBuffers === undefined ) {
  17383. data.arrayBuffers = {};
  17384. }
  17385. if ( this.array.buffer._uuid === undefined ) {
  17386. this.array.buffer._uuid = generateUUID();
  17387. }
  17388. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17389. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17390. }
  17391. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17392. const ib = new this.constructor( array, this.stride );
  17393. ib.setUsage( this.usage );
  17394. return ib;
  17395. }
  17396. /**
  17397. * Sets the given callback function that is executed after the Renderer has transferred
  17398. * the array data to the GPU. Can be used to perform clean-up operations after
  17399. * the upload when data are not needed anymore on the CPU side.
  17400. *
  17401. * @param {Function} callback - The `onUpload()` callback.
  17402. * @return {InterleavedBuffer} A reference to this instance.
  17403. */
  17404. onUpload( callback ) {
  17405. this.onUploadCallback = callback;
  17406. return this;
  17407. }
  17408. /**
  17409. * Serializes the interleaved buffer into JSON.
  17410. *
  17411. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17412. * @return {Object} A JSON object representing the serialized interleaved buffer.
  17413. */
  17414. toJSON( data ) {
  17415. if ( data.arrayBuffers === undefined ) {
  17416. data.arrayBuffers = {};
  17417. }
  17418. // generate UUID for array buffer if necessary
  17419. if ( this.array.buffer._uuid === undefined ) {
  17420. this.array.buffer._uuid = generateUUID();
  17421. }
  17422. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17423. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17424. }
  17425. //
  17426. return {
  17427. uuid: this.uuid,
  17428. buffer: this.array.buffer._uuid,
  17429. type: this.array.constructor.name,
  17430. stride: this.stride
  17431. };
  17432. }
  17433. }
  17434. const _vector$7 = /*@__PURE__*/ new Vector3();
  17435. /**
  17436. * An alternative version of a buffer attribute with interleaved data. Interleaved
  17437. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  17438. * different offsets into the buffer.
  17439. */
  17440. class InterleavedBufferAttribute {
  17441. /**
  17442. * Constructs a new interleaved buffer attribute.
  17443. *
  17444. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  17445. * @param {number} itemSize - The item size.
  17446. * @param {number} offset - The attribute offset into the buffer.
  17447. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  17448. */
  17449. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17450. /**
  17451. * This flag can be used for type testing.
  17452. *
  17453. * @type {boolean}
  17454. * @readonly
  17455. * @default true
  17456. */
  17457. this.isInterleavedBufferAttribute = true;
  17458. /**
  17459. * The name of the buffer attribute.
  17460. *
  17461. * @type {string}
  17462. */
  17463. this.name = '';
  17464. /**
  17465. * The buffer holding the interleaved data.
  17466. *
  17467. * @type {InterleavedBuffer}
  17468. */
  17469. this.data = interleavedBuffer;
  17470. /**
  17471. * The item size, see {@link BufferAttribute#itemSize}.
  17472. *
  17473. * @type {number}
  17474. */
  17475. this.itemSize = itemSize;
  17476. /**
  17477. * The attribute offset into the buffer.
  17478. *
  17479. * @type {number}
  17480. */
  17481. this.offset = offset;
  17482. /**
  17483. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  17484. *
  17485. * @type {InterleavedBuffer}
  17486. */
  17487. this.normalized = normalized;
  17488. }
  17489. /**
  17490. * The item count of this buffer attribute.
  17491. *
  17492. * @type {number}
  17493. * @readonly
  17494. */
  17495. get count() {
  17496. return this.data.count;
  17497. }
  17498. /**
  17499. * The array holding the interleaved buffer attribute data.
  17500. *
  17501. * @type {TypedArray}
  17502. */
  17503. get array() {
  17504. return this.data.array;
  17505. }
  17506. /**
  17507. * Flag to indicate that this attribute has changed and should be re-sent to
  17508. * the GPU. Set this to `true` when you modify the value of the array.
  17509. *
  17510. * @type {number}
  17511. * @default false
  17512. * @param {boolean} value
  17513. */
  17514. set needsUpdate( value ) {
  17515. this.data.needsUpdate = value;
  17516. }
  17517. /**
  17518. * Applies the given 4x4 matrix to the given attribute. Only works with
  17519. * item size `3`.
  17520. *
  17521. * @param {Matrix4} m - The matrix to apply.
  17522. * @return {InterleavedBufferAttribute} A reference to this instance.
  17523. */
  17524. applyMatrix4( m ) {
  17525. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17526. _vector$7.fromBufferAttribute( this, i );
  17527. _vector$7.applyMatrix4( m );
  17528. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17529. }
  17530. return this;
  17531. }
  17532. /**
  17533. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  17534. * item size `3`.
  17535. *
  17536. * @param {Matrix3} m - The normal matrix to apply.
  17537. * @return {InterleavedBufferAttribute} A reference to this instance.
  17538. */
  17539. applyNormalMatrix( m ) {
  17540. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17541. _vector$7.fromBufferAttribute( this, i );
  17542. _vector$7.applyNormalMatrix( m );
  17543. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17544. }
  17545. return this;
  17546. }
  17547. /**
  17548. * Applies the given 4x4 matrix to the given attribute. Only works with
  17549. * item size `3` and with direction vectors.
  17550. *
  17551. * @param {Matrix4} m - The matrix to apply.
  17552. * @return {InterleavedBufferAttribute} A reference to this instance.
  17553. */
  17554. transformDirection( m ) {
  17555. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17556. _vector$7.fromBufferAttribute( this, i );
  17557. _vector$7.transformDirection( m );
  17558. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17559. }
  17560. return this;
  17561. }
  17562. /**
  17563. * Returns the given component of the vector at the given index.
  17564. *
  17565. * @param {number} index - The index into the buffer attribute.
  17566. * @param {number} component - The component index.
  17567. * @return {number} The returned value.
  17568. */
  17569. getComponent( index, component ) {
  17570. let value = this.array[ index * this.data.stride + this.offset + component ];
  17571. if ( this.normalized ) value = denormalize( value, this.array );
  17572. return value;
  17573. }
  17574. /**
  17575. * Sets the given value to the given component of the vector at the given index.
  17576. *
  17577. * @param {number} index - The index into the buffer attribute.
  17578. * @param {number} component - The component index.
  17579. * @param {number} value - The value to set.
  17580. * @return {InterleavedBufferAttribute} A reference to this instance.
  17581. */
  17582. setComponent( index, component, value ) {
  17583. if ( this.normalized ) value = normalize( value, this.array );
  17584. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  17585. return this;
  17586. }
  17587. /**
  17588. * Sets the x component of the vector at the given index.
  17589. *
  17590. * @param {number} index - The index into the buffer attribute.
  17591. * @param {number} x - The value to set.
  17592. * @return {InterleavedBufferAttribute} A reference to this instance.
  17593. */
  17594. setX( index, x ) {
  17595. if ( this.normalized ) x = normalize( x, this.array );
  17596. this.data.array[ index * this.data.stride + this.offset ] = x;
  17597. return this;
  17598. }
  17599. /**
  17600. * Sets the y component of the vector at the given index.
  17601. *
  17602. * @param {number} index - The index into the buffer attribute.
  17603. * @param {number} y - The value to set.
  17604. * @return {InterleavedBufferAttribute} A reference to this instance.
  17605. */
  17606. setY( index, y ) {
  17607. if ( this.normalized ) y = normalize( y, this.array );
  17608. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17609. return this;
  17610. }
  17611. /**
  17612. * Sets the z component of the vector at the given index.
  17613. *
  17614. * @param {number} index - The index into the buffer attribute.
  17615. * @param {number} z - The value to set.
  17616. * @return {InterleavedBufferAttribute} A reference to this instance.
  17617. */
  17618. setZ( index, z ) {
  17619. if ( this.normalized ) z = normalize( z, this.array );
  17620. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17621. return this;
  17622. }
  17623. /**
  17624. * Sets the w component of the vector at the given index.
  17625. *
  17626. * @param {number} index - The index into the buffer attribute.
  17627. * @param {number} w - The value to set.
  17628. * @return {InterleavedBufferAttribute} A reference to this instance.
  17629. */
  17630. setW( index, w ) {
  17631. if ( this.normalized ) w = normalize( w, this.array );
  17632. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17633. return this;
  17634. }
  17635. /**
  17636. * Returns the x component of the vector at the given index.
  17637. *
  17638. * @param {number} index - The index into the buffer attribute.
  17639. * @return {number} The x component.
  17640. */
  17641. getX( index ) {
  17642. let x = this.data.array[ index * this.data.stride + this.offset ];
  17643. if ( this.normalized ) x = denormalize( x, this.array );
  17644. return x;
  17645. }
  17646. /**
  17647. * Returns the y component of the vector at the given index.
  17648. *
  17649. * @param {number} index - The index into the buffer attribute.
  17650. * @return {number} The y component.
  17651. */
  17652. getY( index ) {
  17653. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17654. if ( this.normalized ) y = denormalize( y, this.array );
  17655. return y;
  17656. }
  17657. /**
  17658. * Returns the z component of the vector at the given index.
  17659. *
  17660. * @param {number} index - The index into the buffer attribute.
  17661. * @return {number} The z component.
  17662. */
  17663. getZ( index ) {
  17664. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17665. if ( this.normalized ) z = denormalize( z, this.array );
  17666. return z;
  17667. }
  17668. /**
  17669. * Returns the w component of the vector at the given index.
  17670. *
  17671. * @param {number} index - The index into the buffer attribute.
  17672. * @return {number} The w component.
  17673. */
  17674. getW( index ) {
  17675. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17676. if ( this.normalized ) w = denormalize( w, this.array );
  17677. return w;
  17678. }
  17679. /**
  17680. * Sets the x and y component of the vector at the given index.
  17681. *
  17682. * @param {number} index - The index into the buffer attribute.
  17683. * @param {number} x - The value for the x component to set.
  17684. * @param {number} y - The value for the y component to set.
  17685. * @return {InterleavedBufferAttribute} A reference to this instance.
  17686. */
  17687. setXY( index, x, y ) {
  17688. index = index * this.data.stride + this.offset;
  17689. if ( this.normalized ) {
  17690. x = normalize( x, this.array );
  17691. y = normalize( y, this.array );
  17692. }
  17693. this.data.array[ index + 0 ] = x;
  17694. this.data.array[ index + 1 ] = y;
  17695. return this;
  17696. }
  17697. /**
  17698. * Sets the x, y and z component of the vector at the given index.
  17699. *
  17700. * @param {number} index - The index into the buffer attribute.
  17701. * @param {number} x - The value for the x component to set.
  17702. * @param {number} y - The value for the y component to set.
  17703. * @param {number} z - The value for the z component to set.
  17704. * @return {InterleavedBufferAttribute} A reference to this instance.
  17705. */
  17706. setXYZ( index, x, y, z ) {
  17707. index = index * this.data.stride + this.offset;
  17708. if ( this.normalized ) {
  17709. x = normalize( x, this.array );
  17710. y = normalize( y, this.array );
  17711. z = normalize( z, this.array );
  17712. }
  17713. this.data.array[ index + 0 ] = x;
  17714. this.data.array[ index + 1 ] = y;
  17715. this.data.array[ index + 2 ] = z;
  17716. return this;
  17717. }
  17718. /**
  17719. * Sets the x, y, z and w component of the vector at the given index.
  17720. *
  17721. * @param {number} index - The index into the buffer attribute.
  17722. * @param {number} x - The value for the x component to set.
  17723. * @param {number} y - The value for the y component to set.
  17724. * @param {number} z - The value for the z component to set.
  17725. * @param {number} w - The value for the w component to set.
  17726. * @return {InterleavedBufferAttribute} A reference to this instance.
  17727. */
  17728. setXYZW( index, x, y, z, w ) {
  17729. index = index * this.data.stride + this.offset;
  17730. if ( this.normalized ) {
  17731. x = normalize( x, this.array );
  17732. y = normalize( y, this.array );
  17733. z = normalize( z, this.array );
  17734. w = normalize( w, this.array );
  17735. }
  17736. this.data.array[ index + 0 ] = x;
  17737. this.data.array[ index + 1 ] = y;
  17738. this.data.array[ index + 2 ] = z;
  17739. this.data.array[ index + 3 ] = w;
  17740. return this;
  17741. }
  17742. /**
  17743. * Returns a new buffer attribute with copied values from this instance.
  17744. *
  17745. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17746. *
  17747. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  17748. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  17749. */
  17750. clone( data ) {
  17751. if ( data === undefined ) {
  17752. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17753. const array = [];
  17754. for ( let i = 0; i < this.count; i ++ ) {
  17755. const index = i * this.data.stride + this.offset;
  17756. for ( let j = 0; j < this.itemSize; j ++ ) {
  17757. array.push( this.data.array[ index + j ] );
  17758. }
  17759. }
  17760. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17761. } else {
  17762. if ( data.interleavedBuffers === undefined ) {
  17763. data.interleavedBuffers = {};
  17764. }
  17765. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17766. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17767. }
  17768. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17769. }
  17770. }
  17771. /**
  17772. * Serializes the buffer attribute into JSON.
  17773. *
  17774. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17775. *
  17776. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17777. * @return {Object} A JSON object representing the serialized buffer attribute.
  17778. */
  17779. toJSON( data ) {
  17780. if ( data === undefined ) {
  17781. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17782. const array = [];
  17783. for ( let i = 0; i < this.count; i ++ ) {
  17784. const index = i * this.data.stride + this.offset;
  17785. for ( let j = 0; j < this.itemSize; j ++ ) {
  17786. array.push( this.data.array[ index + j ] );
  17787. }
  17788. }
  17789. // de-interleave data and save it as an ordinary buffer attribute for now
  17790. return {
  17791. itemSize: this.itemSize,
  17792. type: this.array.constructor.name,
  17793. array: array,
  17794. normalized: this.normalized
  17795. };
  17796. } else {
  17797. // save as true interleaved attribute
  17798. if ( data.interleavedBuffers === undefined ) {
  17799. data.interleavedBuffers = {};
  17800. }
  17801. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17802. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17803. }
  17804. return {
  17805. isInterleavedBufferAttribute: true,
  17806. itemSize: this.itemSize,
  17807. data: this.data.uuid,
  17808. offset: this.offset,
  17809. normalized: this.normalized
  17810. };
  17811. }
  17812. }
  17813. }
  17814. /**
  17815. * A material for rendering instances of {@link Sprite}.
  17816. *
  17817. * ```js
  17818. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  17819. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  17820. *
  17821. * const sprite = new THREE.Sprite( material );
  17822. * sprite.scale.set(200, 200, 1)
  17823. * scene.add( sprite );
  17824. * ```
  17825. *
  17826. * @augments Material
  17827. */
  17828. class SpriteMaterial extends Material {
  17829. /**
  17830. * Constructs a new sprite material.
  17831. *
  17832. * @param {Object} [parameters] - An object with one or more properties
  17833. * defining the material's appearance. Any property of the material
  17834. * (including any property from inherited materials) can be passed
  17835. * in here. Color values can be passed any type of value accepted
  17836. * by {@link Color#set}.
  17837. */
  17838. constructor( parameters ) {
  17839. super();
  17840. /**
  17841. * This flag can be used for type testing.
  17842. *
  17843. * @type {boolean}
  17844. * @readonly
  17845. * @default true
  17846. */
  17847. this.isSpriteMaterial = true;
  17848. this.type = 'SpriteMaterial';
  17849. /**
  17850. * Color of the material.
  17851. *
  17852. * @type {Color}
  17853. * @default (1,1,1)
  17854. */
  17855. this.color = new Color( 0xffffff );
  17856. /**
  17857. * The color map. May optionally include an alpha channel, typically combined
  17858. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  17859. * color is modulated by the diffuse `color`.
  17860. *
  17861. * @type {?Texture}
  17862. * @default null
  17863. */
  17864. this.map = null;
  17865. /**
  17866. * The alpha map is a grayscale texture that controls the opacity across the
  17867. * surface (black: fully transparent; white: fully opaque).
  17868. *
  17869. * Only the color of the texture is used, ignoring the alpha channel if one
  17870. * exists. For RGB and RGBA textures, the renderer will use the green channel
  17871. * when sampling this texture due to the extra bit of precision provided for
  17872. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  17873. * luminance/alpha textures will also still work as expected.
  17874. *
  17875. * @type {?Texture}
  17876. * @default null
  17877. */
  17878. this.alphaMap = null;
  17879. /**
  17880. * The rotation of the sprite in radians.
  17881. *
  17882. * @type {number}
  17883. * @default 0
  17884. */
  17885. this.rotation = 0;
  17886. /**
  17887. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  17888. *
  17889. * @type {boolean}
  17890. * @default true
  17891. */
  17892. this.sizeAttenuation = true;
  17893. /**
  17894. * Overwritten since sprite materials are transparent
  17895. * by default.
  17896. *
  17897. * @type {boolean}
  17898. * @default true
  17899. */
  17900. this.transparent = true;
  17901. /**
  17902. * Whether the material is affected by fog or not.
  17903. *
  17904. * @type {boolean}
  17905. * @default true
  17906. */
  17907. this.fog = true;
  17908. this.setValues( parameters );
  17909. }
  17910. copy( source ) {
  17911. super.copy( source );
  17912. this.color.copy( source.color );
  17913. this.map = source.map;
  17914. this.alphaMap = source.alphaMap;
  17915. this.rotation = source.rotation;
  17916. this.sizeAttenuation = source.sizeAttenuation;
  17917. this.fog = source.fog;
  17918. return this;
  17919. }
  17920. }
  17921. let _geometry;
  17922. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17923. const _worldScale = /*@__PURE__*/ new Vector3();
  17924. const _mvPosition = /*@__PURE__*/ new Vector3();
  17925. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17926. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17927. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17928. const _vA = /*@__PURE__*/ new Vector3();
  17929. const _vB = /*@__PURE__*/ new Vector3();
  17930. const _vC = /*@__PURE__*/ new Vector3();
  17931. const _uvA = /*@__PURE__*/ new Vector2();
  17932. const _uvB = /*@__PURE__*/ new Vector2();
  17933. const _uvC = /*@__PURE__*/ new Vector2();
  17934. /**
  17935. * A sprite is a plane that always faces towards the camera, generally with a
  17936. * partially transparent texture applied.
  17937. *
  17938. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  17939. * have no effect.
  17940. *
  17941. * ```js
  17942. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  17943. * const material = new THREE.SpriteMaterial( { map: map } );
  17944. *
  17945. * const sprite = new THREE.Sprite( material );
  17946. * scene.add( sprite );
  17947. * ```
  17948. *
  17949. * @augments Object3D
  17950. */
  17951. class Sprite extends Object3D {
  17952. /**
  17953. * Constructs a new sprite.
  17954. *
  17955. * @param {(SpriteMaterial|SpriteNodeMaterial)} [material] - The sprite material.
  17956. */
  17957. constructor( material = new SpriteMaterial() ) {
  17958. super();
  17959. /**
  17960. * This flag can be used for type testing.
  17961. *
  17962. * @type {boolean}
  17963. * @readonly
  17964. * @default true
  17965. */
  17966. this.isSprite = true;
  17967. this.type = 'Sprite';
  17968. if ( _geometry === undefined ) {
  17969. _geometry = new BufferGeometry();
  17970. const float32Array = new Float32Array( [
  17971. -0.5, -0.5, 0, 0, 0,
  17972. 0.5, -0.5, 0, 1, 0,
  17973. 0.5, 0.5, 0, 1, 1,
  17974. -0.5, 0.5, 0, 0, 1
  17975. ] );
  17976. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  17977. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  17978. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  17979. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  17980. }
  17981. /**
  17982. * The sprite geometry.
  17983. *
  17984. * @type {BufferGeometry}
  17985. */
  17986. this.geometry = _geometry;
  17987. /**
  17988. * The sprite material.
  17989. *
  17990. * @type {(SpriteMaterial|SpriteNodeMaterial)}
  17991. */
  17992. this.material = material;
  17993. /**
  17994. * The sprite's anchor point, and the point around which the sprite rotates.
  17995. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  17996. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  17997. *
  17998. * @type {Vector2}
  17999. * @default (0.5,0.5)
  18000. */
  18001. this.center = new Vector2( 0.5, 0.5 );
  18002. /**
  18003. * The number of instances of this sprite.
  18004. * Can only be used with {@link WebGPURenderer}.
  18005. *
  18006. * @type {number}
  18007. * @default 1
  18008. */
  18009. this.count = 1;
  18010. }
  18011. /**
  18012. * Computes intersection points between a casted ray and this sprite.
  18013. *
  18014. * @param {Raycaster} raycaster - The raycaster.
  18015. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18016. */
  18017. raycast( raycaster, intersects ) {
  18018. if ( raycaster.camera === null ) {
  18019. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18020. }
  18021. _worldScale.setFromMatrixScale( this.matrixWorld );
  18022. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18023. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18024. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18025. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18026. _worldScale.multiplyScalar( - _mvPosition.z );
  18027. }
  18028. const rotation = this.material.rotation;
  18029. let sin, cos;
  18030. if ( rotation !== 0 ) {
  18031. cos = Math.cos( rotation );
  18032. sin = Math.sin( rotation );
  18033. }
  18034. const center = this.center;
  18035. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18036. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18037. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18038. _uvA.set( 0, 0 );
  18039. _uvB.set( 1, 0 );
  18040. _uvC.set( 1, 1 );
  18041. // check first triangle
  18042. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18043. if ( intersect === null ) {
  18044. // check second triangle
  18045. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18046. _uvB.set( 0, 1 );
  18047. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18048. if ( intersect === null ) {
  18049. return;
  18050. }
  18051. }
  18052. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18053. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18054. intersects.push( {
  18055. distance: distance,
  18056. point: _intersectPoint.clone(),
  18057. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18058. face: null,
  18059. object: this
  18060. } );
  18061. }
  18062. copy( source, recursive ) {
  18063. super.copy( source, recursive );
  18064. if ( source.center !== undefined ) this.center.copy( source.center );
  18065. this.material = source.material;
  18066. return this;
  18067. }
  18068. }
  18069. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18070. // compute position in camera space
  18071. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18072. // to check if rotation is not zero
  18073. if ( sin !== undefined ) {
  18074. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18075. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18076. } else {
  18077. _rotatedPosition.copy( _alignedPosition );
  18078. }
  18079. vertexPosition.copy( mvPosition );
  18080. vertexPosition.x += _rotatedPosition.x;
  18081. vertexPosition.y += _rotatedPosition.y;
  18082. // transform to world space
  18083. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18084. }
  18085. const _v1$2 = /*@__PURE__*/ new Vector3();
  18086. const _v2$1 = /*@__PURE__*/ new Vector3();
  18087. /**
  18088. * A component for providing a basic Level of Detail (LOD) mechanism.
  18089. *
  18090. * Every LOD level is associated with an object, and rendering can be switched
  18091. * between them at the distances specified. Typically you would create, say,
  18092. * three meshes, one for far away (low detail), one for mid range (medium
  18093. * detail) and one for close up (high detail).
  18094. *
  18095. * ```js
  18096. * const lod = new THREE.LOD();
  18097. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  18098. *
  18099. * //Create spheres with 3 levels of detail and create new LOD levels for them
  18100. * for( let i = 0; i < 3; i++ ) {
  18101. *
  18102. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  18103. * const mesh = new THREE.Mesh( geometry, material );
  18104. * lod.addLevel( mesh, i * 75 );
  18105. *
  18106. * }
  18107. *
  18108. * scene.add( lod );
  18109. * ```
  18110. *
  18111. * @augments Object3D
  18112. */
  18113. class LOD extends Object3D {
  18114. /**
  18115. * Constructs a new LOD.
  18116. */
  18117. constructor() {
  18118. super();
  18119. /**
  18120. * This flag can be used for type testing.
  18121. *
  18122. * @type {boolean}
  18123. * @readonly
  18124. * @default true
  18125. */
  18126. this.isLOD = true;
  18127. /**
  18128. * The current LOD index.
  18129. *
  18130. * @private
  18131. * @type {number}
  18132. * @default 0
  18133. */
  18134. this._currentLevel = 0;
  18135. this.type = 'LOD';
  18136. Object.defineProperties( this, {
  18137. /**
  18138. * This array holds the LOD levels.
  18139. *
  18140. * @name LOD#levels
  18141. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  18142. */
  18143. levels: {
  18144. enumerable: true,
  18145. value: []
  18146. }
  18147. } );
  18148. /**
  18149. * Whether the LOD object is updated automatically by the renderer per frame
  18150. * or not. If set to `false`, you have to call {@link LOD#update} in the
  18151. * render loop by yourself.
  18152. *
  18153. * @type {boolean}
  18154. * @default true
  18155. */
  18156. this.autoUpdate = true;
  18157. }
  18158. copy( source ) {
  18159. super.copy( source, false );
  18160. const levels = source.levels;
  18161. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18162. const level = levels[ i ];
  18163. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18164. }
  18165. this.autoUpdate = source.autoUpdate;
  18166. return this;
  18167. }
  18168. /**
  18169. * Adds a mesh that will display at a certain distance and greater. Typically
  18170. * the further away the distance, the lower the detail on the mesh.
  18171. *
  18172. * @param {Object3D} object - The 3D object to display at this level.
  18173. * @param {number} [distance=0] - The distance at which to display this level of detail.
  18174. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  18175. * @return {LOD} A reference to this instance.
  18176. */
  18177. addLevel( object, distance = 0, hysteresis = 0 ) {
  18178. distance = Math.abs( distance );
  18179. const levels = this.levels;
  18180. let l;
  18181. for ( l = 0; l < levels.length; l ++ ) {
  18182. if ( distance < levels[ l ].distance ) {
  18183. break;
  18184. }
  18185. }
  18186. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18187. this.add( object );
  18188. return this;
  18189. }
  18190. /**
  18191. * Removes an existing level, based on the distance from the camera.
  18192. * Returns `true` when the level has been removed. Otherwise `false`.
  18193. *
  18194. * @param {number} distance - Distance of the level to remove.
  18195. * @return {boolean} Whether the level has been removed or not.
  18196. */
  18197. removeLevel( distance ) {
  18198. const levels = this.levels;
  18199. for ( let i = 0; i < levels.length; i ++ ) {
  18200. if ( levels[ i ].distance === distance ) {
  18201. const removedElements = levels.splice( i, 1 );
  18202. this.remove( removedElements[ 0 ].object );
  18203. return true;
  18204. }
  18205. }
  18206. return false;
  18207. }
  18208. /**
  18209. * Returns the currently active LOD level index.
  18210. *
  18211. * @return {number} The current active LOD level index.
  18212. */
  18213. getCurrentLevel() {
  18214. return this._currentLevel;
  18215. }
  18216. /**
  18217. * Returns a reference to the first 3D object that is greater than
  18218. * the given distance.
  18219. *
  18220. * @param {number} distance - The LOD distance.
  18221. * @return {Object3D|null} The found 3D object. `null` if no 3D object has been found.
  18222. */
  18223. getObjectForDistance( distance ) {
  18224. const levels = this.levels;
  18225. if ( levels.length > 0 ) {
  18226. let i, l;
  18227. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18228. let levelDistance = levels[ i ].distance;
  18229. if ( levels[ i ].object.visible ) {
  18230. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18231. }
  18232. if ( distance < levelDistance ) {
  18233. break;
  18234. }
  18235. }
  18236. return levels[ i - 1 ].object;
  18237. }
  18238. return null;
  18239. }
  18240. /**
  18241. * Computes intersection points between a casted ray and this LOD.
  18242. *
  18243. * @param {Raycaster} raycaster - The raycaster.
  18244. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18245. */
  18246. raycast( raycaster, intersects ) {
  18247. const levels = this.levels;
  18248. if ( levels.length > 0 ) {
  18249. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18250. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18251. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18252. }
  18253. }
  18254. /**
  18255. * Updates the LOD by computing which LOD level should be visible according
  18256. * to the current distance of the given camera.
  18257. *
  18258. * @param {Camera} camera - The camera the scene is rendered with.
  18259. */
  18260. update( camera ) {
  18261. const levels = this.levels;
  18262. if ( levels.length > 1 ) {
  18263. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18264. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18265. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18266. levels[ 0 ].object.visible = true;
  18267. let i, l;
  18268. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18269. let levelDistance = levels[ i ].distance;
  18270. if ( levels[ i ].object.visible ) {
  18271. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18272. }
  18273. if ( distance >= levelDistance ) {
  18274. levels[ i - 1 ].object.visible = false;
  18275. levels[ i ].object.visible = true;
  18276. } else {
  18277. break;
  18278. }
  18279. }
  18280. this._currentLevel = i - 1;
  18281. for ( ; i < l; i ++ ) {
  18282. levels[ i ].object.visible = false;
  18283. }
  18284. }
  18285. }
  18286. toJSON( meta ) {
  18287. const data = super.toJSON( meta );
  18288. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18289. data.object.levels = [];
  18290. const levels = this.levels;
  18291. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18292. const level = levels[ i ];
  18293. data.object.levels.push( {
  18294. object: level.object.uuid,
  18295. distance: level.distance,
  18296. hysteresis: level.hysteresis
  18297. } );
  18298. }
  18299. return data;
  18300. }
  18301. }
  18302. const _basePosition = /*@__PURE__*/ new Vector3();
  18303. const _skinIndex = /*@__PURE__*/ new Vector4();
  18304. const _skinWeight = /*@__PURE__*/ new Vector4();
  18305. const _vector3 = /*@__PURE__*/ new Vector3();
  18306. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18307. const _vertex = /*@__PURE__*/ new Vector3();
  18308. const _sphere$5 = /*@__PURE__*/ new Sphere();
  18309. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18310. const _ray$2 = /*@__PURE__*/ new Ray();
  18311. /**
  18312. * A mesh that has a {@link Skeleton} that can then be used to animate the
  18313. * vertices of the geometry with skinning/skeleton animation.
  18314. *
  18315. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  18316. * as buffer attributes in its geometry. These attribute define which bones affect a single
  18317. * vertex to a certain extend.
  18318. *
  18319. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  18320. * or {@link FBXLoader } import respective models.
  18321. *
  18322. * @augments Mesh
  18323. */
  18324. class SkinnedMesh extends Mesh {
  18325. /**
  18326. * Constructs a new skinned mesh.
  18327. *
  18328. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18329. * @param {Material|Array<Material>} [material] - The mesh material.
  18330. */
  18331. constructor( geometry, material ) {
  18332. super( geometry, material );
  18333. /**
  18334. * This flag can be used for type testing.
  18335. *
  18336. * @type {boolean}
  18337. * @readonly
  18338. * @default true
  18339. */
  18340. this.isSkinnedMesh = true;
  18341. this.type = 'SkinnedMesh';
  18342. /**
  18343. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  18344. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  18345. * across multiple skinned meshes.
  18346. *
  18347. * @type {(AttachedBindMode|DetachedBindMode)}
  18348. * @default AttachedBindMode
  18349. */
  18350. this.bindMode = AttachedBindMode;
  18351. /**
  18352. * The base matrix that is used for the bound bone transforms.
  18353. *
  18354. * @type {Matrix4}
  18355. */
  18356. this.bindMatrix = new Matrix4();
  18357. /**
  18358. * The base matrix that is used for resetting the bound bone transforms.
  18359. *
  18360. * @type {Matrix4}
  18361. */
  18362. this.bindMatrixInverse = new Matrix4();
  18363. /**
  18364. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  18365. *
  18366. * @type {?Box3}
  18367. * @default null
  18368. */
  18369. this.boundingBox = null;
  18370. /**
  18371. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  18372. *
  18373. * @type {?Sphere}
  18374. * @default null
  18375. */
  18376. this.boundingSphere = null;
  18377. }
  18378. /**
  18379. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  18380. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18381. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  18382. * the current animation state.
  18383. */
  18384. computeBoundingBox() {
  18385. const geometry = this.geometry;
  18386. if ( this.boundingBox === null ) {
  18387. this.boundingBox = new Box3();
  18388. }
  18389. this.boundingBox.makeEmpty();
  18390. const positionAttribute = geometry.getAttribute( 'position' );
  18391. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18392. this.getVertexPosition( i, _vertex );
  18393. this.boundingBox.expandByPoint( _vertex );
  18394. }
  18395. }
  18396. /**
  18397. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  18398. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  18399. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  18400. * per frame in order to reflect the current animation state.
  18401. */
  18402. computeBoundingSphere() {
  18403. const geometry = this.geometry;
  18404. if ( this.boundingSphere === null ) {
  18405. this.boundingSphere = new Sphere();
  18406. }
  18407. this.boundingSphere.makeEmpty();
  18408. const positionAttribute = geometry.getAttribute( 'position' );
  18409. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18410. this.getVertexPosition( i, _vertex );
  18411. this.boundingSphere.expandByPoint( _vertex );
  18412. }
  18413. }
  18414. copy( source, recursive ) {
  18415. super.copy( source, recursive );
  18416. this.bindMode = source.bindMode;
  18417. this.bindMatrix.copy( source.bindMatrix );
  18418. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18419. this.skeleton = source.skeleton;
  18420. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18421. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18422. return this;
  18423. }
  18424. raycast( raycaster, intersects ) {
  18425. const material = this.material;
  18426. const matrixWorld = this.matrixWorld;
  18427. if ( material === undefined ) return;
  18428. // test with bounding sphere in world space
  18429. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18430. _sphere$5.copy( this.boundingSphere );
  18431. _sphere$5.applyMatrix4( matrixWorld );
  18432. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  18433. // convert ray to local space of skinned mesh
  18434. _inverseMatrix$2.copy( matrixWorld ).invert();
  18435. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18436. // test with bounding box in local space
  18437. if ( this.boundingBox !== null ) {
  18438. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18439. }
  18440. // test for intersections with geometry
  18441. this._computeIntersections( raycaster, intersects, _ray$2 );
  18442. }
  18443. getVertexPosition( index, target ) {
  18444. super.getVertexPosition( index, target );
  18445. this.applyBoneTransform( index, target );
  18446. return target;
  18447. }
  18448. /**
  18449. * Binds the given skeleton to the skinned mesh.
  18450. *
  18451. * @param {Skeleton} skeleton - The skeleton to bind.
  18452. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  18453. * the skinned mesh's world matrix will be used instead.
  18454. */
  18455. bind( skeleton, bindMatrix ) {
  18456. this.skeleton = skeleton;
  18457. if ( bindMatrix === undefined ) {
  18458. this.updateMatrixWorld( true );
  18459. this.skeleton.calculateInverses();
  18460. bindMatrix = this.matrixWorld;
  18461. }
  18462. this.bindMatrix.copy( bindMatrix );
  18463. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18464. }
  18465. /**
  18466. * This method sets the skinned mesh in the rest pose).
  18467. */
  18468. pose() {
  18469. this.skeleton.pose();
  18470. }
  18471. /**
  18472. * Normalizes the skin weights which are defined as a buffer attribute
  18473. * in the skinned mesh's geometry.
  18474. */
  18475. normalizeSkinWeights() {
  18476. const vector = new Vector4();
  18477. const skinWeight = this.geometry.attributes.skinWeight;
  18478. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18479. vector.fromBufferAttribute( skinWeight, i );
  18480. const scale = 1.0 / vector.manhattanLength();
  18481. if ( scale !== Infinity ) {
  18482. vector.multiplyScalar( scale );
  18483. } else {
  18484. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18485. }
  18486. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18487. }
  18488. }
  18489. updateMatrixWorld( force ) {
  18490. super.updateMatrixWorld( force );
  18491. if ( this.bindMode === AttachedBindMode ) {
  18492. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18493. } else if ( this.bindMode === DetachedBindMode ) {
  18494. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18495. } else {
  18496. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18497. }
  18498. }
  18499. /**
  18500. * Applies the bone transform associated with the given index to the given
  18501. * vertex position. Returns the updated vector.
  18502. *
  18503. * @param {number} index - The vertex index.
  18504. * @param {Vector3} target - The target object that is used to store the method's result.
  18505. * the skinned mesh's world matrix will be used instead.
  18506. * @return {Vector3} The updated vertex position.
  18507. */
  18508. applyBoneTransform( index, target ) {
  18509. const skeleton = this.skeleton;
  18510. const geometry = this.geometry;
  18511. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18512. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18513. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18514. target.set( 0, 0, 0 );
  18515. for ( let i = 0; i < 4; i ++ ) {
  18516. const weight = _skinWeight.getComponent( i );
  18517. if ( weight !== 0 ) {
  18518. const boneIndex = _skinIndex.getComponent( i );
  18519. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18520. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18521. }
  18522. }
  18523. return target.applyMatrix4( this.bindMatrixInverse );
  18524. }
  18525. }
  18526. /**
  18527. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  18528. * the {@link SkinnedMesh}.
  18529. *
  18530. * ```js
  18531. * const root = new THREE.Bone();
  18532. * const child = new THREE.Bone();
  18533. *
  18534. * root.add( child );
  18535. * child.position.y = 5;
  18536. * ```
  18537. *
  18538. * @augments Object3D
  18539. */
  18540. class Bone extends Object3D {
  18541. /**
  18542. * Constructs a new bone.
  18543. */
  18544. constructor() {
  18545. super();
  18546. /**
  18547. * This flag can be used for type testing.
  18548. *
  18549. * @type {boolean}
  18550. * @readonly
  18551. * @default true
  18552. */
  18553. this.isBone = true;
  18554. this.type = 'Bone';
  18555. }
  18556. }
  18557. /**
  18558. * Creates a texture directly from raw buffer data.
  18559. *
  18560. * The interpretation of the data depends on type and format: If the type is
  18561. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  18562. * texel data. If the format is `RGBAFormat`, data needs four values for
  18563. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  18564. *
  18565. * @augments Texture
  18566. */
  18567. class DataTexture extends Texture {
  18568. /**
  18569. * Constructs a new data texture.
  18570. *
  18571. * @param {?TypedArray} [data=null] - The buffer data.
  18572. * @param {number} [width=1] - The width of the texture.
  18573. * @param {number} [height=1] - The height of the texture.
  18574. * @param {number} [format=RGBAFormat] - The texture format.
  18575. * @param {number} [type=UnsignedByteType] - The texture type.
  18576. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  18577. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  18578. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  18579. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  18580. * @param {number} [minFilter=NearestFilter] - The min filter value.
  18581. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  18582. * @param {string} [colorSpace=NoColorSpace] - The color space.
  18583. */
  18584. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18585. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18586. /**
  18587. * This flag can be used for type testing.
  18588. *
  18589. * @type {boolean}
  18590. * @readonly
  18591. * @default true
  18592. */
  18593. this.isDataTexture = true;
  18594. /**
  18595. * The image definition of a data texture.
  18596. *
  18597. * @type {{data:TypedArray,width:number,height:number}}
  18598. */
  18599. this.image = { data: data, width: width, height: height };
  18600. /**
  18601. * Whether to generate mipmaps (if possible) for a texture.
  18602. *
  18603. * Overwritten and set to `false` by default.
  18604. *
  18605. * @type {boolean}
  18606. * @default false
  18607. */
  18608. this.generateMipmaps = false;
  18609. /**
  18610. * If set to `true`, the texture is flipped along the vertical axis when
  18611. * uploaded to the GPU.
  18612. *
  18613. * Overwritten and set to `false` by default.
  18614. *
  18615. * @type {boolean}
  18616. * @default false
  18617. */
  18618. this.flipY = false;
  18619. /**
  18620. * Specifies the alignment requirements for the start of each pixel row in memory.
  18621. *
  18622. * Overwritten and set to `1` by default.
  18623. *
  18624. * @type {boolean}
  18625. * @default 1
  18626. */
  18627. this.unpackAlignment = 1;
  18628. }
  18629. }
  18630. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18631. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18632. /**
  18633. * Class for representing the armatures in `three.js`. The skeleton
  18634. * is defined by a hierarchy of bones.
  18635. *
  18636. * ```js
  18637. * const bones = [];
  18638. *
  18639. * const shoulder = new THREE.Bone();
  18640. * const elbow = new THREE.Bone();
  18641. * const hand = new THREE.Bone();
  18642. *
  18643. * shoulder.add( elbow );
  18644. * elbow.add( hand );
  18645. *
  18646. * bones.push( shoulder , elbow, hand);
  18647. *
  18648. * shoulder.position.y = -5;
  18649. * elbow.position.y = 0;
  18650. * hand.position.y = 5;
  18651. *
  18652. * const armSkeleton = new THREE.Skeleton( bones );
  18653. * ```
  18654. */
  18655. class Skeleton {
  18656. /**
  18657. * Constructs a new skeleton.
  18658. *
  18659. * @param {Array<Bone>} [bones] - An array of bones.
  18660. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  18661. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  18662. */
  18663. constructor( bones = [], boneInverses = [] ) {
  18664. this.uuid = generateUUID();
  18665. /**
  18666. * An array of bones defining the skeleton.
  18667. *
  18668. * @type {Array<Bone>}
  18669. */
  18670. this.bones = bones.slice( 0 );
  18671. /**
  18672. * An array of bone inverse matrices.
  18673. *
  18674. * @type {Array<Matrix4>}
  18675. */
  18676. this.boneInverses = boneInverses;
  18677. /**
  18678. * An array buffer holding the bone data.
  18679. * Input data for {@link Skeleton#boneTexture}.
  18680. *
  18681. * @type {?Float32Array}
  18682. * @default null
  18683. */
  18684. this.boneMatrices = null;
  18685. /**
  18686. * A texture holding the bone data for use
  18687. * in the vertex shader.
  18688. *
  18689. * @type {?DataTexture}
  18690. * @default null
  18691. */
  18692. this.boneTexture = null;
  18693. this.init();
  18694. }
  18695. /**
  18696. * Initializes the skeleton. This method gets automatically called by the constructor
  18697. * but depending on how the skeleton is created it might be necessary to call this method
  18698. * manually.
  18699. */
  18700. init() {
  18701. const bones = this.bones;
  18702. const boneInverses = this.boneInverses;
  18703. this.boneMatrices = new Float32Array( bones.length * 16 );
  18704. // calculate inverse bone matrices if necessary
  18705. if ( boneInverses.length === 0 ) {
  18706. this.calculateInverses();
  18707. } else {
  18708. // handle special case
  18709. if ( bones.length !== boneInverses.length ) {
  18710. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18711. this.boneInverses = [];
  18712. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18713. this.boneInverses.push( new Matrix4() );
  18714. }
  18715. }
  18716. }
  18717. }
  18718. /**
  18719. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  18720. * and fills it with new matrices.
  18721. */
  18722. calculateInverses() {
  18723. this.boneInverses.length = 0;
  18724. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18725. const inverse = new Matrix4();
  18726. if ( this.bones[ i ] ) {
  18727. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18728. }
  18729. this.boneInverses.push( inverse );
  18730. }
  18731. }
  18732. /**
  18733. * Resets the skeleton to the base pose.
  18734. */
  18735. pose() {
  18736. // recover the bind-time world matrices
  18737. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18738. const bone = this.bones[ i ];
  18739. if ( bone ) {
  18740. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18741. }
  18742. }
  18743. // compute the local matrices, positions, rotations and scales
  18744. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18745. const bone = this.bones[ i ];
  18746. if ( bone ) {
  18747. if ( bone.parent && bone.parent.isBone ) {
  18748. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18749. bone.matrix.multiply( bone.matrixWorld );
  18750. } else {
  18751. bone.matrix.copy( bone.matrixWorld );
  18752. }
  18753. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18754. }
  18755. }
  18756. }
  18757. /**
  18758. * Resets the skeleton to the base pose.
  18759. */
  18760. update() {
  18761. const bones = this.bones;
  18762. const boneInverses = this.boneInverses;
  18763. const boneMatrices = this.boneMatrices;
  18764. const boneTexture = this.boneTexture;
  18765. // flatten bone matrices to array
  18766. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18767. // compute the offset between the current and the original transform
  18768. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18769. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18770. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18771. }
  18772. if ( boneTexture !== null ) {
  18773. boneTexture.needsUpdate = true;
  18774. }
  18775. }
  18776. /**
  18777. * Returns a new skeleton with copied values from this instance.
  18778. *
  18779. * @return {Skeleton} A clone of this instance.
  18780. */
  18781. clone() {
  18782. return new Skeleton( this.bones, this.boneInverses );
  18783. }
  18784. /**
  18785. * Computes a data texture for passing bone data to the vertex shader.
  18786. *
  18787. * @return {Skeleton} A reference of this instance.
  18788. */
  18789. computeBoneTexture() {
  18790. // layout (1 matrix = 4 pixels)
  18791. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18792. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18793. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18794. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18795. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18796. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18797. size = Math.ceil( size / 4 ) * 4;
  18798. size = Math.max( size, 4 );
  18799. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18800. boneMatrices.set( this.boneMatrices ); // copy current values
  18801. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18802. boneTexture.needsUpdate = true;
  18803. this.boneMatrices = boneMatrices;
  18804. this.boneTexture = boneTexture;
  18805. return this;
  18806. }
  18807. /**
  18808. * Searches through the skeleton's bone array and returns the first with a
  18809. * matching name.
  18810. *
  18811. * @param {string} name - The name of the bone.
  18812. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  18813. */
  18814. getBoneByName( name ) {
  18815. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18816. const bone = this.bones[ i ];
  18817. if ( bone.name === name ) {
  18818. return bone;
  18819. }
  18820. }
  18821. return undefined;
  18822. }
  18823. /**
  18824. * Frees the GPU-related resources allocated by this instance. Call this
  18825. * method whenever this instance is no longer used in your app.
  18826. */
  18827. dispose( ) {
  18828. if ( this.boneTexture !== null ) {
  18829. this.boneTexture.dispose();
  18830. this.boneTexture = null;
  18831. }
  18832. }
  18833. /**
  18834. * Setups the skeleton by the given JSON and bones.
  18835. *
  18836. * @param {Object} json - The skeleton as serialized JSON.
  18837. * @param {Object<string, Bone>} bones - An array of bones.
  18838. * @return {Skeleton} A reference of this instance.
  18839. */
  18840. fromJSON( json, bones ) {
  18841. this.uuid = json.uuid;
  18842. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18843. const uuid = json.bones[ i ];
  18844. let bone = bones[ uuid ];
  18845. if ( bone === undefined ) {
  18846. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18847. bone = new Bone();
  18848. }
  18849. this.bones.push( bone );
  18850. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18851. }
  18852. this.init();
  18853. return this;
  18854. }
  18855. /**
  18856. * Serializes the skeleton into JSON.
  18857. *
  18858. * @return {Object} A JSON object representing the serialized skeleton.
  18859. * @see {@link ObjectLoader#parse}
  18860. */
  18861. toJSON() {
  18862. const data = {
  18863. metadata: {
  18864. version: 4.7,
  18865. type: 'Skeleton',
  18866. generator: 'Skeleton.toJSON'
  18867. },
  18868. bones: [],
  18869. boneInverses: []
  18870. };
  18871. data.uuid = this.uuid;
  18872. const bones = this.bones;
  18873. const boneInverses = this.boneInverses;
  18874. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18875. const bone = bones[ i ];
  18876. data.bones.push( bone.uuid );
  18877. const boneInverse = boneInverses[ i ];
  18878. data.boneInverses.push( boneInverse.toArray() );
  18879. }
  18880. return data;
  18881. }
  18882. }
  18883. /**
  18884. * An instanced version of a buffer attribute.
  18885. *
  18886. * @augments BufferAttribute
  18887. */
  18888. class InstancedBufferAttribute extends BufferAttribute {
  18889. /**
  18890. * Constructs a new instanced buffer attribute.
  18891. *
  18892. * @param {TypedArray} array - The array holding the attribute data.
  18893. * @param {number} itemSize - The item size.
  18894. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  18895. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  18896. */
  18897. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18898. super( array, itemSize, normalized );
  18899. /**
  18900. * This flag can be used for type testing.
  18901. *
  18902. * @type {boolean}
  18903. * @readonly
  18904. * @default true
  18905. */
  18906. this.isInstancedBufferAttribute = true;
  18907. /**
  18908. * Defines how often a value of this buffer attribute should be repeated. A
  18909. * value of one means that each value of the instanced attribute is used for
  18910. * a single instance. A value of two means that each value is used for two
  18911. * consecutive instances (and so on).
  18912. *
  18913. * @type {number}
  18914. * @default 1
  18915. */
  18916. this.meshPerAttribute = meshPerAttribute;
  18917. }
  18918. copy( source ) {
  18919. super.copy( source );
  18920. this.meshPerAttribute = source.meshPerAttribute;
  18921. return this;
  18922. }
  18923. toJSON() {
  18924. const data = super.toJSON();
  18925. data.meshPerAttribute = this.meshPerAttribute;
  18926. data.isInstancedBufferAttribute = true;
  18927. return data;
  18928. }
  18929. }
  18930. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18931. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18932. const _instanceIntersects = [];
  18933. const _box3 = /*@__PURE__*/ new Box3();
  18934. const _identity = /*@__PURE__*/ new Matrix4();
  18935. const _mesh$1 = /*@__PURE__*/ new Mesh();
  18936. const _sphere$4 = /*@__PURE__*/ new Sphere();
  18937. /**
  18938. * A special version of a mesh with instanced rendering support. Use
  18939. * this class if you have to render a large number of objects with the same
  18940. * geometry and material(s) but with different world transformations. The usage
  18941. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  18942. * improve the overall rendering performance in your application.
  18943. *
  18944. * @augments Mesh
  18945. */
  18946. class InstancedMesh extends Mesh {
  18947. /**
  18948. * Constructs a new instanced mesh.
  18949. *
  18950. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18951. * @param {Material|Array<Material>} [material] - The mesh material.
  18952. * @param {number} count - The number of instances.
  18953. */
  18954. constructor( geometry, material, count ) {
  18955. super( geometry, material );
  18956. /**
  18957. * This flag can be used for type testing.
  18958. *
  18959. * @type {boolean}
  18960. * @readonly
  18961. * @default true
  18962. */
  18963. this.isInstancedMesh = true;
  18964. /**
  18965. * Represents the local transformation of all instances. You have to set its
  18966. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18967. * via {@link InstancedMesh#setMatrixAt}.
  18968. *
  18969. * @type {InstancedBufferAttribute}
  18970. */
  18971. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18972. /**
  18973. * Represents the color of all instances. You have to set its
  18974. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18975. * via {@link InstancedMesh#setColorAt}.
  18976. *
  18977. * @type {?InstancedBufferAttribute}
  18978. * @default null
  18979. */
  18980. this.instanceColor = null;
  18981. /**
  18982. * Represents the morph target weights of all instances. You have to set its
  18983. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  18984. * via {@link InstancedMesh#setMorphAt}.
  18985. *
  18986. * @type {?DataTexture}
  18987. * @default null
  18988. */
  18989. this.morphTexture = null;
  18990. /**
  18991. * The number of instances.
  18992. *
  18993. * @type {number}
  18994. */
  18995. this.count = count;
  18996. /**
  18997. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  18998. *
  18999. * @type {?Box3}
  19000. * @default null
  19001. */
  19002. this.boundingBox = null;
  19003. /**
  19004. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  19005. *
  19006. * @type {?Sphere}
  19007. * @default null
  19008. */
  19009. this.boundingSphere = null;
  19010. for ( let i = 0; i < count; i ++ ) {
  19011. this.setMatrixAt( i, _identity );
  19012. }
  19013. }
  19014. /**
  19015. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  19016. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  19017. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19018. */
  19019. computeBoundingBox() {
  19020. const geometry = this.geometry;
  19021. const count = this.count;
  19022. if ( this.boundingBox === null ) {
  19023. this.boundingBox = new Box3();
  19024. }
  19025. if ( geometry.boundingBox === null ) {
  19026. geometry.computeBoundingBox();
  19027. }
  19028. this.boundingBox.makeEmpty();
  19029. for ( let i = 0; i < count; i ++ ) {
  19030. this.getMatrixAt( i, _instanceLocalMatrix );
  19031. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19032. this.boundingBox.union( _box3 );
  19033. }
  19034. }
  19035. /**
  19036. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  19037. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  19038. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19039. */
  19040. computeBoundingSphere() {
  19041. const geometry = this.geometry;
  19042. const count = this.count;
  19043. if ( this.boundingSphere === null ) {
  19044. this.boundingSphere = new Sphere();
  19045. }
  19046. if ( geometry.boundingSphere === null ) {
  19047. geometry.computeBoundingSphere();
  19048. }
  19049. this.boundingSphere.makeEmpty();
  19050. for ( let i = 0; i < count; i ++ ) {
  19051. this.getMatrixAt( i, _instanceLocalMatrix );
  19052. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19053. this.boundingSphere.union( _sphere$4 );
  19054. }
  19055. }
  19056. copy( source, recursive ) {
  19057. super.copy( source, recursive );
  19058. this.instanceMatrix.copy( source.instanceMatrix );
  19059. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  19060. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19061. this.count = source.count;
  19062. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19063. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19064. return this;
  19065. }
  19066. /**
  19067. * Gets the color of the defined instance.
  19068. *
  19069. * @param {number} index - The instance index.
  19070. * @param {Color} color - The target object that is used to store the method's result.
  19071. */
  19072. getColorAt( index, color ) {
  19073. color.fromArray( this.instanceColor.array, index * 3 );
  19074. }
  19075. /**
  19076. * Gets the local transformation matrix of the defined instance.
  19077. *
  19078. * @param {number} index - The instance index.
  19079. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19080. */
  19081. getMatrixAt( index, matrix ) {
  19082. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19083. }
  19084. /**
  19085. * Gets the morph target weights of the defined instance.
  19086. *
  19087. * @param {number} index - The instance index.
  19088. * @param {Mesh} object - The target object that is used to store the method's result.
  19089. */
  19090. getMorphAt( index, object ) {
  19091. const objectInfluences = object.morphTargetInfluences;
  19092. const array = this.morphTexture.source.data.data;
  19093. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  19094. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  19095. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19096. objectInfluences[ i ] = array[ dataIndex + i ];
  19097. }
  19098. }
  19099. raycast( raycaster, intersects ) {
  19100. const matrixWorld = this.matrixWorld;
  19101. const raycastTimes = this.count;
  19102. _mesh$1.geometry = this.geometry;
  19103. _mesh$1.material = this.material;
  19104. if ( _mesh$1.material === undefined ) return;
  19105. // test with bounding sphere first
  19106. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19107. _sphere$4.copy( this.boundingSphere );
  19108. _sphere$4.applyMatrix4( matrixWorld );
  19109. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  19110. // now test each instance
  19111. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19112. // calculate the world matrix for each instance
  19113. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19114. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19115. // the mesh represents this single instance
  19116. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19117. _mesh$1.raycast( raycaster, _instanceIntersects );
  19118. // process the result of raycast
  19119. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19120. const intersect = _instanceIntersects[ i ];
  19121. intersect.instanceId = instanceId;
  19122. intersect.object = this;
  19123. intersects.push( intersect );
  19124. }
  19125. _instanceIntersects.length = 0;
  19126. }
  19127. }
  19128. /**
  19129. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  19130. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  19131. *
  19132. * @param {number} index - The instance index.
  19133. * @param {Color} color - The instance color.
  19134. */
  19135. setColorAt( index, color ) {
  19136. if ( this.instanceColor === null ) {
  19137. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  19138. }
  19139. color.toArray( this.instanceColor.array, index * 3 );
  19140. }
  19141. /**
  19142. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  19143. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  19144. *
  19145. * @param {number} index - The instance index.
  19146. * @param {Matrix4} matrix - The local transformation.
  19147. */
  19148. setMatrixAt( index, matrix ) {
  19149. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19150. }
  19151. /**
  19152. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  19153. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  19154. *
  19155. * @param {number} index - The instance index.
  19156. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  19157. * of a single instance.
  19158. */
  19159. setMorphAt( index, object ) {
  19160. const objectInfluences = object.morphTargetInfluences;
  19161. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  19162. if ( this.morphTexture === null ) {
  19163. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  19164. }
  19165. const array = this.morphTexture.source.data.data;
  19166. let morphInfluencesSum = 0;
  19167. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19168. morphInfluencesSum += objectInfluences[ i ];
  19169. }
  19170. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  19171. const dataIndex = len * index;
  19172. array[ dataIndex ] = morphBaseInfluence;
  19173. array.set( objectInfluences, dataIndex + 1 );
  19174. }
  19175. updateMorphTargets() {
  19176. }
  19177. /**
  19178. * Frees the GPU-related resources allocated by this instance. Call this
  19179. * method whenever this instance is no longer used in your app.
  19180. */
  19181. dispose() {
  19182. this.dispatchEvent( { type: 'dispose' } );
  19183. if ( this.morphTexture !== null ) {
  19184. this.morphTexture.dispose();
  19185. this.morphTexture = null;
  19186. }
  19187. }
  19188. }
  19189. const _vector1 = /*@__PURE__*/ new Vector3();
  19190. const _vector2 = /*@__PURE__*/ new Vector3();
  19191. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  19192. /**
  19193. * A two dimensional surface that extends infinitely in 3D space, represented
  19194. * in [Hessian normal form]{@link http://mathworld.wolfram.com/HessianNormalForm.html}
  19195. * by a unit length normal vector and a constant.
  19196. */
  19197. class Plane {
  19198. /**
  19199. * Constructs a new plane.
  19200. *
  19201. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  19202. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  19203. */
  19204. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  19205. /**
  19206. * This flag can be used for type testing.
  19207. *
  19208. * @type {boolean}
  19209. * @readonly
  19210. * @default true
  19211. */
  19212. this.isPlane = true;
  19213. /**
  19214. * A unit length vector defining the normal of the plane.
  19215. *
  19216. * @type {Vector3}
  19217. */
  19218. this.normal = normal;
  19219. /**
  19220. * The signed distance from the origin to the plane.
  19221. *
  19222. * @type {number}
  19223. * @default 0
  19224. */
  19225. this.constant = constant;
  19226. }
  19227. /**
  19228. * Sets the plane components by copying the given values.
  19229. *
  19230. * @param {Vector3} normal - The normal.
  19231. * @param {number} constant - The constant.
  19232. * @return {Plane} A reference to this plane.
  19233. */
  19234. set( normal, constant ) {
  19235. this.normal.copy( normal );
  19236. this.constant = constant;
  19237. return this;
  19238. }
  19239. /**
  19240. * Sets the plane components by defining `x`, `y`, `z` as the
  19241. * plane normal and `w` as the constant.
  19242. *
  19243. * @param {number} x - The value for the normal's x component.
  19244. * @param {number} y - The value for the normal's y component.
  19245. * @param {number} z - The value for the normal's z component.
  19246. * @param {number} w - The constant value.
  19247. * @return {Plane} A reference to this plane.
  19248. */
  19249. setComponents( x, y, z, w ) {
  19250. this.normal.set( x, y, z );
  19251. this.constant = w;
  19252. return this;
  19253. }
  19254. /**
  19255. * Sets the plane from the given normal and coplanar point (that is a point
  19256. * that lies onto the plane).
  19257. *
  19258. * @param {Vector3} normal - The normal.
  19259. * @param {Vector3} point - A coplanar point.
  19260. * @return {Plane} A reference to this plane.
  19261. */
  19262. setFromNormalAndCoplanarPoint( normal, point ) {
  19263. this.normal.copy( normal );
  19264. this.constant = - point.dot( this.normal );
  19265. return this;
  19266. }
  19267. /**
  19268. * Sets the plane from three coplanar points. The winding order is
  19269. * assumed to be counter-clockwise, and determines the direction of
  19270. * the plane normal.
  19271. *
  19272. * @param {Vector3} a - The first coplanar point.
  19273. * @param {Vector3} b - The second coplanar point.
  19274. * @param {Vector3} c - The third coplanar point.
  19275. * @return {Plane} A reference to this plane.
  19276. */
  19277. setFromCoplanarPoints( a, b, c ) {
  19278. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  19279. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  19280. this.setFromNormalAndCoplanarPoint( normal, a );
  19281. return this;
  19282. }
  19283. /**
  19284. * Copies the values of the given plane to this instance.
  19285. *
  19286. * @param {Plane} plane - The plane to copy.
  19287. * @return {Plane} A reference to this plane.
  19288. */
  19289. copy( plane ) {
  19290. this.normal.copy( plane.normal );
  19291. this.constant = plane.constant;
  19292. return this;
  19293. }
  19294. /**
  19295. * Normalizes the plane normal and adjusts the constant accordingly.
  19296. *
  19297. * @return {Plane} A reference to this plane.
  19298. */
  19299. normalize() {
  19300. // Note: will lead to a divide by zero if the plane is invalid.
  19301. const inverseNormalLength = 1.0 / this.normal.length();
  19302. this.normal.multiplyScalar( inverseNormalLength );
  19303. this.constant *= inverseNormalLength;
  19304. return this;
  19305. }
  19306. /**
  19307. * Negates both the plane normal and the constant.
  19308. *
  19309. * @return {Plane} A reference to this plane.
  19310. */
  19311. negate() {
  19312. this.constant *= -1;
  19313. this.normal.negate();
  19314. return this;
  19315. }
  19316. /**
  19317. * Returns the signed distance from the given point to this plane.
  19318. *
  19319. * @param {Vector3} point - The point to compute the distance for.
  19320. * @return {number} The signed distance.
  19321. */
  19322. distanceToPoint( point ) {
  19323. return this.normal.dot( point ) + this.constant;
  19324. }
  19325. /**
  19326. * Returns the signed distance from the given sphere to this plane.
  19327. *
  19328. * @param {Sphere} sphere - The sphere to compute the distance for.
  19329. * @return {number} The signed distance.
  19330. */
  19331. distanceToSphere( sphere ) {
  19332. return this.distanceToPoint( sphere.center ) - sphere.radius;
  19333. }
  19334. /**
  19335. * Projects a the given point onto the plane.
  19336. *
  19337. * @param {Vector3} point - The point to project.
  19338. * @param {Vector3} target - The target vector that is used to store the method's result.
  19339. * @return {Vector3} The projected point on the plane.
  19340. */
  19341. projectPoint( point, target ) {
  19342. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  19343. }
  19344. /**
  19345. * Returns the intersection point of the passed line and the plane. Returns
  19346. * `null` if the line does not intersect. Returns the line's starting point if
  19347. * the line is coplanar with the plane.
  19348. *
  19349. * @param {Line3} line - The line to compute the intersection for.
  19350. * @param {Vector3} target - The target vector that is used to store the method's result.
  19351. * @return {?Vector3} The intersection point.
  19352. */
  19353. intersectLine( line, target ) {
  19354. const direction = line.delta( _vector1 );
  19355. const denominator = this.normal.dot( direction );
  19356. if ( denominator === 0 ) {
  19357. // line is coplanar, return origin
  19358. if ( this.distanceToPoint( line.start ) === 0 ) {
  19359. return target.copy( line.start );
  19360. }
  19361. // Unsure if this is the correct method to handle this case.
  19362. return null;
  19363. }
  19364. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  19365. if ( t < 0 || t > 1 ) {
  19366. return null;
  19367. }
  19368. return target.copy( line.start ).addScaledVector( direction, t );
  19369. }
  19370. /**
  19371. * Returns `true` if the given line segment intersects with (passes through) the plane.
  19372. *
  19373. * @param {Line3} line - The line to test.
  19374. * @return {boolean} Whether the given line segment intersects with the plane or not.
  19375. */
  19376. intersectsLine( line ) {
  19377. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  19378. const startSign = this.distanceToPoint( line.start );
  19379. const endSign = this.distanceToPoint( line.end );
  19380. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  19381. }
  19382. /**
  19383. * Returns `true` if the given bounding box intersects with the plane.
  19384. *
  19385. * @param {Box3} box - The bounding box to test.
  19386. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  19387. */
  19388. intersectsBox( box ) {
  19389. return box.intersectsPlane( this );
  19390. }
  19391. /**
  19392. * Returns `true` if the given bounding sphere intersects with the plane.
  19393. *
  19394. * @param {Sphere} sphere - The bounding sphere to test.
  19395. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  19396. */
  19397. intersectsSphere( sphere ) {
  19398. return sphere.intersectsPlane( this );
  19399. }
  19400. /**
  19401. * Returns a coplanar vector to the plane, by calculating the
  19402. * projection of the normal at the origin onto the plane.
  19403. *
  19404. * @param {Vector3} target - The target vector that is used to store the method's result.
  19405. * @return {Vector3} The coplanar point.
  19406. */
  19407. coplanarPoint( target ) {
  19408. return target.copy( this.normal ).multiplyScalar( - this.constant );
  19409. }
  19410. /**
  19411. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  19412. *
  19413. * The optional normal matrix can be pre-computed like so:
  19414. * ```js
  19415. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  19416. * ```
  19417. *
  19418. * @param {Matrix4} matrix - The transformation matrix.
  19419. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  19420. * @return {Plane} A reference to this plane.
  19421. */
  19422. applyMatrix4( matrix, optionalNormalMatrix ) {
  19423. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  19424. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  19425. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  19426. this.constant = - referencePoint.dot( normal );
  19427. return this;
  19428. }
  19429. /**
  19430. * Translates the plane by the distance defined by the given offset vector.
  19431. * Note that this only affects the plane constant and will not affect the normal vector.
  19432. *
  19433. * @param {Vector3} offset - The offset vector.
  19434. * @return {Plane} A reference to this plane.
  19435. */
  19436. translate( offset ) {
  19437. this.constant -= offset.dot( this.normal );
  19438. return this;
  19439. }
  19440. /**
  19441. * Returns `true` if this plane is equal with the given one.
  19442. *
  19443. * @param {Plane} plane - The plane to test for equality.
  19444. * @return {boolean} Whether this plane is equal with the given one.
  19445. */
  19446. equals( plane ) {
  19447. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  19448. }
  19449. /**
  19450. * Returns a new plane with copied values from this instance.
  19451. *
  19452. * @return {Plane} A clone of this instance.
  19453. */
  19454. clone() {
  19455. return new this.constructor().copy( this );
  19456. }
  19457. }
  19458. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19459. const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 );
  19460. const _vector$6 = /*@__PURE__*/ new Vector3();
  19461. /**
  19462. * Frustums are used to determine what is inside the camera's field of view.
  19463. * They help speed up the rendering process - objects which lie outside a camera's
  19464. * frustum can safely be excluded from rendering.
  19465. *
  19466. * This class is mainly intended for use internally by a renderer.
  19467. */
  19468. class Frustum {
  19469. /**
  19470. * Constructs a new frustum.
  19471. *
  19472. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19473. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19474. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19475. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19476. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19477. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19478. */
  19479. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  19480. /**
  19481. * This array holds the planes that enclose the frustum.
  19482. *
  19483. * @type {Array<Plane>}
  19484. */
  19485. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  19486. }
  19487. /**
  19488. * Sets the frustum planes by copying the given planes.
  19489. *
  19490. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19491. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19492. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19493. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19494. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19495. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19496. * @return {Frustum} A reference to this frustum.
  19497. */
  19498. set( p0, p1, p2, p3, p4, p5 ) {
  19499. const planes = this.planes;
  19500. planes[ 0 ].copy( p0 );
  19501. planes[ 1 ].copy( p1 );
  19502. planes[ 2 ].copy( p2 );
  19503. planes[ 3 ].copy( p3 );
  19504. planes[ 4 ].copy( p4 );
  19505. planes[ 5 ].copy( p5 );
  19506. return this;
  19507. }
  19508. /**
  19509. * Copies the values of the given frustum to this instance.
  19510. *
  19511. * @param {Frustum} frustum - The frustum to copy.
  19512. * @return {Frustum} A reference to this frustum.
  19513. */
  19514. copy( frustum ) {
  19515. const planes = this.planes;
  19516. for ( let i = 0; i < 6; i ++ ) {
  19517. planes[ i ].copy( frustum.planes[ i ] );
  19518. }
  19519. return this;
  19520. }
  19521. /**
  19522. * Sets the frustum planes from the given projection matrix.
  19523. *
  19524. * @param {Matrix4} m - The projection matrix.
  19525. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  19526. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  19527. * @return {Frustum} A reference to this frustum.
  19528. */
  19529. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  19530. const planes = this.planes;
  19531. const me = m.elements;
  19532. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  19533. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  19534. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  19535. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  19536. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  19537. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  19538. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  19539. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  19540. if ( reversedDepth ) {
  19541. planes[ 4 ].setComponents( me2, me6, me10, me14 ).normalize(); // far
  19542. planes[ 5 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // near
  19543. } else {
  19544. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // far
  19545. if ( coordinateSystem === WebGLCoordinateSystem ) {
  19546. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); // near
  19547. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  19548. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); // near
  19549. } else {
  19550. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  19551. }
  19552. }
  19553. return this;
  19554. }
  19555. /**
  19556. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  19557. *
  19558. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  19559. *
  19560. * @param {Object3D} object - The 3D object to test.
  19561. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  19562. */
  19563. intersectsObject( object ) {
  19564. if ( object.boundingSphere !== undefined ) {
  19565. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  19566. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  19567. } else {
  19568. const geometry = object.geometry;
  19569. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19570. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  19571. }
  19572. return this.intersectsSphere( _sphere$3 );
  19573. }
  19574. /**
  19575. * Returns `true` if the given sprite is intersecting this frustum.
  19576. *
  19577. * @param {Sprite} sprite - The sprite to test.
  19578. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  19579. */
  19580. intersectsSprite( sprite ) {
  19581. _sphere$3.center.set( 0, 0, 0 );
  19582. const offset = _defaultSpriteCenter.distanceTo( sprite.center );
  19583. _sphere$3.radius = 0.7071067811865476 + offset;
  19584. _sphere$3.applyMatrix4( sprite.matrixWorld );
  19585. return this.intersectsSphere( _sphere$3 );
  19586. }
  19587. /**
  19588. * Returns `true` if the given bounding sphere is intersecting this frustum.
  19589. *
  19590. * @param {Sphere} sphere - The bounding sphere to test.
  19591. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  19592. */
  19593. intersectsSphere( sphere ) {
  19594. const planes = this.planes;
  19595. const center = sphere.center;
  19596. const negRadius = - sphere.radius;
  19597. for ( let i = 0; i < 6; i ++ ) {
  19598. const distance = planes[ i ].distanceToPoint( center );
  19599. if ( distance < negRadius ) {
  19600. return false;
  19601. }
  19602. }
  19603. return true;
  19604. }
  19605. /**
  19606. * Returns `true` if the given bounding box is intersecting this frustum.
  19607. *
  19608. * @param {Box3} box - The bounding box to test.
  19609. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  19610. */
  19611. intersectsBox( box ) {
  19612. const planes = this.planes;
  19613. for ( let i = 0; i < 6; i ++ ) {
  19614. const plane = planes[ i ];
  19615. // corner at max distance
  19616. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  19617. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  19618. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  19619. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  19620. return false;
  19621. }
  19622. }
  19623. return true;
  19624. }
  19625. /**
  19626. * Returns `true` if the given point lies within the frustum.
  19627. *
  19628. * @param {Vector3} point - The point to test.
  19629. * @return {boolean} Whether the point lies within this frustum or not.
  19630. */
  19631. containsPoint( point ) {
  19632. const planes = this.planes;
  19633. for ( let i = 0; i < 6; i ++ ) {
  19634. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  19635. return false;
  19636. }
  19637. }
  19638. return true;
  19639. }
  19640. /**
  19641. * Returns a new frustum with copied values from this instance.
  19642. *
  19643. * @return {Frustum} A clone of this instance.
  19644. */
  19645. clone() {
  19646. return new this.constructor().copy( this );
  19647. }
  19648. }
  19649. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  19650. const _frustum$1 = /*@__PURE__*/ new Frustum();
  19651. /**
  19652. * FrustumArray is used to determine if an object is visible in at least one camera
  19653. * from an array of cameras. This is particularly useful for multi-view renderers.
  19654. */
  19655. class FrustumArray {
  19656. /**
  19657. * Constructs a new frustum array.
  19658. *
  19659. */
  19660. constructor() {
  19661. /**
  19662. * The coordinate system to use.
  19663. *
  19664. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  19665. * @default WebGLCoordinateSystem
  19666. */
  19667. this.coordinateSystem = WebGLCoordinateSystem;
  19668. }
  19669. /**
  19670. * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
  19671. * from the camera array.
  19672. *
  19673. * @param {Object3D} object - The 3D object to test.
  19674. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19675. * @return {boolean} Whether the 3D object is visible in any camera.
  19676. */
  19677. intersectsObject( object, cameraArray ) {
  19678. if ( ! cameraArray.isArrayCamera || cameraArray.cameras.length === 0 ) {
  19679. return false;
  19680. }
  19681. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19682. const camera = cameraArray.cameras[ i ];
  19683. _projScreenMatrix$2.multiplyMatrices(
  19684. camera.projectionMatrix,
  19685. camera.matrixWorldInverse
  19686. );
  19687. _frustum$1.setFromProjectionMatrix(
  19688. _projScreenMatrix$2,
  19689. camera.coordinateSystem,
  19690. camera.reversedDepth
  19691. );
  19692. if ( _frustum$1.intersectsObject( object ) ) {
  19693. return true; // Object is visible in at least one camera
  19694. }
  19695. }
  19696. return false; // Not visible in any camera
  19697. }
  19698. /**
  19699. * Returns `true` if the given sprite is intersecting any frustum
  19700. * from the camera array.
  19701. *
  19702. * @param {Sprite} sprite - The sprite to test.
  19703. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19704. * @return {boolean} Whether the sprite is visible in any camera.
  19705. */
  19706. intersectsSprite( sprite, cameraArray ) {
  19707. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19708. return false;
  19709. }
  19710. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19711. const camera = cameraArray.cameras[ i ];
  19712. _projScreenMatrix$2.multiplyMatrices(
  19713. camera.projectionMatrix,
  19714. camera.matrixWorldInverse
  19715. );
  19716. _frustum$1.setFromProjectionMatrix(
  19717. _projScreenMatrix$2,
  19718. camera.coordinateSystem,
  19719. camera.reversedDepth
  19720. );
  19721. if ( _frustum$1.intersectsSprite( sprite ) ) {
  19722. return true; // Sprite is visible in at least one camera
  19723. }
  19724. }
  19725. return false; // Not visible in any camera
  19726. }
  19727. /**
  19728. * Returns `true` if the given bounding sphere is intersecting any frustum
  19729. * from the camera array.
  19730. *
  19731. * @param {Sphere} sphere - The bounding sphere to test.
  19732. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19733. * @return {boolean} Whether the sphere is visible in any camera.
  19734. */
  19735. intersectsSphere( sphere, cameraArray ) {
  19736. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19737. return false;
  19738. }
  19739. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19740. const camera = cameraArray.cameras[ i ];
  19741. _projScreenMatrix$2.multiplyMatrices(
  19742. camera.projectionMatrix,
  19743. camera.matrixWorldInverse
  19744. );
  19745. _frustum$1.setFromProjectionMatrix(
  19746. _projScreenMatrix$2,
  19747. camera.coordinateSystem,
  19748. camera.reversedDepth
  19749. );
  19750. if ( _frustum$1.intersectsSphere( sphere ) ) {
  19751. return true; // Sphere is visible in at least one camera
  19752. }
  19753. }
  19754. return false; // Not visible in any camera
  19755. }
  19756. /**
  19757. * Returns `true` if the given bounding box is intersecting any frustum
  19758. * from the camera array.
  19759. *
  19760. * @param {Box3} box - The bounding box to test.
  19761. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19762. * @return {boolean} Whether the box is visible in any camera.
  19763. */
  19764. intersectsBox( box, cameraArray ) {
  19765. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19766. return false;
  19767. }
  19768. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19769. const camera = cameraArray.cameras[ i ];
  19770. _projScreenMatrix$2.multiplyMatrices(
  19771. camera.projectionMatrix,
  19772. camera.matrixWorldInverse
  19773. );
  19774. _frustum$1.setFromProjectionMatrix(
  19775. _projScreenMatrix$2,
  19776. camera.coordinateSystem,
  19777. camera.reversedDepth
  19778. );
  19779. if ( _frustum$1.intersectsBox( box ) ) {
  19780. return true; // Box is visible in at least one camera
  19781. }
  19782. }
  19783. return false; // Not visible in any camera
  19784. }
  19785. /**
  19786. * Returns `true` if the given point lies within any frustum
  19787. * from the camera array.
  19788. *
  19789. * @param {Vector3} point - The point to test.
  19790. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19791. * @return {boolean} Whether the point is visible in any camera.
  19792. */
  19793. containsPoint( point, cameraArray ) {
  19794. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19795. return false;
  19796. }
  19797. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19798. const camera = cameraArray.cameras[ i ];
  19799. _projScreenMatrix$2.multiplyMatrices(
  19800. camera.projectionMatrix,
  19801. camera.matrixWorldInverse
  19802. );
  19803. _frustum$1.setFromProjectionMatrix(
  19804. _projScreenMatrix$2,
  19805. camera.coordinateSystem,
  19806. camera.reversedDepth
  19807. );
  19808. if ( _frustum$1.containsPoint( point ) ) {
  19809. return true; // Point is visible in at least one camera
  19810. }
  19811. }
  19812. return false; // Not visible in any camera
  19813. }
  19814. /**
  19815. * Returns a new frustum array with copied values from this instance.
  19816. *
  19817. * @return {FrustumArray} A clone of this instance.
  19818. */
  19819. clone() {
  19820. return new FrustumArray();
  19821. }
  19822. }
  19823. function ascIdSort( a, b ) {
  19824. return a - b;
  19825. }
  19826. function sortOpaque( a, b ) {
  19827. return a.z - b.z;
  19828. }
  19829. function sortTransparent( a, b ) {
  19830. return b.z - a.z;
  19831. }
  19832. class MultiDrawRenderList {
  19833. constructor() {
  19834. this.index = 0;
  19835. this.pool = [];
  19836. this.list = [];
  19837. }
  19838. push( start, count, z, index ) {
  19839. const pool = this.pool;
  19840. const list = this.list;
  19841. if ( this.index >= pool.length ) {
  19842. pool.push( {
  19843. start: -1,
  19844. count: -1,
  19845. z: -1,
  19846. index: -1,
  19847. } );
  19848. }
  19849. const item = pool[ this.index ];
  19850. list.push( item );
  19851. this.index ++;
  19852. item.start = start;
  19853. item.count = count;
  19854. item.z = z;
  19855. item.index = index;
  19856. }
  19857. reset() {
  19858. this.list.length = 0;
  19859. this.index = 0;
  19860. }
  19861. }
  19862. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  19863. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  19864. const _frustum = /*@__PURE__*/ new Frustum();
  19865. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  19866. const _box$1 = /*@__PURE__*/ new Box3();
  19867. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19868. const _vector$5 = /*@__PURE__*/ new Vector3();
  19869. const _forward$1 = /*@__PURE__*/ new Vector3();
  19870. const _temp = /*@__PURE__*/ new Vector3();
  19871. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19872. const _mesh = /*@__PURE__*/ new Mesh();
  19873. const _batchIntersects = [];
  19874. // copies data from attribute "src" into "target" starting at "targetOffset"
  19875. function copyAttributeData( src, target, targetOffset = 0 ) {
  19876. const itemSize = target.itemSize;
  19877. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19878. // use the component getters and setters if the array data cannot
  19879. // be copied directly
  19880. const vertexCount = src.count;
  19881. for ( let i = 0; i < vertexCount; i ++ ) {
  19882. for ( let c = 0; c < itemSize; c ++ ) {
  19883. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19884. }
  19885. }
  19886. } else {
  19887. // faster copy approach using typed array set function
  19888. target.array.set( src.array, targetOffset * itemSize );
  19889. }
  19890. target.needsUpdate = true;
  19891. }
  19892. // safely copies array contents to a potentially smaller array
  19893. function copyArrayContents( src, target ) {
  19894. if ( src.constructor !== target.constructor ) {
  19895. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  19896. const len = Math.min( src.length, target.length );
  19897. for ( let i = 0; i < len; i ++ ) {
  19898. target[ i ] = src[ i ];
  19899. }
  19900. } else {
  19901. // if the arrays use the same data layout we can use a fast block copy
  19902. const len = Math.min( src.length, target.length );
  19903. target.set( new src.constructor( src.buffer, 0, len ) );
  19904. }
  19905. }
  19906. /**
  19907. * A special version of a mesh with multi draw batch rendering support. Use
  19908. * this class if you have to render a large number of objects with the same
  19909. * material but with different geometries or world transformations. The usage of
  19910. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  19911. * rendering performance in your application.
  19912. *
  19913. * ```js
  19914. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  19915. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  19916. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  19917. *
  19918. * // initialize and add geometries into the batched mesh
  19919. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  19920. * const boxGeometryId = batchedMesh.addGeometry( box );
  19921. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  19922. *
  19923. * // create instances of those geometries
  19924. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  19925. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  19926. *
  19927. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  19928. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  19929. *
  19930. * // position the geometries
  19931. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  19932. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  19933. *
  19934. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  19935. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  19936. *
  19937. * scene.add( batchedMesh );
  19938. * ```
  19939. *
  19940. * @augments Mesh
  19941. */
  19942. class BatchedMesh extends Mesh {
  19943. /**
  19944. * Constructs a new batched mesh.
  19945. *
  19946. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  19947. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  19948. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  19949. * @param {Material|Array<Material>} [material] - The mesh material.
  19950. */
  19951. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19952. super( new BufferGeometry(), material );
  19953. /**
  19954. * This flag can be used for type testing.
  19955. *
  19956. * @type {boolean}
  19957. * @readonly
  19958. * @default true
  19959. */
  19960. this.isBatchedMesh = true;
  19961. /**
  19962. * When set ot `true`, the individual objects of a batch are frustum culled.
  19963. *
  19964. * @type {boolean}
  19965. * @default true
  19966. */
  19967. this.perObjectFrustumCulled = true;
  19968. /**
  19969. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  19970. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  19971. * rendered front to back.
  19972. *
  19973. * @type {boolean}
  19974. * @default true
  19975. */
  19976. this.sortObjects = true;
  19977. /**
  19978. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  19979. *
  19980. * @type {?Box3}
  19981. * @default null
  19982. */
  19983. this.boundingBox = null;
  19984. /**
  19985. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  19986. *
  19987. * @type {?Sphere}
  19988. * @default null
  19989. */
  19990. this.boundingSphere = null;
  19991. /**
  19992. * Takes a sort a function that is run before render. The function takes a list of instances to
  19993. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  19994. * sort with.
  19995. *
  19996. * @type {?Function}
  19997. * @default null
  19998. */
  19999. this.customSort = null;
  20000. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  20001. this._instanceInfo = [];
  20002. this._geometryInfo = [];
  20003. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  20004. this._availableInstanceIds = [];
  20005. this._availableGeometryIds = [];
  20006. // used to track where the next point is that geometry should be inserted
  20007. this._nextIndexStart = 0;
  20008. this._nextVertexStart = 0;
  20009. this._geometryCount = 0;
  20010. // flags
  20011. this._visibilityChanged = true;
  20012. this._geometryInitialized = false;
  20013. // cached user options
  20014. this._maxInstanceCount = maxInstanceCount;
  20015. this._maxVertexCount = maxVertexCount;
  20016. this._maxIndexCount = maxIndexCount;
  20017. // buffers for multi draw
  20018. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  20019. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  20020. this._multiDrawCount = 0;
  20021. this._multiDrawInstances = null;
  20022. // Local matrix per geometry by using data texture
  20023. this._matricesTexture = null;
  20024. this._indirectTexture = null;
  20025. this._colorsTexture = null;
  20026. this._initMatricesTexture();
  20027. this._initIndirectTexture();
  20028. }
  20029. /**
  20030. * The maximum number of individual instances that can be stored in the batch.
  20031. *
  20032. * @type {number}
  20033. * @readonly
  20034. */
  20035. get maxInstanceCount() {
  20036. return this._maxInstanceCount;
  20037. }
  20038. /**
  20039. * The instance count.
  20040. *
  20041. * @type {number}
  20042. * @readonly
  20043. */
  20044. get instanceCount() {
  20045. return this._instanceInfo.length - this._availableInstanceIds.length;
  20046. }
  20047. /**
  20048. * The number of unused vertices.
  20049. *
  20050. * @type {number}
  20051. * @readonly
  20052. */
  20053. get unusedVertexCount() {
  20054. return this._maxVertexCount - this._nextVertexStart;
  20055. }
  20056. /**
  20057. * The number of unused indices.
  20058. *
  20059. * @type {number}
  20060. * @readonly
  20061. */
  20062. get unusedIndexCount() {
  20063. return this._maxIndexCount - this._nextIndexStart;
  20064. }
  20065. _initMatricesTexture() {
  20066. // layout (1 matrix = 4 pixels)
  20067. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  20068. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  20069. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  20070. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  20071. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  20072. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  20073. size = Math.ceil( size / 4 ) * 4;
  20074. size = Math.max( size, 4 );
  20075. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  20076. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  20077. this._matricesTexture = matricesTexture;
  20078. }
  20079. _initIndirectTexture() {
  20080. let size = Math.sqrt( this._maxInstanceCount );
  20081. size = Math.ceil( size );
  20082. const indirectArray = new Uint32Array( size * size );
  20083. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  20084. this._indirectTexture = indirectTexture;
  20085. }
  20086. _initColorsTexture() {
  20087. let size = Math.sqrt( this._maxInstanceCount );
  20088. size = Math.ceil( size );
  20089. // 4 floats per RGBA pixel initialized to white
  20090. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  20091. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  20092. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  20093. this._colorsTexture = colorsTexture;
  20094. }
  20095. _initializeGeometry( reference ) {
  20096. const geometry = this.geometry;
  20097. const maxVertexCount = this._maxVertexCount;
  20098. const maxIndexCount = this._maxIndexCount;
  20099. if ( this._geometryInitialized === false ) {
  20100. for ( const attributeName in reference.attributes ) {
  20101. const srcAttribute = reference.getAttribute( attributeName );
  20102. const { array, itemSize, normalized } = srcAttribute;
  20103. const dstArray = new array.constructor( maxVertexCount * itemSize );
  20104. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  20105. geometry.setAttribute( attributeName, dstAttribute );
  20106. }
  20107. if ( reference.getIndex() !== null ) {
  20108. // Reserve last u16 index for primitive restart.
  20109. const indexArray = maxVertexCount > 65535
  20110. ? new Uint32Array( maxIndexCount )
  20111. : new Uint16Array( maxIndexCount );
  20112. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  20113. }
  20114. this._geometryInitialized = true;
  20115. }
  20116. }
  20117. // Make sure the geometry is compatible with the existing combined geometry attributes
  20118. _validateGeometry( geometry ) {
  20119. // check to ensure the geometries are using consistent attributes and indices
  20120. const batchGeometry = this.geometry;
  20121. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  20122. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  20123. }
  20124. for ( const attributeName in batchGeometry.attributes ) {
  20125. if ( ! geometry.hasAttribute( attributeName ) ) {
  20126. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  20127. }
  20128. const srcAttribute = geometry.getAttribute( attributeName );
  20129. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20130. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  20131. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  20132. }
  20133. }
  20134. }
  20135. /**
  20136. * Validates the instance defined by the given ID.
  20137. *
  20138. * @param {number} instanceId - The instance to validate.
  20139. */
  20140. validateInstanceId( instanceId ) {
  20141. const instanceInfo = this._instanceInfo;
  20142. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  20143. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  20144. }
  20145. }
  20146. /**
  20147. * Validates the geometry defined by the given ID.
  20148. *
  20149. * @param {number} geometryId - The geometry to validate.
  20150. */
  20151. validateGeometryId( geometryId ) {
  20152. const geometryInfoList = this._geometryInfo;
  20153. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20154. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  20155. }
  20156. }
  20157. /**
  20158. * Takes a sort a function that is run before render. The function takes a list of instances to
  20159. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  20160. *
  20161. * @param {Function} func - The custom sort function.
  20162. * @return {BatchedMesh} A reference to this batched mesh.
  20163. */
  20164. setCustomSort( func ) {
  20165. this.customSort = func;
  20166. return this;
  20167. }
  20168. /**
  20169. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  20170. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  20171. * otherwise they are `null`.
  20172. */
  20173. computeBoundingBox() {
  20174. if ( this.boundingBox === null ) {
  20175. this.boundingBox = new Box3();
  20176. }
  20177. const boundingBox = this.boundingBox;
  20178. const instanceInfo = this._instanceInfo;
  20179. boundingBox.makeEmpty();
  20180. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20181. if ( instanceInfo[ i ].active === false ) continue;
  20182. const geometryId = instanceInfo[ i ].geometryIndex;
  20183. this.getMatrixAt( i, _matrix$1 );
  20184. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  20185. boundingBox.union( _box$1 );
  20186. }
  20187. }
  20188. /**
  20189. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  20190. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  20191. * otherwise they are `null`.
  20192. */
  20193. computeBoundingSphere() {
  20194. if ( this.boundingSphere === null ) {
  20195. this.boundingSphere = new Sphere();
  20196. }
  20197. const boundingSphere = this.boundingSphere;
  20198. const instanceInfo = this._instanceInfo;
  20199. boundingSphere.makeEmpty();
  20200. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20201. if ( instanceInfo[ i ].active === false ) continue;
  20202. const geometryId = instanceInfo[ i ].geometryIndex;
  20203. this.getMatrixAt( i, _matrix$1 );
  20204. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20205. boundingSphere.union( _sphere$2 );
  20206. }
  20207. }
  20208. /**
  20209. * Adds a new instance to the batch using the geometry of the given ID and returns
  20210. * a new id referring to the new instance to be used by other functions.
  20211. *
  20212. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  20213. * @return {number} The instance ID.
  20214. */
  20215. addInstance( geometryId ) {
  20216. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  20217. // ensure we're not over geometry
  20218. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  20219. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  20220. }
  20221. const instanceInfo = {
  20222. visible: true,
  20223. active: true,
  20224. geometryIndex: geometryId,
  20225. };
  20226. let drawId = null;
  20227. // Prioritize using previously freed instance ids
  20228. if ( this._availableInstanceIds.length > 0 ) {
  20229. this._availableInstanceIds.sort( ascIdSort );
  20230. drawId = this._availableInstanceIds.shift();
  20231. this._instanceInfo[ drawId ] = instanceInfo;
  20232. } else {
  20233. drawId = this._instanceInfo.length;
  20234. this._instanceInfo.push( instanceInfo );
  20235. }
  20236. const matricesTexture = this._matricesTexture;
  20237. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  20238. matricesTexture.needsUpdate = true;
  20239. const colorsTexture = this._colorsTexture;
  20240. if ( colorsTexture ) {
  20241. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  20242. colorsTexture.needsUpdate = true;
  20243. }
  20244. this._visibilityChanged = true;
  20245. return drawId;
  20246. }
  20247. /**
  20248. * Adds the given geometry to the batch and returns the associated
  20249. * geometry id referring to it to be used in other functions.
  20250. *
  20251. * @param {BufferGeometry} geometry - The geometry to add.
  20252. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  20253. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  20254. * to set a new geometry at this index at a later time that is larger than the original geometry.
  20255. * Defaults to the length of the given geometry vertex buffer.
  20256. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  20257. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  20258. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  20259. * the length of the given geometry index buffer.
  20260. * @return {number} The geometry ID.
  20261. */
  20262. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  20263. this._initializeGeometry( geometry );
  20264. this._validateGeometry( geometry );
  20265. const geometryInfo = {
  20266. // geometry information
  20267. vertexStart: -1,
  20268. vertexCount: -1,
  20269. reservedVertexCount: -1,
  20270. indexStart: -1,
  20271. indexCount: -1,
  20272. reservedIndexCount: -1,
  20273. // draw range information
  20274. start: -1,
  20275. count: -1,
  20276. // state
  20277. boundingBox: null,
  20278. boundingSphere: null,
  20279. active: true,
  20280. };
  20281. const geometryInfoList = this._geometryInfo;
  20282. geometryInfo.vertexStart = this._nextVertexStart;
  20283. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  20284. const index = geometry.getIndex();
  20285. const hasIndex = index !== null;
  20286. if ( hasIndex ) {
  20287. geometryInfo.indexStart = this._nextIndexStart;
  20288. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  20289. }
  20290. if (
  20291. geometryInfo.indexStart !== -1 &&
  20292. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  20293. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  20294. ) {
  20295. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  20296. }
  20297. // update id
  20298. let geometryId;
  20299. if ( this._availableGeometryIds.length > 0 ) {
  20300. this._availableGeometryIds.sort( ascIdSort );
  20301. geometryId = this._availableGeometryIds.shift();
  20302. geometryInfoList[ geometryId ] = geometryInfo;
  20303. } else {
  20304. geometryId = this._geometryCount;
  20305. this._geometryCount ++;
  20306. geometryInfoList.push( geometryInfo );
  20307. }
  20308. // update the geometry
  20309. this.setGeometryAt( geometryId, geometry );
  20310. // increment the next geometry position
  20311. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  20312. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20313. return geometryId;
  20314. }
  20315. /**
  20316. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  20317. * is not enough space reserved for geometry. Calling this will change all instances that are
  20318. * rendering that geometry.
  20319. *
  20320. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  20321. * @param {BufferGeometry} geometry - The new geometry.
  20322. * @return {number} The geometry ID.
  20323. */
  20324. setGeometryAt( geometryId, geometry ) {
  20325. if ( geometryId >= this._geometryCount ) {
  20326. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  20327. }
  20328. this._validateGeometry( geometry );
  20329. const batchGeometry = this.geometry;
  20330. const hasIndex = batchGeometry.getIndex() !== null;
  20331. const dstIndex = batchGeometry.getIndex();
  20332. const srcIndex = geometry.getIndex();
  20333. const geometryInfo = this._geometryInfo[ geometryId ];
  20334. if (
  20335. hasIndex &&
  20336. srcIndex.count > geometryInfo.reservedIndexCount ||
  20337. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  20338. ) {
  20339. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  20340. }
  20341. // copy geometry buffer data over
  20342. const vertexStart = geometryInfo.vertexStart;
  20343. const reservedVertexCount = geometryInfo.reservedVertexCount;
  20344. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  20345. for ( const attributeName in batchGeometry.attributes ) {
  20346. // copy attribute data
  20347. const srcAttribute = geometry.getAttribute( attributeName );
  20348. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20349. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  20350. // fill the rest in with zeroes
  20351. const itemSize = srcAttribute.itemSize;
  20352. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  20353. const index = vertexStart + i;
  20354. for ( let c = 0; c < itemSize; c ++ ) {
  20355. dstAttribute.setComponent( index, c, 0 );
  20356. }
  20357. }
  20358. dstAttribute.needsUpdate = true;
  20359. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  20360. }
  20361. // copy index
  20362. if ( hasIndex ) {
  20363. const indexStart = geometryInfo.indexStart;
  20364. const reservedIndexCount = geometryInfo.reservedIndexCount;
  20365. geometryInfo.indexCount = geometry.getIndex().count;
  20366. // copy index data over
  20367. for ( let i = 0; i < srcIndex.count; i ++ ) {
  20368. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  20369. }
  20370. // fill the rest in with zeroes
  20371. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  20372. dstIndex.setX( indexStart + i, vertexStart );
  20373. }
  20374. dstIndex.needsUpdate = true;
  20375. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  20376. }
  20377. // update the draw range
  20378. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20379. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  20380. // store the bounding boxes
  20381. geometryInfo.boundingBox = null;
  20382. if ( geometry.boundingBox !== null ) {
  20383. geometryInfo.boundingBox = geometry.boundingBox.clone();
  20384. }
  20385. geometryInfo.boundingSphere = null;
  20386. if ( geometry.boundingSphere !== null ) {
  20387. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  20388. }
  20389. this._visibilityChanged = true;
  20390. return geometryId;
  20391. }
  20392. /**
  20393. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  20394. * this geometry will also be removed as a side effect.
  20395. *
  20396. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  20397. * @return {BatchedMesh} A reference to this batched mesh.
  20398. */
  20399. deleteGeometry( geometryId ) {
  20400. const geometryInfoList = this._geometryInfo;
  20401. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20402. return this;
  20403. }
  20404. // delete any instances associated with this geometry
  20405. const instanceInfo = this._instanceInfo;
  20406. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20407. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  20408. this.deleteInstance( i );
  20409. }
  20410. }
  20411. geometryInfoList[ geometryId ].active = false;
  20412. this._availableGeometryIds.push( geometryId );
  20413. this._visibilityChanged = true;
  20414. return this;
  20415. }
  20416. /**
  20417. * Deletes an existing instance from the batch using the given ID.
  20418. *
  20419. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20420. * @return {BatchedMesh} A reference to this batched mesh.
  20421. */
  20422. deleteInstance( instanceId ) {
  20423. this.validateInstanceId( instanceId );
  20424. this._instanceInfo[ instanceId ].active = false;
  20425. this._availableInstanceIds.push( instanceId );
  20426. this._visibilityChanged = true;
  20427. return this;
  20428. }
  20429. /**
  20430. * Repacks the sub geometries in [name] to remove any unused space remaining from
  20431. * previously deleted geometry, freeing up space to add new geometry.
  20432. *
  20433. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20434. * @return {BatchedMesh} A reference to this batched mesh.
  20435. */
  20436. optimize() {
  20437. // track the next indices to copy data to
  20438. let nextVertexStart = 0;
  20439. let nextIndexStart = 0;
  20440. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  20441. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  20442. const geometryInfoList = this._geometryInfo;
  20443. const indices = geometryInfoList
  20444. .map( ( e, i ) => i )
  20445. .sort( ( a, b ) => {
  20446. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  20447. } );
  20448. const geometry = this.geometry;
  20449. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  20450. // if a geometry range is inactive then don't copy anything
  20451. const index = indices[ i ];
  20452. const geometryInfo = geometryInfoList[ index ];
  20453. if ( geometryInfo.active === false ) {
  20454. continue;
  20455. }
  20456. // if a geometry contains an index buffer then shift it, as well
  20457. if ( geometry.index !== null ) {
  20458. if ( geometryInfo.indexStart !== nextIndexStart ) {
  20459. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  20460. const index = geometry.index;
  20461. const array = index.array;
  20462. // shift the index pointers based on how the vertex data will shift
  20463. // adjusting the index must happen first so the original vertex start value is available
  20464. const elementDelta = nextVertexStart - vertexStart;
  20465. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  20466. array[ j ] = array[ j ] + elementDelta;
  20467. }
  20468. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  20469. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  20470. geometryInfo.indexStart = nextIndexStart;
  20471. }
  20472. nextIndexStart += geometryInfo.reservedIndexCount;
  20473. }
  20474. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  20475. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  20476. const { vertexStart, reservedVertexCount } = geometryInfo;
  20477. const attributes = geometry.attributes;
  20478. for ( const key in attributes ) {
  20479. const attribute = attributes[ key ];
  20480. const { array, itemSize } = attribute;
  20481. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  20482. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  20483. }
  20484. geometryInfo.vertexStart = nextVertexStart;
  20485. }
  20486. nextVertexStart += geometryInfo.reservedVertexCount;
  20487. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20488. // step the next geometry points to the shifted position
  20489. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  20490. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20491. }
  20492. return this;
  20493. }
  20494. /**
  20495. * Returns the bounding box for the given geometry.
  20496. *
  20497. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  20498. * @param {Box3} target - The target object that is used to store the method's result.
  20499. * @return {Box3|null} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  20500. */
  20501. getBoundingBoxAt( geometryId, target ) {
  20502. if ( geometryId >= this._geometryCount ) {
  20503. return null;
  20504. }
  20505. // compute bounding box
  20506. const geometry = this.geometry;
  20507. const geometryInfo = this._geometryInfo[ geometryId ];
  20508. if ( geometryInfo.boundingBox === null ) {
  20509. const box = new Box3();
  20510. const index = geometry.index;
  20511. const position = geometry.attributes.position;
  20512. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20513. let iv = i;
  20514. if ( index ) {
  20515. iv = index.getX( iv );
  20516. }
  20517. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  20518. }
  20519. geometryInfo.boundingBox = box;
  20520. }
  20521. target.copy( geometryInfo.boundingBox );
  20522. return target;
  20523. }
  20524. /**
  20525. * Returns the bounding sphere for the given geometry.
  20526. *
  20527. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  20528. * @param {Sphere} target - The target object that is used to store the method's result.
  20529. * @return {Sphere|null} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  20530. */
  20531. getBoundingSphereAt( geometryId, target ) {
  20532. if ( geometryId >= this._geometryCount ) {
  20533. return null;
  20534. }
  20535. // compute bounding sphere
  20536. const geometry = this.geometry;
  20537. const geometryInfo = this._geometryInfo[ geometryId ];
  20538. if ( geometryInfo.boundingSphere === null ) {
  20539. const sphere = new Sphere();
  20540. this.getBoundingBoxAt( geometryId, _box$1 );
  20541. _box$1.getCenter( sphere.center );
  20542. const index = geometry.index;
  20543. const position = geometry.attributes.position;
  20544. let maxRadiusSq = 0;
  20545. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20546. let iv = i;
  20547. if ( index ) {
  20548. iv = index.getX( iv );
  20549. }
  20550. _vector$5.fromBufferAttribute( position, iv );
  20551. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20552. }
  20553. sphere.radius = Math.sqrt( maxRadiusSq );
  20554. geometryInfo.boundingSphere = sphere;
  20555. }
  20556. target.copy( geometryInfo.boundingSphere );
  20557. return target;
  20558. }
  20559. /**
  20560. * Sets the given local transformation matrix to the defined instance.
  20561. * Negatively scaled matrices are not supported.
  20562. *
  20563. * @param {number} instanceId - The ID of an instance to set the matrix of.
  20564. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  20565. * @return {BatchedMesh} A reference to this batched mesh.
  20566. */
  20567. setMatrixAt( instanceId, matrix ) {
  20568. this.validateInstanceId( instanceId );
  20569. const matricesTexture = this._matricesTexture;
  20570. const matricesArray = this._matricesTexture.image.data;
  20571. matrix.toArray( matricesArray, instanceId * 16 );
  20572. matricesTexture.needsUpdate = true;
  20573. return this;
  20574. }
  20575. /**
  20576. * Returns the local transformation matrix of the defined instance.
  20577. *
  20578. * @param {number} instanceId - The ID of an instance to get the matrix of.
  20579. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  20580. * @return {Matrix4} The instance's local transformation matrix.
  20581. */
  20582. getMatrixAt( instanceId, matrix ) {
  20583. this.validateInstanceId( instanceId );
  20584. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  20585. }
  20586. /**
  20587. * Sets the given color to the defined instance.
  20588. *
  20589. * @param {number} instanceId - The ID of an instance to set the color of.
  20590. * @param {Color} color - The color to set the instance to.
  20591. * @return {BatchedMesh} A reference to this batched mesh.
  20592. */
  20593. setColorAt( instanceId, color ) {
  20594. this.validateInstanceId( instanceId );
  20595. if ( this._colorsTexture === null ) {
  20596. this._initColorsTexture();
  20597. }
  20598. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  20599. this._colorsTexture.needsUpdate = true;
  20600. return this;
  20601. }
  20602. /**
  20603. * Returns the color of the defined instance.
  20604. *
  20605. * @param {number} instanceId - The ID of an instance to get the color of.
  20606. * @param {Color} color - The target object that is used to store the method's result.
  20607. * @return {Color} The instance's color.
  20608. */
  20609. getColorAt( instanceId, color ) {
  20610. this.validateInstanceId( instanceId );
  20611. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  20612. }
  20613. /**
  20614. * Sets the visibility of the instance.
  20615. *
  20616. * @param {number} instanceId - The id of the instance to set the visibility of.
  20617. * @param {boolean} visible - Whether the instance is visible or not.
  20618. * @return {BatchedMesh} A reference to this batched mesh.
  20619. */
  20620. setVisibleAt( instanceId, visible ) {
  20621. this.validateInstanceId( instanceId );
  20622. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  20623. return this;
  20624. }
  20625. this._instanceInfo[ instanceId ].visible = visible;
  20626. this._visibilityChanged = true;
  20627. return this;
  20628. }
  20629. /**
  20630. * Returns the visibility state of the defined instance.
  20631. *
  20632. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  20633. * @return {boolean} Whether the instance is visible or not.
  20634. */
  20635. getVisibleAt( instanceId ) {
  20636. this.validateInstanceId( instanceId );
  20637. return this._instanceInfo[ instanceId ].visible;
  20638. }
  20639. /**
  20640. * Sets the geometry ID of the instance at the given index.
  20641. *
  20642. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  20643. * @param {number} geometryId - The geometry ID to be use by the instance.
  20644. * @return {BatchedMesh} A reference to this batched mesh.
  20645. */
  20646. setGeometryIdAt( instanceId, geometryId ) {
  20647. this.validateInstanceId( instanceId );
  20648. this.validateGeometryId( geometryId );
  20649. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  20650. return this;
  20651. }
  20652. /**
  20653. * Returns the geometry ID of the defined instance.
  20654. *
  20655. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  20656. * @return {number} The instance's geometry ID.
  20657. */
  20658. getGeometryIdAt( instanceId ) {
  20659. this.validateInstanceId( instanceId );
  20660. return this._instanceInfo[ instanceId ].geometryIndex;
  20661. }
  20662. /**
  20663. * Get the range representing the subset of triangles related to the attached geometry,
  20664. * indicating the starting offset and count, or `null` if invalid.
  20665. *
  20666. * @param {number} geometryId - The id of the geometry to get the range of.
  20667. * @param {Object} [target] - The target object that is used to store the method's result.
  20668. * @return {{
  20669. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  20670. * indexStart:number,indexCount:number,reservedIndexCount:number,
  20671. * start:number,count:number
  20672. * }} The result object with range data.
  20673. */
  20674. getGeometryRangeAt( geometryId, target = {} ) {
  20675. this.validateGeometryId( geometryId );
  20676. const geometryInfo = this._geometryInfo[ geometryId ];
  20677. target.vertexStart = geometryInfo.vertexStart;
  20678. target.vertexCount = geometryInfo.vertexCount;
  20679. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  20680. target.indexStart = geometryInfo.indexStart;
  20681. target.indexCount = geometryInfo.indexCount;
  20682. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  20683. target.start = geometryInfo.start;
  20684. target.count = geometryInfo.count;
  20685. return target;
  20686. }
  20687. /**
  20688. * Resizes the necessary buffers to support the provided number of instances.
  20689. * If the provided arguments shrink the number of instances but there are not enough
  20690. * unused Ids at the end of the list then an error is thrown.
  20691. *
  20692. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  20693. */
  20694. setInstanceCount( maxInstanceCount ) {
  20695. // shrink the available instances as much as possible
  20696. const availableInstanceIds = this._availableInstanceIds;
  20697. const instanceInfo = this._instanceInfo;
  20698. availableInstanceIds.sort( ascIdSort );
  20699. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) {
  20700. instanceInfo.pop();
  20701. availableInstanceIds.pop();
  20702. }
  20703. // throw an error if it can't be shrunk to the desired size
  20704. if ( maxInstanceCount < instanceInfo.length ) {
  20705. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  20706. }
  20707. // copy the multi draw counts
  20708. const multiDrawCounts = new Int32Array( maxInstanceCount );
  20709. const multiDrawStarts = new Int32Array( maxInstanceCount );
  20710. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  20711. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  20712. this._multiDrawCounts = multiDrawCounts;
  20713. this._multiDrawStarts = multiDrawStarts;
  20714. this._maxInstanceCount = maxInstanceCount;
  20715. // update texture data for instance sampling
  20716. const indirectTexture = this._indirectTexture;
  20717. const matricesTexture = this._matricesTexture;
  20718. const colorsTexture = this._colorsTexture;
  20719. indirectTexture.dispose();
  20720. this._initIndirectTexture();
  20721. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  20722. matricesTexture.dispose();
  20723. this._initMatricesTexture();
  20724. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  20725. if ( colorsTexture ) {
  20726. colorsTexture.dispose();
  20727. this._initColorsTexture();
  20728. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  20729. }
  20730. }
  20731. /**
  20732. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  20733. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  20734. * end of the geometry attributes then an error is thrown.
  20735. *
  20736. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  20737. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  20738. */
  20739. setGeometrySize( maxVertexCount, maxIndexCount ) {
  20740. // Check if we can shrink to the requested vertex attribute size
  20741. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  20742. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  20743. if ( requiredVertexLength > maxVertexCount ) {
  20744. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20745. }
  20746. // Check if we can shrink to the requested index attribute size
  20747. if ( this.geometry.index ) {
  20748. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  20749. if ( requiredIndexLength > maxIndexCount ) {
  20750. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20751. }
  20752. }
  20753. //
  20754. // dispose of the previous geometry
  20755. const oldGeometry = this.geometry;
  20756. oldGeometry.dispose();
  20757. // recreate the geometry needed based on the previous variant
  20758. this._maxVertexCount = maxVertexCount;
  20759. this._maxIndexCount = maxIndexCount;
  20760. if ( this._geometryInitialized ) {
  20761. this._geometryInitialized = false;
  20762. this.geometry = new BufferGeometry();
  20763. this._initializeGeometry( oldGeometry );
  20764. }
  20765. // copy data from the previous geometry
  20766. const geometry = this.geometry;
  20767. if ( oldGeometry.index ) {
  20768. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  20769. }
  20770. for ( const key in oldGeometry.attributes ) {
  20771. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  20772. }
  20773. }
  20774. raycast( raycaster, intersects ) {
  20775. const instanceInfo = this._instanceInfo;
  20776. const geometryInfoList = this._geometryInfo;
  20777. const matrixWorld = this.matrixWorld;
  20778. const batchGeometry = this.geometry;
  20779. // iterate over each geometry
  20780. _mesh.material = this.material;
  20781. _mesh.geometry.index = batchGeometry.index;
  20782. _mesh.geometry.attributes = batchGeometry.attributes;
  20783. if ( _mesh.geometry.boundingBox === null ) {
  20784. _mesh.geometry.boundingBox = new Box3();
  20785. }
  20786. if ( _mesh.geometry.boundingSphere === null ) {
  20787. _mesh.geometry.boundingSphere = new Sphere();
  20788. }
  20789. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20790. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  20791. continue;
  20792. }
  20793. const geometryId = instanceInfo[ i ].geometryIndex;
  20794. const geometryInfo = geometryInfoList[ geometryId ];
  20795. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  20796. // get the intersects
  20797. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  20798. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  20799. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  20800. _mesh.raycast( raycaster, _batchIntersects );
  20801. // add batch id to the intersects
  20802. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  20803. const intersect = _batchIntersects[ j ];
  20804. intersect.object = this;
  20805. intersect.batchId = i;
  20806. intersects.push( intersect );
  20807. }
  20808. _batchIntersects.length = 0;
  20809. }
  20810. _mesh.material = null;
  20811. _mesh.geometry.index = null;
  20812. _mesh.geometry.attributes = {};
  20813. _mesh.geometry.setDrawRange( 0, Infinity );
  20814. }
  20815. copy( source ) {
  20816. super.copy( source );
  20817. this.geometry = source.geometry.clone();
  20818. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  20819. this.sortObjects = source.sortObjects;
  20820. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  20821. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  20822. this._geometryInfo = source._geometryInfo.map( info => ( {
  20823. ...info,
  20824. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  20825. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  20826. } ) );
  20827. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  20828. this._availableInstanceIds = source._availableInstanceIds.slice();
  20829. this._availableGeometryIds = source._availableGeometryIds.slice();
  20830. this._nextIndexStart = source._nextIndexStart;
  20831. this._nextVertexStart = source._nextVertexStart;
  20832. this._geometryCount = source._geometryCount;
  20833. this._maxInstanceCount = source._maxInstanceCount;
  20834. this._maxVertexCount = source._maxVertexCount;
  20835. this._maxIndexCount = source._maxIndexCount;
  20836. this._geometryInitialized = source._geometryInitialized;
  20837. this._multiDrawCounts = source._multiDrawCounts.slice();
  20838. this._multiDrawStarts = source._multiDrawStarts.slice();
  20839. this._indirectTexture = source._indirectTexture.clone();
  20840. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  20841. this._matricesTexture = source._matricesTexture.clone();
  20842. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  20843. if ( this._colorsTexture !== null ) {
  20844. this._colorsTexture = source._colorsTexture.clone();
  20845. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  20846. }
  20847. return this;
  20848. }
  20849. /**
  20850. * Frees the GPU-related resources allocated by this instance. Call this
  20851. * method whenever this instance is no longer used in your app.
  20852. */
  20853. dispose() {
  20854. // Assuming the geometry is not shared with other meshes
  20855. this.geometry.dispose();
  20856. this._matricesTexture.dispose();
  20857. this._matricesTexture = null;
  20858. this._indirectTexture.dispose();
  20859. this._indirectTexture = null;
  20860. if ( this._colorsTexture !== null ) {
  20861. this._colorsTexture.dispose();
  20862. this._colorsTexture = null;
  20863. }
  20864. }
  20865. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  20866. // if visibility has not changed and frustum culling and object sorting is not required
  20867. // then skip iterating over all items
  20868. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  20869. return;
  20870. }
  20871. // the indexed version of the multi draw function requires specifying the start
  20872. // offset in bytes.
  20873. const index = geometry.getIndex();
  20874. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  20875. const instanceInfo = this._instanceInfo;
  20876. const multiDrawStarts = this._multiDrawStarts;
  20877. const multiDrawCounts = this._multiDrawCounts;
  20878. const geometryInfoList = this._geometryInfo;
  20879. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  20880. const indirectTexture = this._indirectTexture;
  20881. const indirectArray = indirectTexture.image.data;
  20882. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  20883. // prepare the frustum in the local frame
  20884. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  20885. _matrix$1
  20886. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  20887. .multiply( this.matrixWorld );
  20888. _frustum.setFromProjectionMatrix(
  20889. _matrix$1,
  20890. camera.coordinateSystem,
  20891. camera.reversedDepth
  20892. );
  20893. }
  20894. let multiDrawCount = 0;
  20895. if ( this.sortObjects ) {
  20896. // get the camera position in the local frame
  20897. _matrix$1.copy( this.matrixWorld ).invert();
  20898. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  20899. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  20900. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20901. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20902. const geometryId = instanceInfo[ i ].geometryIndex;
  20903. // get the bounds in world space
  20904. this.getMatrixAt( i, _matrix$1 );
  20905. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20906. // determine whether the batched geometry is within the frustum
  20907. let culled = false;
  20908. if ( perObjectFrustumCulled ) {
  20909. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20910. }
  20911. if ( ! culled ) {
  20912. // get the distance from camera used for sorting
  20913. const geometryInfo = geometryInfoList[ geometryId ];
  20914. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  20915. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  20916. }
  20917. }
  20918. }
  20919. // Sort the draw ranges and prep for rendering
  20920. const list = _renderList.list;
  20921. const customSort = this.customSort;
  20922. if ( customSort === null ) {
  20923. list.sort( material.transparent ? sortTransparent : sortOpaque );
  20924. } else {
  20925. customSort.call( this, list, camera );
  20926. }
  20927. for ( let i = 0, l = list.length; i < l; i ++ ) {
  20928. const item = list[ i ];
  20929. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  20930. multiDrawCounts[ multiDrawCount ] = item.count;
  20931. indirectArray[ multiDrawCount ] = item.index;
  20932. multiDrawCount ++;
  20933. }
  20934. _renderList.reset();
  20935. } else {
  20936. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20937. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20938. const geometryId = instanceInfo[ i ].geometryIndex;
  20939. // determine whether the batched geometry is within the frustum
  20940. let culled = false;
  20941. if ( perObjectFrustumCulled ) {
  20942. // get the bounds in world space
  20943. this.getMatrixAt( i, _matrix$1 );
  20944. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20945. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20946. }
  20947. if ( ! culled ) {
  20948. const geometryInfo = geometryInfoList[ geometryId ];
  20949. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  20950. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  20951. indirectArray[ multiDrawCount ] = i;
  20952. multiDrawCount ++;
  20953. }
  20954. }
  20955. }
  20956. }
  20957. indirectTexture.needsUpdate = true;
  20958. this._multiDrawCount = multiDrawCount;
  20959. this._visibilityChanged = false;
  20960. }
  20961. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  20962. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  20963. }
  20964. }
  20965. /**
  20966. * A material for rendering line primitives.
  20967. *
  20968. * Materials define the appearance of renderable 3D objects.
  20969. *
  20970. * ```js
  20971. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  20972. * ```
  20973. *
  20974. * @augments Material
  20975. */
  20976. class LineBasicMaterial extends Material {
  20977. /**
  20978. * Constructs a new line basic material.
  20979. *
  20980. * @param {Object} [parameters] - An object with one or more properties
  20981. * defining the material's appearance. Any property of the material
  20982. * (including any property from inherited materials) can be passed
  20983. * in here. Color values can be passed any type of value accepted
  20984. * by {@link Color#set}.
  20985. */
  20986. constructor( parameters ) {
  20987. super();
  20988. /**
  20989. * This flag can be used for type testing.
  20990. *
  20991. * @type {boolean}
  20992. * @readonly
  20993. * @default true
  20994. */
  20995. this.isLineBasicMaterial = true;
  20996. this.type = 'LineBasicMaterial';
  20997. /**
  20998. * Color of the material.
  20999. *
  21000. * @type {Color}
  21001. * @default (1,1,1)
  21002. */
  21003. this.color = new Color( 0xffffff );
  21004. /**
  21005. * Sets the color of the lines using data from a texture. The texture map
  21006. * color is modulated by the diffuse `color`.
  21007. *
  21008. * @type {?Texture}
  21009. * @default null
  21010. */
  21011. this.map = null;
  21012. /**
  21013. * Controls line thickness or lines.
  21014. *
  21015. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  21016. * ignore this setting and always render line primitives with a
  21017. * width of one pixel.
  21018. *
  21019. * @type {number}
  21020. * @default 1
  21021. */
  21022. this.linewidth = 1;
  21023. /**
  21024. * Defines appearance of line ends.
  21025. *
  21026. * Can only be used with {@link SVGRenderer}.
  21027. *
  21028. * @type {('butt'|'round'|'square')}
  21029. * @default 'round'
  21030. */
  21031. this.linecap = 'round';
  21032. /**
  21033. * Defines appearance of line joints.
  21034. *
  21035. * Can only be used with {@link SVGRenderer}.
  21036. *
  21037. * @type {('round'|'bevel'|'miter')}
  21038. * @default 'round'
  21039. */
  21040. this.linejoin = 'round';
  21041. /**
  21042. * Whether the material is affected by fog or not.
  21043. *
  21044. * @type {boolean}
  21045. * @default true
  21046. */
  21047. this.fog = true;
  21048. this.setValues( parameters );
  21049. }
  21050. copy( source ) {
  21051. super.copy( source );
  21052. this.color.copy( source.color );
  21053. this.map = source.map;
  21054. this.linewidth = source.linewidth;
  21055. this.linecap = source.linecap;
  21056. this.linejoin = source.linejoin;
  21057. this.fog = source.fog;
  21058. return this;
  21059. }
  21060. }
  21061. const _vStart = /*@__PURE__*/ new Vector3();
  21062. const _vEnd = /*@__PURE__*/ new Vector3();
  21063. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  21064. const _ray$1 = /*@__PURE__*/ new Ray();
  21065. const _sphere$1 = /*@__PURE__*/ new Sphere();
  21066. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  21067. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  21068. /**
  21069. * A continuous line. The line are rendered by connecting consecutive
  21070. * vertices with straight lines.
  21071. *
  21072. * ```js
  21073. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  21074. *
  21075. * const points = [];
  21076. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  21077. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  21078. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  21079. *
  21080. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  21081. *
  21082. * const line = new THREE.Line( geometry, material );
  21083. * scene.add( line );
  21084. * ```
  21085. *
  21086. * @augments Object3D
  21087. */
  21088. class Line extends Object3D {
  21089. /**
  21090. * Constructs a new line.
  21091. *
  21092. * @param {BufferGeometry} [geometry] - The line geometry.
  21093. * @param {Material|Array<Material>} [material] - The line material.
  21094. */
  21095. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  21096. super();
  21097. /**
  21098. * This flag can be used for type testing.
  21099. *
  21100. * @type {boolean}
  21101. * @readonly
  21102. * @default true
  21103. */
  21104. this.isLine = true;
  21105. this.type = 'Line';
  21106. /**
  21107. * The line geometry.
  21108. *
  21109. * @type {BufferGeometry}
  21110. */
  21111. this.geometry = geometry;
  21112. /**
  21113. * The line material.
  21114. *
  21115. * @type {Material|Array<Material>}
  21116. * @default LineBasicMaterial
  21117. */
  21118. this.material = material;
  21119. /**
  21120. * A dictionary representing the morph targets in the geometry. The key is the
  21121. * morph targets name, the value its attribute index. This member is `undefined`
  21122. * by default and only set when morph targets are detected in the geometry.
  21123. *
  21124. * @type {Object<String,number>|undefined}
  21125. * @default undefined
  21126. */
  21127. this.morphTargetDictionary = undefined;
  21128. /**
  21129. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21130. * is applied. This member is `undefined` by default and only set when morph targets are
  21131. * detected in the geometry.
  21132. *
  21133. * @type {Array<number>|undefined}
  21134. * @default undefined
  21135. */
  21136. this.morphTargetInfluences = undefined;
  21137. this.updateMorphTargets();
  21138. }
  21139. copy( source, recursive ) {
  21140. super.copy( source, recursive );
  21141. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21142. this.geometry = source.geometry;
  21143. return this;
  21144. }
  21145. /**
  21146. * Computes an array of distance values which are necessary for rendering dashed lines.
  21147. * For each vertex in the geometry, the method calculates the cumulative length from the
  21148. * current point to the very beginning of the line.
  21149. *
  21150. * @return {Line} A reference to this line.
  21151. */
  21152. computeLineDistances() {
  21153. const geometry = this.geometry;
  21154. // we assume non-indexed geometry
  21155. if ( geometry.index === null ) {
  21156. const positionAttribute = geometry.attributes.position;
  21157. const lineDistances = [ 0 ];
  21158. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  21159. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  21160. _vEnd.fromBufferAttribute( positionAttribute, i );
  21161. lineDistances[ i ] = lineDistances[ i - 1 ];
  21162. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  21163. }
  21164. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21165. } else {
  21166. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21167. }
  21168. return this;
  21169. }
  21170. /**
  21171. * Computes intersection points between a casted ray and this line.
  21172. *
  21173. * @param {Raycaster} raycaster - The raycaster.
  21174. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21175. */
  21176. raycast( raycaster, intersects ) {
  21177. const geometry = this.geometry;
  21178. const matrixWorld = this.matrixWorld;
  21179. const threshold = raycaster.params.Line.threshold;
  21180. const drawRange = geometry.drawRange;
  21181. // Checking boundingSphere distance to ray
  21182. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21183. _sphere$1.copy( geometry.boundingSphere );
  21184. _sphere$1.applyMatrix4( matrixWorld );
  21185. _sphere$1.radius += threshold;
  21186. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  21187. //
  21188. _inverseMatrix$1.copy( matrixWorld ).invert();
  21189. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  21190. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21191. const localThresholdSq = localThreshold * localThreshold;
  21192. const step = this.isLineSegments ? 2 : 1;
  21193. const index = geometry.index;
  21194. const attributes = geometry.attributes;
  21195. const positionAttribute = attributes.position;
  21196. if ( index !== null ) {
  21197. const start = Math.max( 0, drawRange.start );
  21198. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21199. for ( let i = start, l = end - 1; i < l; i += step ) {
  21200. const a = index.getX( i );
  21201. const b = index.getX( i + 1 );
  21202. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  21203. if ( intersect ) {
  21204. intersects.push( intersect );
  21205. }
  21206. }
  21207. if ( this.isLineLoop ) {
  21208. const a = index.getX( end - 1 );
  21209. const b = index.getX( start );
  21210. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  21211. if ( intersect ) {
  21212. intersects.push( intersect );
  21213. }
  21214. }
  21215. } else {
  21216. const start = Math.max( 0, drawRange.start );
  21217. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21218. for ( let i = start, l = end - 1; i < l; i += step ) {
  21219. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  21220. if ( intersect ) {
  21221. intersects.push( intersect );
  21222. }
  21223. }
  21224. if ( this.isLineLoop ) {
  21225. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  21226. if ( intersect ) {
  21227. intersects.push( intersect );
  21228. }
  21229. }
  21230. }
  21231. }
  21232. /**
  21233. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  21234. * to make sure existing morph targets can influence this 3D object.
  21235. */
  21236. updateMorphTargets() {
  21237. const geometry = this.geometry;
  21238. const morphAttributes = geometry.morphAttributes;
  21239. const keys = Object.keys( morphAttributes );
  21240. if ( keys.length > 0 ) {
  21241. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21242. if ( morphAttribute !== undefined ) {
  21243. this.morphTargetInfluences = [];
  21244. this.morphTargetDictionary = {};
  21245. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21246. const name = morphAttribute[ m ].name || String( m );
  21247. this.morphTargetInfluences.push( 0 );
  21248. this.morphTargetDictionary[ name ] = m;
  21249. }
  21250. }
  21251. }
  21252. }
  21253. }
  21254. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  21255. const positionAttribute = object.geometry.attributes.position;
  21256. _vStart.fromBufferAttribute( positionAttribute, a );
  21257. _vEnd.fromBufferAttribute( positionAttribute, b );
  21258. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  21259. if ( distSq > thresholdSq ) return;
  21260. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  21261. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  21262. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21263. return {
  21264. distance: distance,
  21265. // What do we want? intersection point on the ray or on the segment??
  21266. // point: raycaster.ray.at( distance ),
  21267. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  21268. index: i,
  21269. face: null,
  21270. faceIndex: null,
  21271. barycoord: null,
  21272. object: object
  21273. };
  21274. }
  21275. const _start = /*@__PURE__*/ new Vector3();
  21276. const _end = /*@__PURE__*/ new Vector3();
  21277. /**
  21278. * A series of lines drawn between pairs of vertices.
  21279. *
  21280. * @augments Line
  21281. */
  21282. class LineSegments extends Line {
  21283. /**
  21284. * Constructs a new line segments.
  21285. *
  21286. * @param {BufferGeometry} [geometry] - The line geometry.
  21287. * @param {Material|Array<Material>} [material] - The line material.
  21288. */
  21289. constructor( geometry, material ) {
  21290. super( geometry, material );
  21291. /**
  21292. * This flag can be used for type testing.
  21293. *
  21294. * @type {boolean}
  21295. * @readonly
  21296. * @default true
  21297. */
  21298. this.isLineSegments = true;
  21299. this.type = 'LineSegments';
  21300. }
  21301. computeLineDistances() {
  21302. const geometry = this.geometry;
  21303. // we assume non-indexed geometry
  21304. if ( geometry.index === null ) {
  21305. const positionAttribute = geometry.attributes.position;
  21306. const lineDistances = [];
  21307. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  21308. _start.fromBufferAttribute( positionAttribute, i );
  21309. _end.fromBufferAttribute( positionAttribute, i + 1 );
  21310. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  21311. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  21312. }
  21313. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21314. } else {
  21315. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21316. }
  21317. return this;
  21318. }
  21319. }
  21320. /**
  21321. * A continuous line. This is nearly the same as {@link Line} the only difference
  21322. * is that the last vertex is connected with the first vertex in order to close
  21323. * the line to form a loop.
  21324. *
  21325. * @augments Line
  21326. */
  21327. class LineLoop extends Line {
  21328. /**
  21329. * Constructs a new line loop.
  21330. *
  21331. * @param {BufferGeometry} [geometry] - The line geometry.
  21332. * @param {Material|Array<Material>} [material] - The line material.
  21333. */
  21334. constructor( geometry, material ) {
  21335. super( geometry, material );
  21336. /**
  21337. * This flag can be used for type testing.
  21338. *
  21339. * @type {boolean}
  21340. * @readonly
  21341. * @default true
  21342. */
  21343. this.isLineLoop = true;
  21344. this.type = 'LineLoop';
  21345. }
  21346. }
  21347. /**
  21348. * A material for rendering point primitives.
  21349. *
  21350. * Materials define the appearance of renderable 3D objects.
  21351. *
  21352. * ```js
  21353. * const vertices = [];
  21354. *
  21355. * for ( let i = 0; i < 10000; i ++ ) {
  21356. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  21357. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  21358. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  21359. *
  21360. * vertices.push( x, y, z );
  21361. * }
  21362. *
  21363. * const geometry = new THREE.BufferGeometry();
  21364. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  21365. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  21366. * const points = new THREE.Points( geometry, material );
  21367. * scene.add( points );
  21368. * ```
  21369. *
  21370. * @augments Material
  21371. */
  21372. class PointsMaterial extends Material {
  21373. /**
  21374. * Constructs a new points material.
  21375. *
  21376. * @param {Object} [parameters] - An object with one or more properties
  21377. * defining the material's appearance. Any property of the material
  21378. * (including any property from inherited materials) can be passed
  21379. * in here. Color values can be passed any type of value accepted
  21380. * by {@link Color#set}.
  21381. */
  21382. constructor( parameters ) {
  21383. super();
  21384. /**
  21385. * This flag can be used for type testing.
  21386. *
  21387. * @type {boolean}
  21388. * @readonly
  21389. * @default true
  21390. */
  21391. this.isPointsMaterial = true;
  21392. this.type = 'PointsMaterial';
  21393. /**
  21394. * Color of the material.
  21395. *
  21396. * @type {Color}
  21397. * @default (1,1,1)
  21398. */
  21399. this.color = new Color( 0xffffff );
  21400. /**
  21401. * The color map. May optionally include an alpha channel, typically combined
  21402. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  21403. * color is modulated by the diffuse `color`.
  21404. *
  21405. * @type {?Texture}
  21406. * @default null
  21407. */
  21408. this.map = null;
  21409. /**
  21410. * The alpha map is a grayscale texture that controls the opacity across the
  21411. * surface (black: fully transparent; white: fully opaque).
  21412. *
  21413. * Only the color of the texture is used, ignoring the alpha channel if one
  21414. * exists. For RGB and RGBA textures, the renderer will use the green channel
  21415. * when sampling this texture due to the extra bit of precision provided for
  21416. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  21417. * luminance/alpha textures will also still work as expected.
  21418. *
  21419. * @type {?Texture}
  21420. * @default null
  21421. */
  21422. this.alphaMap = null;
  21423. /**
  21424. * Defines the size of the points in pixels.
  21425. *
  21426. * 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}.
  21427. *
  21428. * @type {number}
  21429. * @default 1
  21430. */
  21431. this.size = 1;
  21432. /**
  21433. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  21434. *
  21435. * @type {boolean}
  21436. * @default true
  21437. */
  21438. this.sizeAttenuation = true;
  21439. /**
  21440. * Whether the material is affected by fog or not.
  21441. *
  21442. * @type {boolean}
  21443. * @default true
  21444. */
  21445. this.fog = true;
  21446. this.setValues( parameters );
  21447. }
  21448. copy( source ) {
  21449. super.copy( source );
  21450. this.color.copy( source.color );
  21451. this.map = source.map;
  21452. this.alphaMap = source.alphaMap;
  21453. this.size = source.size;
  21454. this.sizeAttenuation = source.sizeAttenuation;
  21455. this.fog = source.fog;
  21456. return this;
  21457. }
  21458. }
  21459. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  21460. const _ray = /*@__PURE__*/ new Ray();
  21461. const _sphere = /*@__PURE__*/ new Sphere();
  21462. const _position$2 = /*@__PURE__*/ new Vector3();
  21463. /**
  21464. * A class for displaying points or point clouds.
  21465. *
  21466. * @augments Object3D
  21467. */
  21468. class Points extends Object3D {
  21469. /**
  21470. * Constructs a new point cloud.
  21471. *
  21472. * @param {BufferGeometry} [geometry] - The points geometry.
  21473. * @param {Material|Array<Material>} [material] - The points material.
  21474. */
  21475. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  21476. super();
  21477. /**
  21478. * This flag can be used for type testing.
  21479. *
  21480. * @type {boolean}
  21481. * @readonly
  21482. * @default true
  21483. */
  21484. this.isPoints = true;
  21485. this.type = 'Points';
  21486. /**
  21487. * The points geometry.
  21488. *
  21489. * @type {BufferGeometry}
  21490. */
  21491. this.geometry = geometry;
  21492. /**
  21493. * The line material.
  21494. *
  21495. * @type {Material|Array<Material>}
  21496. * @default PointsMaterial
  21497. */
  21498. this.material = material;
  21499. /**
  21500. * A dictionary representing the morph targets in the geometry. The key is the
  21501. * morph targets name, the value its attribute index. This member is `undefined`
  21502. * by default and only set when morph targets are detected in the geometry.
  21503. *
  21504. * @type {Object<String,number>|undefined}
  21505. * @default undefined
  21506. */
  21507. this.morphTargetDictionary = undefined;
  21508. /**
  21509. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21510. * is applied. This member is `undefined` by default and only set when morph targets are
  21511. * detected in the geometry.
  21512. *
  21513. * @type {Array<number>|undefined}
  21514. * @default undefined
  21515. */
  21516. this.morphTargetInfluences = undefined;
  21517. this.updateMorphTargets();
  21518. }
  21519. copy( source, recursive ) {
  21520. super.copy( source, recursive );
  21521. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21522. this.geometry = source.geometry;
  21523. return this;
  21524. }
  21525. /**
  21526. * Computes intersection points between a casted ray and this point cloud.
  21527. *
  21528. * @param {Raycaster} raycaster - The raycaster.
  21529. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21530. */
  21531. raycast( raycaster, intersects ) {
  21532. const geometry = this.geometry;
  21533. const matrixWorld = this.matrixWorld;
  21534. const threshold = raycaster.params.Points.threshold;
  21535. const drawRange = geometry.drawRange;
  21536. // Checking boundingSphere distance to ray
  21537. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21538. _sphere.copy( geometry.boundingSphere );
  21539. _sphere.applyMatrix4( matrixWorld );
  21540. _sphere.radius += threshold;
  21541. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  21542. //
  21543. _inverseMatrix.copy( matrixWorld ).invert();
  21544. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  21545. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21546. const localThresholdSq = localThreshold * localThreshold;
  21547. const index = geometry.index;
  21548. const attributes = geometry.attributes;
  21549. const positionAttribute = attributes.position;
  21550. if ( index !== null ) {
  21551. const start = Math.max( 0, drawRange.start );
  21552. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21553. for ( let i = start, il = end; i < il; i ++ ) {
  21554. const a = index.getX( i );
  21555. _position$2.fromBufferAttribute( positionAttribute, a );
  21556. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21557. }
  21558. } else {
  21559. const start = Math.max( 0, drawRange.start );
  21560. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21561. for ( let i = start, l = end; i < l; i ++ ) {
  21562. _position$2.fromBufferAttribute( positionAttribute, i );
  21563. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21564. }
  21565. }
  21566. }
  21567. /**
  21568. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  21569. * to make sure existing morph targets can influence this 3D object.
  21570. */
  21571. updateMorphTargets() {
  21572. const geometry = this.geometry;
  21573. const morphAttributes = geometry.morphAttributes;
  21574. const keys = Object.keys( morphAttributes );
  21575. if ( keys.length > 0 ) {
  21576. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21577. if ( morphAttribute !== undefined ) {
  21578. this.morphTargetInfluences = [];
  21579. this.morphTargetDictionary = {};
  21580. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21581. const name = morphAttribute[ m ].name || String( m );
  21582. this.morphTargetInfluences.push( 0 );
  21583. this.morphTargetDictionary[ name ] = m;
  21584. }
  21585. }
  21586. }
  21587. }
  21588. }
  21589. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  21590. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  21591. if ( rayPointDistanceSq < localThresholdSq ) {
  21592. const intersectPoint = new Vector3();
  21593. _ray.closestPointToPoint( point, intersectPoint );
  21594. intersectPoint.applyMatrix4( matrixWorld );
  21595. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  21596. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21597. intersects.push( {
  21598. distance: distance,
  21599. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  21600. point: intersectPoint,
  21601. index: index,
  21602. face: null,
  21603. faceIndex: null,
  21604. barycoord: null,
  21605. object: object
  21606. } );
  21607. }
  21608. }
  21609. /**
  21610. * A texture for use with a video.
  21611. *
  21612. * ```js
  21613. * // assuming you have created a HTML video element with id="video"
  21614. * const video = document.getElementById( 'video' );
  21615. * const texture = new THREE.VideoTexture( video );
  21616. * ```
  21617. *
  21618. * Note: When using video textures with {@link WebGPURenderer}, {@link Texture#colorSpace} must be
  21619. * set to THREE.SRGBColorSpace.
  21620. *
  21621. * Note: After the initial use of a texture, its dimensions, format, and type
  21622. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  21623. *
  21624. * @augments Texture
  21625. */
  21626. class VideoTexture extends Texture {
  21627. /**
  21628. * Constructs a new video texture.
  21629. *
  21630. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  21631. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21632. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21633. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21634. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21635. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21636. * @param {number} [format=RGBAFormat] - The texture format.
  21637. * @param {number} [type=UnsignedByteType] - The texture type.
  21638. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21639. */
  21640. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  21641. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21642. /**
  21643. * This flag can be used for type testing.
  21644. *
  21645. * @type {boolean}
  21646. * @readonly
  21647. * @default true
  21648. */
  21649. this.isVideoTexture = true;
  21650. /**
  21651. * Whether to generate mipmaps (if possible) for a texture.
  21652. *
  21653. * Overwritten and set to `false` by default.
  21654. *
  21655. * @type {boolean}
  21656. * @default false
  21657. */
  21658. this.generateMipmaps = false;
  21659. /**
  21660. * The video frame request callback identifier, which is a positive integer.
  21661. *
  21662. * Value of 0 represents no scheduled rVFC.
  21663. *
  21664. * @private
  21665. * @type {number}
  21666. */
  21667. this._requestVideoFrameCallbackId = 0;
  21668. const scope = this;
  21669. function updateVideo() {
  21670. scope.needsUpdate = true;
  21671. scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21672. }
  21673. if ( 'requestVideoFrameCallback' in video ) {
  21674. this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21675. }
  21676. }
  21677. clone() {
  21678. return new this.constructor( this.image ).copy( this );
  21679. }
  21680. /**
  21681. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  21682. * to `true` every time a new frame is available.
  21683. *
  21684. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  21685. */
  21686. update() {
  21687. const video = this.image;
  21688. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  21689. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  21690. this.needsUpdate = true;
  21691. }
  21692. }
  21693. dispose() {
  21694. if ( this._requestVideoFrameCallbackId !== 0 ) {
  21695. this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId );
  21696. }
  21697. super.dispose();
  21698. }
  21699. }
  21700. /**
  21701. * This class can be used as an alternative way to define video data. Instead of using
  21702. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  21703. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  21704. * video frames are decoded with the WebCodecs API.
  21705. *
  21706. * ```js
  21707. * const texture = new THREE.VideoFrameTexture();
  21708. * texture.setFrame( frame );
  21709. * ```
  21710. *
  21711. * @augments VideoTexture
  21712. */
  21713. class VideoFrameTexture extends VideoTexture {
  21714. /**
  21715. * Constructs a new video frame texture.
  21716. *
  21717. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21718. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21719. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21720. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21721. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21722. * @param {number} [format=RGBAFormat] - The texture format.
  21723. * @param {number} [type=UnsignedByteType] - The texture type.
  21724. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21725. */
  21726. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21727. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21728. /**
  21729. * This flag can be used for type testing.
  21730. *
  21731. * @type {boolean}
  21732. * @readonly
  21733. * @default true
  21734. */
  21735. this.isVideoFrameTexture = true;
  21736. }
  21737. /**
  21738. * This method overwritten with an empty implementation since
  21739. * this type of texture is updated via `setFrame()`.
  21740. */
  21741. update() {}
  21742. clone() {
  21743. return new this.constructor().copy( this ); // restoring Texture.clone()
  21744. }
  21745. /**
  21746. * Sets the current frame of the video. This will automatically update the texture
  21747. * so the data can be used for rendering.
  21748. *
  21749. * @param {VideoFrame} frame - The video frame.
  21750. */
  21751. setFrame( frame ) {
  21752. this.image = frame;
  21753. this.needsUpdate = true;
  21754. }
  21755. }
  21756. /**
  21757. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  21758. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  21759. * as a texture for further usage.
  21760. *
  21761. * ```js
  21762. * const pixelRatio = window.devicePixelRatio;
  21763. * const textureSize = 128 * pixelRatio;
  21764. *
  21765. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  21766. *
  21767. * // calculate start position for copying part of the frame data
  21768. * const vector = new Vector2();
  21769. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  21770. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  21771. *
  21772. * renderer.render( scene, camera );
  21773. *
  21774. * // copy part of the rendered frame into the framebuffer texture
  21775. * renderer.copyFramebufferToTexture( frameTexture, vector );
  21776. * ```
  21777. *
  21778. * @augments Texture
  21779. */
  21780. class FramebufferTexture extends Texture {
  21781. /**
  21782. * Constructs a new framebuffer texture.
  21783. *
  21784. * @param {number} [width] - The width of the texture.
  21785. * @param {number} [height] - The height of the texture.
  21786. */
  21787. constructor( width, height ) {
  21788. super( { width, height } );
  21789. /**
  21790. * This flag can be used for type testing.
  21791. *
  21792. * @type {boolean}
  21793. * @readonly
  21794. * @default true
  21795. */
  21796. this.isFramebufferTexture = true;
  21797. /**
  21798. * How the texture is sampled when a texel covers more than one pixel.
  21799. *
  21800. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21801. *
  21802. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21803. * @default NearestFilter
  21804. */
  21805. this.magFilter = NearestFilter;
  21806. /**
  21807. * How the texture is sampled when a texel covers less than one pixel.
  21808. *
  21809. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21810. *
  21811. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21812. * @default NearestFilter
  21813. */
  21814. this.minFilter = NearestFilter;
  21815. /**
  21816. * Whether to generate mipmaps (if possible) for a texture.
  21817. *
  21818. * Overwritten and set to `false` by default.
  21819. *
  21820. * @type {boolean}
  21821. * @default false
  21822. */
  21823. this.generateMipmaps = false;
  21824. this.needsUpdate = true;
  21825. }
  21826. }
  21827. /**
  21828. * Creates a texture based on data in compressed form.
  21829. *
  21830. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21831. *
  21832. * @augments Texture
  21833. */
  21834. class CompressedTexture extends Texture {
  21835. /**
  21836. * Constructs a new compressed texture.
  21837. *
  21838. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21839. * the data and dimensions.
  21840. * @param {number} width - The width of the texture.
  21841. * @param {number} height - The height of the texture.
  21842. * @param {number} [format=RGBAFormat] - The texture format.
  21843. * @param {number} [type=UnsignedByteType] - The texture type.
  21844. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21845. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21846. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21847. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21848. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21849. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21850. * @param {string} [colorSpace=NoColorSpace] - The color space.
  21851. */
  21852. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  21853. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21854. /**
  21855. * This flag can be used for type testing.
  21856. *
  21857. * @type {boolean}
  21858. * @readonly
  21859. * @default true
  21860. */
  21861. this.isCompressedTexture = true;
  21862. /**
  21863. * The image property of a compressed texture just defines its dimensions.
  21864. *
  21865. * @type {{width:number,height:number}}
  21866. */
  21867. this.image = { width: width, height: height };
  21868. /**
  21869. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  21870. *
  21871. * @type {Array<Object>}
  21872. */
  21873. this.mipmaps = mipmaps;
  21874. /**
  21875. * If set to `true`, the texture is flipped along the vertical axis when
  21876. * uploaded to the GPU.
  21877. *
  21878. * Overwritten and set to `false` by default since it is not possible to
  21879. * flip compressed textures.
  21880. *
  21881. * @type {boolean}
  21882. * @default false
  21883. * @readonly
  21884. */
  21885. this.flipY = false;
  21886. /**
  21887. * Whether to generate mipmaps (if possible) for a texture.
  21888. *
  21889. * Overwritten and set to `false` by default since it is not
  21890. * possible to generate mipmaps for compressed data. Mipmaps
  21891. * must be embedded in the compressed texture file.
  21892. *
  21893. * @type {boolean}
  21894. * @default false
  21895. * @readonly
  21896. */
  21897. this.generateMipmaps = false;
  21898. }
  21899. }
  21900. /**
  21901. * Creates a texture 2D array based on data in compressed form.
  21902. *
  21903. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21904. *
  21905. * @augments CompressedTexture
  21906. */
  21907. class CompressedArrayTexture extends CompressedTexture {
  21908. /**
  21909. * Constructs a new compressed array texture.
  21910. *
  21911. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21912. * the data and dimensions.
  21913. * @param {number} width - The width of the texture.
  21914. * @param {number} height - The height of the texture.
  21915. * @param {number} depth - The depth of the texture.
  21916. * @param {number} [format=RGBAFormat] - The min filter value.
  21917. * @param {number} [type=UnsignedByteType] - The min filter value.
  21918. */
  21919. constructor( mipmaps, width, height, depth, format, type ) {
  21920. super( mipmaps, width, height, format, type );
  21921. /**
  21922. * This flag can be used for type testing.
  21923. *
  21924. * @type {boolean}
  21925. * @readonly
  21926. * @default true
  21927. */
  21928. this.isCompressedArrayTexture = true;
  21929. /**
  21930. * The image property of a compressed texture just defines its dimensions.
  21931. *
  21932. * @name CompressedArrayTexture#image
  21933. * @type {{width:number,height:number,depth:number}}
  21934. */
  21935. this.image.depth = depth;
  21936. /**
  21937. * This defines how the texture is wrapped in the depth and corresponds to
  21938. * *W* in UVW mapping.
  21939. *
  21940. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  21941. * @default ClampToEdgeWrapping
  21942. */
  21943. this.wrapR = ClampToEdgeWrapping;
  21944. /**
  21945. * A set of all layers which need to be updated in the texture.
  21946. *
  21947. * @type {Set<number>}
  21948. */
  21949. this.layerUpdates = new Set();
  21950. }
  21951. /**
  21952. * Describes that a specific layer of the texture needs to be updated.
  21953. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  21954. * entire compressed texture array is sent to the GPU. Marking specific
  21955. * layers will only transmit subsets of all mipmaps associated with a
  21956. * specific depth in the array which is often much more performant.
  21957. *
  21958. * @param {number} layerIndex - The layer index that should be updated.
  21959. */
  21960. addLayerUpdate( layerIndex ) {
  21961. this.layerUpdates.add( layerIndex );
  21962. }
  21963. /**
  21964. * Resets the layer updates registry.
  21965. */
  21966. clearLayerUpdates() {
  21967. this.layerUpdates.clear();
  21968. }
  21969. }
  21970. /**
  21971. * Creates a cube texture based on data in compressed form.
  21972. *
  21973. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21974. *
  21975. * @augments CompressedTexture
  21976. */
  21977. class CompressedCubeTexture extends CompressedTexture {
  21978. /**
  21979. * Constructs a new compressed texture.
  21980. *
  21981. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  21982. * @param {number} [format=RGBAFormat] - The texture format.
  21983. * @param {number} [type=UnsignedByteType] - The texture type.
  21984. */
  21985. constructor( images, format, type ) {
  21986. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  21987. /**
  21988. * This flag can be used for type testing.
  21989. *
  21990. * @type {boolean}
  21991. * @readonly
  21992. * @default true
  21993. */
  21994. this.isCompressedCubeTexture = true;
  21995. /**
  21996. * This flag can be used for type testing.
  21997. *
  21998. * @type {boolean}
  21999. * @readonly
  22000. * @default true
  22001. */
  22002. this.isCubeTexture = true;
  22003. this.image = images;
  22004. }
  22005. }
  22006. /**
  22007. * Creates a texture from a canvas element.
  22008. *
  22009. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  22010. * to `true` immediately since a canvas can directly be used for rendering.
  22011. *
  22012. * @augments Texture
  22013. */
  22014. class CanvasTexture extends Texture {
  22015. /**
  22016. * Constructs a new texture.
  22017. *
  22018. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  22019. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22020. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22021. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22022. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22023. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  22024. * @param {number} [format=RGBAFormat] - The texture format.
  22025. * @param {number} [type=UnsignedByteType] - The texture type.
  22026. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22027. */
  22028. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22029. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22030. /**
  22031. * This flag can be used for type testing.
  22032. *
  22033. * @type {boolean}
  22034. * @readonly
  22035. * @default true
  22036. */
  22037. this.isCanvasTexture = true;
  22038. this.needsUpdate = true;
  22039. }
  22040. }
  22041. /**
  22042. * This class can be used to automatically save the depth information of a
  22043. * rendering into a texture.
  22044. *
  22045. * @augments Texture
  22046. */
  22047. class DepthTexture extends Texture {
  22048. /**
  22049. * Constructs a new depth texture.
  22050. *
  22051. * @param {number} width - The width of the texture.
  22052. * @param {number} height - The height of the texture.
  22053. * @param {number} [type=UnsignedIntType] - The texture type.
  22054. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22055. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22056. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22057. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22058. * @param {number} [minFilter=LinearFilter] - The min filter value.
  22059. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22060. * @param {number} [format=DepthFormat] - The texture format.
  22061. * @param {number} [depth=1] - The depth of the texture.
  22062. */
  22063. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  22064. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  22065. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  22066. }
  22067. const image = { width: width, height: height, depth: depth };
  22068. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22069. /**
  22070. * This flag can be used for type testing.
  22071. *
  22072. * @type {boolean}
  22073. * @readonly
  22074. * @default true
  22075. */
  22076. this.isDepthTexture = true;
  22077. /**
  22078. * If set to `true`, the texture is flipped along the vertical axis when
  22079. * uploaded to the GPU.
  22080. *
  22081. * Overwritten and set to `false` by default.
  22082. *
  22083. * @type {boolean}
  22084. * @default false
  22085. */
  22086. this.flipY = false;
  22087. /**
  22088. * Whether to generate mipmaps (if possible) for a texture.
  22089. *
  22090. * Overwritten and set to `false` by default.
  22091. *
  22092. * @type {boolean}
  22093. * @default false
  22094. */
  22095. this.generateMipmaps = false;
  22096. /**
  22097. * Code corresponding to the depth compare function.
  22098. *
  22099. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  22100. * @default null
  22101. */
  22102. this.compareFunction = null;
  22103. }
  22104. copy( source ) {
  22105. super.copy( source );
  22106. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  22107. this.compareFunction = source.compareFunction;
  22108. return this;
  22109. }
  22110. toJSON( meta ) {
  22111. const data = super.toJSON( meta );
  22112. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  22113. return data;
  22114. }
  22115. }
  22116. /**
  22117. * Represents a texture created externally with the same renderer context.
  22118. *
  22119. * This may be a texture from a protected media stream, device camera feed,
  22120. * or other data feeds like a depth sensor.
  22121. *
  22122. * Note that this class is only supported in {@link WebGLRenderer}, and in
  22123. * the {@link WebGPURenderer} WebGPU backend.
  22124. *
  22125. * @augments Texture
  22126. */
  22127. class ExternalTexture extends Texture {
  22128. /**
  22129. * Creates a new raw texture.
  22130. *
  22131. * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture.
  22132. */
  22133. constructor( sourceTexture = null ) {
  22134. super();
  22135. /**
  22136. * The external source texture.
  22137. *
  22138. * @type {?(WebGLTexture|GPUTexture)}
  22139. * @default null
  22140. */
  22141. this.sourceTexture = sourceTexture;
  22142. /**
  22143. * This flag can be used for type testing.
  22144. *
  22145. * @type {boolean}
  22146. * @readonly
  22147. * @default true
  22148. */
  22149. this.isExternalTexture = true;
  22150. }
  22151. copy( source ) {
  22152. super.copy( source );
  22153. this.sourceTexture = source.sourceTexture;
  22154. return this;
  22155. }
  22156. }
  22157. /**
  22158. * A geometry class for representing a capsule.
  22159. *
  22160. * ```js
  22161. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  22162. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  22163. * const capsule = new THREE.Mesh( geometry, material );
  22164. * scene.add( capsule );
  22165. * ```
  22166. *
  22167. * @augments BufferGeometry
  22168. */
  22169. class CapsuleGeometry extends BufferGeometry {
  22170. /**
  22171. * Constructs a new capsule geometry.
  22172. *
  22173. * @param {number} [radius=1] - Radius of the capsule.
  22174. * @param {number} [height=1] - Height of the middle section.
  22175. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  22176. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  22177. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  22178. */
  22179. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  22180. super();
  22181. this.type = 'CapsuleGeometry';
  22182. /**
  22183. * Holds the constructor parameters that have been
  22184. * used to generate the geometry. Any modification
  22185. * after instantiation does not change the geometry.
  22186. *
  22187. * @type {Object}
  22188. */
  22189. this.parameters = {
  22190. radius: radius,
  22191. height: height,
  22192. capSegments: capSegments,
  22193. radialSegments: radialSegments,
  22194. heightSegments: heightSegments,
  22195. };
  22196. height = Math.max( 0, height );
  22197. capSegments = Math.max( 1, Math.floor( capSegments ) );
  22198. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  22199. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  22200. // buffers
  22201. const indices = [];
  22202. const vertices = [];
  22203. const normals = [];
  22204. const uvs = [];
  22205. // helper variables
  22206. const halfHeight = height / 2;
  22207. const capArcLength = ( Math.PI / 2 ) * radius;
  22208. const cylinderPartLength = height;
  22209. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  22210. const numVerticalSegments = capSegments * 2 + heightSegments;
  22211. const verticesPerRow = radialSegments + 1;
  22212. const normal = new Vector3();
  22213. const vertex = new Vector3();
  22214. // generate vertices, normals, and uvs
  22215. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  22216. let currentArcLength = 0;
  22217. let profileY = 0;
  22218. let profileRadius = 0;
  22219. let normalYComponent = 0;
  22220. if ( iy <= capSegments ) {
  22221. // bottom cap
  22222. const segmentProgress = iy / capSegments;
  22223. const angle = ( segmentProgress * Math.PI ) / 2;
  22224. profileY = - halfHeight - radius * Math.cos( angle );
  22225. profileRadius = radius * Math.sin( angle );
  22226. normalYComponent = - radius * Math.cos( angle );
  22227. currentArcLength = segmentProgress * capArcLength;
  22228. } else if ( iy <= capSegments + heightSegments ) {
  22229. // middle section
  22230. const segmentProgress = ( iy - capSegments ) / heightSegments;
  22231. profileY = - halfHeight + segmentProgress * height;
  22232. profileRadius = radius;
  22233. normalYComponent = 0;
  22234. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  22235. } else {
  22236. // top cap
  22237. const segmentProgress =
  22238. ( iy - capSegments - heightSegments ) / capSegments;
  22239. const angle = ( segmentProgress * Math.PI ) / 2;
  22240. profileY = halfHeight + radius * Math.sin( angle );
  22241. profileRadius = radius * Math.cos( angle );
  22242. normalYComponent = radius * Math.sin( angle );
  22243. currentArcLength =
  22244. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  22245. }
  22246. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  22247. // special case for the poles
  22248. let uOffset = 0;
  22249. if ( iy === 0 ) {
  22250. uOffset = 0.5 / radialSegments;
  22251. } else if ( iy === numVerticalSegments ) {
  22252. uOffset = -0.5 / radialSegments;
  22253. }
  22254. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  22255. const u = ix / radialSegments;
  22256. const theta = u * Math.PI * 2;
  22257. const sinTheta = Math.sin( theta );
  22258. const cosTheta = Math.cos( theta );
  22259. // vertex
  22260. vertex.x = - profileRadius * cosTheta;
  22261. vertex.y = profileY;
  22262. vertex.z = profileRadius * sinTheta;
  22263. vertices.push( vertex.x, vertex.y, vertex.z );
  22264. // normal
  22265. normal.set(
  22266. - profileRadius * cosTheta,
  22267. normalYComponent,
  22268. profileRadius * sinTheta
  22269. );
  22270. normal.normalize();
  22271. normals.push( normal.x, normal.y, normal.z );
  22272. // uv
  22273. uvs.push( u + uOffset, v );
  22274. }
  22275. if ( iy > 0 ) {
  22276. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  22277. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  22278. const i1 = prevIndexRow + ix;
  22279. const i2 = prevIndexRow + ix + 1;
  22280. const i3 = iy * verticesPerRow + ix;
  22281. const i4 = iy * verticesPerRow + ix + 1;
  22282. indices.push( i1, i2, i3 );
  22283. indices.push( i2, i4, i3 );
  22284. }
  22285. }
  22286. }
  22287. // build geometry
  22288. this.setIndex( indices );
  22289. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22290. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22291. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22292. }
  22293. copy( source ) {
  22294. super.copy( source );
  22295. this.parameters = Object.assign( {}, source.parameters );
  22296. return this;
  22297. }
  22298. /**
  22299. * Factory method for creating an instance of this class from the given
  22300. * JSON object.
  22301. *
  22302. * @param {Object} data - A JSON object representing the serialized geometry.
  22303. * @return {CapsuleGeometry} A new instance.
  22304. */
  22305. static fromJSON( data ) {
  22306. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  22307. }
  22308. }
  22309. /**
  22310. * A simple shape of Euclidean geometry. It is constructed from a
  22311. * number of triangular segments that are oriented around a central point and
  22312. * extend as far out as a given radius. It is built counter-clockwise from a
  22313. * start angle and a given central angle. It can also be used to create
  22314. * regular polygons, where the number of segments determines the number of
  22315. * sides.
  22316. *
  22317. * ```js
  22318. * const geometry = new THREE.CircleGeometry( 5, 32 );
  22319. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22320. * const circle = new THREE.Mesh( geometry, material );
  22321. * scene.add( circle )
  22322. * ```
  22323. *
  22324. * @augments BufferGeometry
  22325. */
  22326. class CircleGeometry extends BufferGeometry {
  22327. /**
  22328. * Constructs a new circle geometry.
  22329. *
  22330. * @param {number} [radius=1] - Radius of the circle.
  22331. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  22332. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  22333. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  22334. * of the circular sector in radians. The default value results in a complete circle.
  22335. */
  22336. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22337. super();
  22338. this.type = 'CircleGeometry';
  22339. /**
  22340. * Holds the constructor parameters that have been
  22341. * used to generate the geometry. Any modification
  22342. * after instantiation does not change the geometry.
  22343. *
  22344. * @type {Object}
  22345. */
  22346. this.parameters = {
  22347. radius: radius,
  22348. segments: segments,
  22349. thetaStart: thetaStart,
  22350. thetaLength: thetaLength
  22351. };
  22352. segments = Math.max( 3, segments );
  22353. // buffers
  22354. const indices = [];
  22355. const vertices = [];
  22356. const normals = [];
  22357. const uvs = [];
  22358. // helper variables
  22359. const vertex = new Vector3();
  22360. const uv = new Vector2();
  22361. // center point
  22362. vertices.push( 0, 0, 0 );
  22363. normals.push( 0, 0, 1 );
  22364. uvs.push( 0.5, 0.5 );
  22365. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22366. const segment = thetaStart + s / segments * thetaLength;
  22367. // vertex
  22368. vertex.x = radius * Math.cos( segment );
  22369. vertex.y = radius * Math.sin( segment );
  22370. vertices.push( vertex.x, vertex.y, vertex.z );
  22371. // normal
  22372. normals.push( 0, 0, 1 );
  22373. // uvs
  22374. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22375. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22376. uvs.push( uv.x, uv.y );
  22377. }
  22378. // indices
  22379. for ( let i = 1; i <= segments; i ++ ) {
  22380. indices.push( i, i + 1, 0 );
  22381. }
  22382. // build geometry
  22383. this.setIndex( indices );
  22384. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22385. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22386. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22387. }
  22388. copy( source ) {
  22389. super.copy( source );
  22390. this.parameters = Object.assign( {}, source.parameters );
  22391. return this;
  22392. }
  22393. /**
  22394. * Factory method for creating an instance of this class from the given
  22395. * JSON object.
  22396. *
  22397. * @param {Object} data - A JSON object representing the serialized geometry.
  22398. * @return {CircleGeometry} A new instance.
  22399. */
  22400. static fromJSON( data ) {
  22401. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  22402. }
  22403. }
  22404. /**
  22405. * A geometry class for representing a cylinder.
  22406. *
  22407. * ```js
  22408. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  22409. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22410. * const cylinder = new THREE.Mesh( geometry, material );
  22411. * scene.add( cylinder );
  22412. * ```
  22413. *
  22414. * @augments BufferGeometry
  22415. */
  22416. class CylinderGeometry extends BufferGeometry {
  22417. /**
  22418. * Constructs a new cylinder geometry.
  22419. *
  22420. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  22421. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  22422. * @param {number} [height=1] - Height of the cylinder.
  22423. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  22424. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  22425. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  22426. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22427. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22428. * The default value results in a complete cylinder.
  22429. */
  22430. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22431. super();
  22432. this.type = 'CylinderGeometry';
  22433. /**
  22434. * Holds the constructor parameters that have been
  22435. * used to generate the geometry. Any modification
  22436. * after instantiation does not change the geometry.
  22437. *
  22438. * @type {Object}
  22439. */
  22440. this.parameters = {
  22441. radiusTop: radiusTop,
  22442. radiusBottom: radiusBottom,
  22443. height: height,
  22444. radialSegments: radialSegments,
  22445. heightSegments: heightSegments,
  22446. openEnded: openEnded,
  22447. thetaStart: thetaStart,
  22448. thetaLength: thetaLength
  22449. };
  22450. const scope = this;
  22451. radialSegments = Math.floor( radialSegments );
  22452. heightSegments = Math.floor( heightSegments );
  22453. // buffers
  22454. const indices = [];
  22455. const vertices = [];
  22456. const normals = [];
  22457. const uvs = [];
  22458. // helper variables
  22459. let index = 0;
  22460. const indexArray = [];
  22461. const halfHeight = height / 2;
  22462. let groupStart = 0;
  22463. // generate geometry
  22464. generateTorso();
  22465. if ( openEnded === false ) {
  22466. if ( radiusTop > 0 ) generateCap( true );
  22467. if ( radiusBottom > 0 ) generateCap( false );
  22468. }
  22469. // build geometry
  22470. this.setIndex( indices );
  22471. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22472. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22473. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22474. function generateTorso() {
  22475. const normal = new Vector3();
  22476. const vertex = new Vector3();
  22477. let groupCount = 0;
  22478. // this will be used to calculate the normal
  22479. const slope = ( radiusBottom - radiusTop ) / height;
  22480. // generate vertices, normals and uvs
  22481. for ( let y = 0; y <= heightSegments; y ++ ) {
  22482. const indexRow = [];
  22483. const v = y / heightSegments;
  22484. // calculate the radius of the current row
  22485. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22486. for ( let x = 0; x <= radialSegments; x ++ ) {
  22487. const u = x / radialSegments;
  22488. const theta = u * thetaLength + thetaStart;
  22489. const sinTheta = Math.sin( theta );
  22490. const cosTheta = Math.cos( theta );
  22491. // vertex
  22492. vertex.x = radius * sinTheta;
  22493. vertex.y = - v * height + halfHeight;
  22494. vertex.z = radius * cosTheta;
  22495. vertices.push( vertex.x, vertex.y, vertex.z );
  22496. // normal
  22497. normal.set( sinTheta, slope, cosTheta ).normalize();
  22498. normals.push( normal.x, normal.y, normal.z );
  22499. // uv
  22500. uvs.push( u, 1 - v );
  22501. // save index of vertex in respective row
  22502. indexRow.push( index ++ );
  22503. }
  22504. // now save vertices of the row in our index array
  22505. indexArray.push( indexRow );
  22506. }
  22507. // generate indices
  22508. for ( let x = 0; x < radialSegments; x ++ ) {
  22509. for ( let y = 0; y < heightSegments; y ++ ) {
  22510. // we use the index array to access the correct indices
  22511. const a = indexArray[ y ][ x ];
  22512. const b = indexArray[ y + 1 ][ x ];
  22513. const c = indexArray[ y + 1 ][ x + 1 ];
  22514. const d = indexArray[ y ][ x + 1 ];
  22515. // faces
  22516. if ( radiusTop > 0 || y !== 0 ) {
  22517. indices.push( a, b, d );
  22518. groupCount += 3;
  22519. }
  22520. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  22521. indices.push( b, c, d );
  22522. groupCount += 3;
  22523. }
  22524. }
  22525. }
  22526. // add a group to the geometry. this will ensure multi material support
  22527. scope.addGroup( groupStart, groupCount, 0 );
  22528. // calculate new start value for groups
  22529. groupStart += groupCount;
  22530. }
  22531. function generateCap( top ) {
  22532. // save the index of the first center vertex
  22533. const centerIndexStart = index;
  22534. const uv = new Vector2();
  22535. const vertex = new Vector3();
  22536. let groupCount = 0;
  22537. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22538. const sign = ( top === true ) ? 1 : -1;
  22539. // first we generate the center vertex data of the cap.
  22540. // because the geometry needs one set of uvs per face,
  22541. // we must generate a center vertex per face/segment
  22542. for ( let x = 1; x <= radialSegments; x ++ ) {
  22543. // vertex
  22544. vertices.push( 0, halfHeight * sign, 0 );
  22545. // normal
  22546. normals.push( 0, sign, 0 );
  22547. // uv
  22548. uvs.push( 0.5, 0.5 );
  22549. // increase index
  22550. index ++;
  22551. }
  22552. // save the index of the last center vertex
  22553. const centerIndexEnd = index;
  22554. // now we generate the surrounding vertices, normals and uvs
  22555. for ( let x = 0; x <= radialSegments; x ++ ) {
  22556. const u = x / radialSegments;
  22557. const theta = u * thetaLength + thetaStart;
  22558. const cosTheta = Math.cos( theta );
  22559. const sinTheta = Math.sin( theta );
  22560. // vertex
  22561. vertex.x = radius * sinTheta;
  22562. vertex.y = halfHeight * sign;
  22563. vertex.z = radius * cosTheta;
  22564. vertices.push( vertex.x, vertex.y, vertex.z );
  22565. // normal
  22566. normals.push( 0, sign, 0 );
  22567. // uv
  22568. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22569. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22570. uvs.push( uv.x, uv.y );
  22571. // increase index
  22572. index ++;
  22573. }
  22574. // generate indices
  22575. for ( let x = 0; x < radialSegments; x ++ ) {
  22576. const c = centerIndexStart + x;
  22577. const i = centerIndexEnd + x;
  22578. if ( top === true ) {
  22579. // face top
  22580. indices.push( i, i + 1, c );
  22581. } else {
  22582. // face bottom
  22583. indices.push( i + 1, i, c );
  22584. }
  22585. groupCount += 3;
  22586. }
  22587. // add a group to the geometry. this will ensure multi material support
  22588. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22589. // calculate new start value for groups
  22590. groupStart += groupCount;
  22591. }
  22592. }
  22593. copy( source ) {
  22594. super.copy( source );
  22595. this.parameters = Object.assign( {}, source.parameters );
  22596. return this;
  22597. }
  22598. /**
  22599. * Factory method for creating an instance of this class from the given
  22600. * JSON object.
  22601. *
  22602. * @param {Object} data - A JSON object representing the serialized geometry.
  22603. * @return {CylinderGeometry} A new instance.
  22604. */
  22605. static fromJSON( data ) {
  22606. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22607. }
  22608. }
  22609. /**
  22610. * A geometry class for representing a cone.
  22611. *
  22612. * ```js
  22613. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  22614. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22615. * const cone = new THREE.Mesh(geometry, material );
  22616. * scene.add( cone );
  22617. * ```
  22618. *
  22619. * @augments CylinderGeometry
  22620. */
  22621. class ConeGeometry extends CylinderGeometry {
  22622. /**
  22623. * Constructs a new cone geometry.
  22624. *
  22625. * @param {number} [radius=1] - Radius of the cone base.
  22626. * @param {number} [height=1] - Height of the cone.
  22627. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  22628. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  22629. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  22630. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22631. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22632. * The default value results in a complete cone.
  22633. */
  22634. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22635. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22636. this.type = 'ConeGeometry';
  22637. /**
  22638. * Holds the constructor parameters that have been
  22639. * used to generate the geometry. Any modification
  22640. * after instantiation does not change the geometry.
  22641. *
  22642. * @type {Object}
  22643. */
  22644. this.parameters = {
  22645. radius: radius,
  22646. height: height,
  22647. radialSegments: radialSegments,
  22648. heightSegments: heightSegments,
  22649. openEnded: openEnded,
  22650. thetaStart: thetaStart,
  22651. thetaLength: thetaLength
  22652. };
  22653. }
  22654. /**
  22655. * Factory method for creating an instance of this class from the given
  22656. * JSON object.
  22657. *
  22658. * @param {Object} data - A JSON object representing the serialized geometry.
  22659. * @return {ConeGeometry} A new instance.
  22660. */
  22661. static fromJSON( data ) {
  22662. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22663. }
  22664. }
  22665. /**
  22666. * A polyhedron is a solid in three dimensions with flat faces. This class
  22667. * will take an array of vertices, project them onto a sphere, and then
  22668. * divide them up to the desired level of detail.
  22669. *
  22670. * @augments BufferGeometry
  22671. */
  22672. class PolyhedronGeometry extends BufferGeometry {
  22673. /**
  22674. * Constructs a new polyhedron geometry.
  22675. *
  22676. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  22677. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  22678. * @param {number} [radius=1] - The radius of the shape.
  22679. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  22680. */
  22681. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22682. super();
  22683. this.type = 'PolyhedronGeometry';
  22684. /**
  22685. * Holds the constructor parameters that have been
  22686. * used to generate the geometry. Any modification
  22687. * after instantiation does not change the geometry.
  22688. *
  22689. * @type {Object}
  22690. */
  22691. this.parameters = {
  22692. vertices: vertices,
  22693. indices: indices,
  22694. radius: radius,
  22695. detail: detail
  22696. };
  22697. // default buffer data
  22698. const vertexBuffer = [];
  22699. const uvBuffer = [];
  22700. // the subdivision creates the vertex buffer data
  22701. subdivide( detail );
  22702. // all vertices should lie on a conceptual sphere with a given radius
  22703. applyRadius( radius );
  22704. // finally, create the uv data
  22705. generateUVs();
  22706. // build non-indexed geometry
  22707. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22708. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22709. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22710. if ( detail === 0 ) {
  22711. this.computeVertexNormals(); // flat normals
  22712. } else {
  22713. this.normalizeNormals(); // smooth normals
  22714. }
  22715. // helper functions
  22716. function subdivide( detail ) {
  22717. const a = new Vector3();
  22718. const b = new Vector3();
  22719. const c = new Vector3();
  22720. // iterate over all faces and apply a subdivision with the given detail value
  22721. for ( let i = 0; i < indices.length; i += 3 ) {
  22722. // get the vertices of the face
  22723. getVertexByIndex( indices[ i + 0 ], a );
  22724. getVertexByIndex( indices[ i + 1 ], b );
  22725. getVertexByIndex( indices[ i + 2 ], c );
  22726. // perform subdivision
  22727. subdivideFace( a, b, c, detail );
  22728. }
  22729. }
  22730. function subdivideFace( a, b, c, detail ) {
  22731. const cols = detail + 1;
  22732. // we use this multidimensional array as a data structure for creating the subdivision
  22733. const v = [];
  22734. // construct all of the vertices for this subdivision
  22735. for ( let i = 0; i <= cols; i ++ ) {
  22736. v[ i ] = [];
  22737. const aj = a.clone().lerp( c, i / cols );
  22738. const bj = b.clone().lerp( c, i / cols );
  22739. const rows = cols - i;
  22740. for ( let j = 0; j <= rows; j ++ ) {
  22741. if ( j === 0 && i === cols ) {
  22742. v[ i ][ j ] = aj;
  22743. } else {
  22744. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22745. }
  22746. }
  22747. }
  22748. // construct all of the faces
  22749. for ( let i = 0; i < cols; i ++ ) {
  22750. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22751. const k = Math.floor( j / 2 );
  22752. if ( j % 2 === 0 ) {
  22753. pushVertex( v[ i ][ k + 1 ] );
  22754. pushVertex( v[ i + 1 ][ k ] );
  22755. pushVertex( v[ i ][ k ] );
  22756. } else {
  22757. pushVertex( v[ i ][ k + 1 ] );
  22758. pushVertex( v[ i + 1 ][ k + 1 ] );
  22759. pushVertex( v[ i + 1 ][ k ] );
  22760. }
  22761. }
  22762. }
  22763. }
  22764. function applyRadius( radius ) {
  22765. const vertex = new Vector3();
  22766. // iterate over the entire buffer and apply the radius to each vertex
  22767. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22768. vertex.x = vertexBuffer[ i + 0 ];
  22769. vertex.y = vertexBuffer[ i + 1 ];
  22770. vertex.z = vertexBuffer[ i + 2 ];
  22771. vertex.normalize().multiplyScalar( radius );
  22772. vertexBuffer[ i + 0 ] = vertex.x;
  22773. vertexBuffer[ i + 1 ] = vertex.y;
  22774. vertexBuffer[ i + 2 ] = vertex.z;
  22775. }
  22776. }
  22777. function generateUVs() {
  22778. const vertex = new Vector3();
  22779. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22780. vertex.x = vertexBuffer[ i + 0 ];
  22781. vertex.y = vertexBuffer[ i + 1 ];
  22782. vertex.z = vertexBuffer[ i + 2 ];
  22783. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22784. const v = inclination( vertex ) / Math.PI + 0.5;
  22785. uvBuffer.push( u, 1 - v );
  22786. }
  22787. correctUVs();
  22788. correctSeam();
  22789. }
  22790. function correctSeam() {
  22791. // handle case when face straddles the seam, see #3269
  22792. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22793. // uv data of a single face
  22794. const x0 = uvBuffer[ i + 0 ];
  22795. const x1 = uvBuffer[ i + 2 ];
  22796. const x2 = uvBuffer[ i + 4 ];
  22797. const max = Math.max( x0, x1, x2 );
  22798. const min = Math.min( x0, x1, x2 );
  22799. // 0.9 is somewhat arbitrary
  22800. if ( max > 0.9 && min < 0.1 ) {
  22801. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  22802. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  22803. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  22804. }
  22805. }
  22806. }
  22807. function pushVertex( vertex ) {
  22808. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22809. }
  22810. function getVertexByIndex( index, vertex ) {
  22811. const stride = index * 3;
  22812. vertex.x = vertices[ stride + 0 ];
  22813. vertex.y = vertices[ stride + 1 ];
  22814. vertex.z = vertices[ stride + 2 ];
  22815. }
  22816. function correctUVs() {
  22817. const a = new Vector3();
  22818. const b = new Vector3();
  22819. const c = new Vector3();
  22820. const centroid = new Vector3();
  22821. const uvA = new Vector2();
  22822. const uvB = new Vector2();
  22823. const uvC = new Vector2();
  22824. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  22825. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  22826. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  22827. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  22828. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  22829. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  22830. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  22831. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  22832. const azi = azimuth( centroid );
  22833. correctUV( uvA, j + 0, a, azi );
  22834. correctUV( uvB, j + 2, b, azi );
  22835. correctUV( uvC, j + 4, c, azi );
  22836. }
  22837. }
  22838. function correctUV( uv, stride, vector, azimuth ) {
  22839. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  22840. uvBuffer[ stride ] = uv.x - 1;
  22841. }
  22842. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  22843. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  22844. }
  22845. }
  22846. // Angle around the Y axis, counter-clockwise when looking from above.
  22847. function azimuth( vector ) {
  22848. return Math.atan2( vector.z, - vector.x );
  22849. }
  22850. // Angle above the XZ plane.
  22851. function inclination( vector ) {
  22852. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22853. }
  22854. }
  22855. copy( source ) {
  22856. super.copy( source );
  22857. this.parameters = Object.assign( {}, source.parameters );
  22858. return this;
  22859. }
  22860. /**
  22861. * Factory method for creating an instance of this class from the given
  22862. * JSON object.
  22863. *
  22864. * @param {Object} data - A JSON object representing the serialized geometry.
  22865. * @return {PolyhedronGeometry} A new instance.
  22866. */
  22867. static fromJSON( data ) {
  22868. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  22869. }
  22870. }
  22871. /**
  22872. * A geometry class for representing a dodecahedron.
  22873. *
  22874. * ```js
  22875. * const geometry = new THREE.DodecahedronGeometry();
  22876. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22877. * const dodecahedron = new THREE.Mesh( geometry, material );
  22878. * scene.add( dodecahedron );
  22879. * ```
  22880. *
  22881. * @augments PolyhedronGeometry
  22882. */
  22883. class DodecahedronGeometry extends PolyhedronGeometry {
  22884. /**
  22885. * Constructs a new dodecahedron geometry.
  22886. *
  22887. * @param {number} [radius=1] - Radius of the dodecahedron.
  22888. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  22889. */
  22890. constructor( radius = 1, detail = 0 ) {
  22891. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22892. const r = 1 / t;
  22893. const vertices = [
  22894. // (±1, ±1, ±1)
  22895. -1, -1, -1, -1, -1, 1,
  22896. -1, 1, -1, -1, 1, 1,
  22897. 1, -1, -1, 1, -1, 1,
  22898. 1, 1, -1, 1, 1, 1,
  22899. // (0, ±1/φ, ±φ)
  22900. 0, - r, - t, 0, - r, t,
  22901. 0, r, - t, 0, r, t,
  22902. // (±1/φ, ±φ, 0)
  22903. - r, - t, 0, - r, t, 0,
  22904. r, - t, 0, r, t, 0,
  22905. // (±φ, 0, ±1/φ)
  22906. - t, 0, - r, t, 0, - r,
  22907. - t, 0, r, t, 0, r
  22908. ];
  22909. const indices = [
  22910. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22911. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22912. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22913. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22914. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22915. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22916. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22917. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22918. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22919. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22920. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22921. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22922. ];
  22923. super( vertices, indices, radius, detail );
  22924. this.type = 'DodecahedronGeometry';
  22925. /**
  22926. * Holds the constructor parameters that have been
  22927. * used to generate the geometry. Any modification
  22928. * after instantiation does not change the geometry.
  22929. *
  22930. * @type {Object}
  22931. */
  22932. this.parameters = {
  22933. radius: radius,
  22934. detail: detail
  22935. };
  22936. }
  22937. /**
  22938. * Factory method for creating an instance of this class from the given
  22939. * JSON object.
  22940. *
  22941. * @param {Object} data - A JSON object representing the serialized geometry.
  22942. * @return {DodecahedronGeometry} A new instance.
  22943. */
  22944. static fromJSON( data ) {
  22945. return new DodecahedronGeometry( data.radius, data.detail );
  22946. }
  22947. }
  22948. const _v0$1 = /*@__PURE__*/ new Vector3();
  22949. const _v1$1 = /*@__PURE__*/ new Vector3();
  22950. const _normal = /*@__PURE__*/ new Vector3();
  22951. const _triangle = /*@__PURE__*/ new Triangle();
  22952. /**
  22953. * Can be used as a helper object to view the edges of a geometry.
  22954. *
  22955. * ```js
  22956. * const geometry = new THREE.BoxGeometry();
  22957. * const edges = new THREE.EdgesGeometry( geometry );
  22958. * const line = new THREE.LineSegments( edges );
  22959. * scene.add( line );
  22960. * ```
  22961. *
  22962. * Note: It is not yet possible to serialize/deserialize instances of this class.
  22963. *
  22964. * @augments BufferGeometry
  22965. */
  22966. class EdgesGeometry extends BufferGeometry {
  22967. /**
  22968. * Constructs a new edges geometry.
  22969. *
  22970. * @param {?BufferGeometry} [geometry=null] - The geometry.
  22971. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  22972. * between the face normals of the adjoining faces exceeds this value.
  22973. */
  22974. constructor( geometry = null, thresholdAngle = 1 ) {
  22975. super();
  22976. this.type = 'EdgesGeometry';
  22977. /**
  22978. * Holds the constructor parameters that have been
  22979. * used to generate the geometry. Any modification
  22980. * after instantiation does not change the geometry.
  22981. *
  22982. * @type {Object}
  22983. */
  22984. this.parameters = {
  22985. geometry: geometry,
  22986. thresholdAngle: thresholdAngle
  22987. };
  22988. if ( geometry !== null ) {
  22989. const precisionPoints = 4;
  22990. const precision = Math.pow( 10, precisionPoints );
  22991. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  22992. const indexAttr = geometry.getIndex();
  22993. const positionAttr = geometry.getAttribute( 'position' );
  22994. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  22995. const indexArr = [ 0, 0, 0 ];
  22996. const vertKeys = [ 'a', 'b', 'c' ];
  22997. const hashes = new Array( 3 );
  22998. const edgeData = {};
  22999. const vertices = [];
  23000. for ( let i = 0; i < indexCount; i += 3 ) {
  23001. if ( indexAttr ) {
  23002. indexArr[ 0 ] = indexAttr.getX( i );
  23003. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  23004. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  23005. } else {
  23006. indexArr[ 0 ] = i;
  23007. indexArr[ 1 ] = i + 1;
  23008. indexArr[ 2 ] = i + 2;
  23009. }
  23010. const { a, b, c } = _triangle;
  23011. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  23012. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  23013. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  23014. _triangle.getNormal( _normal );
  23015. // create hashes for the edge from the vertices
  23016. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  23017. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  23018. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  23019. // skip degenerate triangles
  23020. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  23021. continue;
  23022. }
  23023. // iterate over every edge
  23024. for ( let j = 0; j < 3; j ++ ) {
  23025. // get the first and next vertex making up the edge
  23026. const jNext = ( j + 1 ) % 3;
  23027. const vecHash0 = hashes[ j ];
  23028. const vecHash1 = hashes[ jNext ];
  23029. const v0 = _triangle[ vertKeys[ j ] ];
  23030. const v1 = _triangle[ vertKeys[ jNext ] ];
  23031. const hash = `${ vecHash0 }_${ vecHash1 }`;
  23032. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  23033. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  23034. // if we found a sibling edge add it into the vertex array if
  23035. // it meets the angle threshold and delete the edge from the map.
  23036. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  23037. vertices.push( v0.x, v0.y, v0.z );
  23038. vertices.push( v1.x, v1.y, v1.z );
  23039. }
  23040. edgeData[ reverseHash ] = null;
  23041. } else if ( ! ( hash in edgeData ) ) {
  23042. // if we've already got an edge here then skip adding a new one
  23043. edgeData[ hash ] = {
  23044. index0: indexArr[ j ],
  23045. index1: indexArr[ jNext ],
  23046. normal: _normal.clone(),
  23047. };
  23048. }
  23049. }
  23050. }
  23051. // iterate over all remaining, unmatched edges and add them to the vertex array
  23052. for ( const key in edgeData ) {
  23053. if ( edgeData[ key ] ) {
  23054. const { index0, index1 } = edgeData[ key ];
  23055. _v0$1.fromBufferAttribute( positionAttr, index0 );
  23056. _v1$1.fromBufferAttribute( positionAttr, index1 );
  23057. vertices.push( _v0$1.x, _v0$1.y, _v0$1.z );
  23058. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  23059. }
  23060. }
  23061. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23062. }
  23063. }
  23064. copy( source ) {
  23065. super.copy( source );
  23066. this.parameters = Object.assign( {}, source.parameters );
  23067. return this;
  23068. }
  23069. }
  23070. /**
  23071. * An abstract base class for creating an analytic curve object that contains methods
  23072. * for interpolation.
  23073. *
  23074. * @abstract
  23075. */
  23076. class Curve {
  23077. /**
  23078. * Constructs a new curve.
  23079. */
  23080. constructor() {
  23081. /**
  23082. * The type property is used for detecting the object type
  23083. * in context of serialization/deserialization.
  23084. *
  23085. * @type {string}
  23086. * @readonly
  23087. */
  23088. this.type = 'Curve';
  23089. /**
  23090. * This value determines the amount of divisions when calculating the
  23091. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  23092. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  23093. * recommended to increase the value of this property if the curve is very large.
  23094. *
  23095. * @type {number}
  23096. * @default 200
  23097. */
  23098. this.arcLengthDivisions = 200;
  23099. /**
  23100. * Must be set to `true` if the curve parameters have changed.
  23101. *
  23102. * @type {boolean}
  23103. * @default false
  23104. */
  23105. this.needsUpdate = false;
  23106. /**
  23107. * An internal cache that holds precomputed curve length values.
  23108. *
  23109. * @private
  23110. * @type {?Array<number>}
  23111. * @default null
  23112. */
  23113. this.cacheArcLengths = null;
  23114. }
  23115. /**
  23116. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23117. * for the given interpolation factor.
  23118. *
  23119. * @abstract
  23120. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23121. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23122. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23123. */
  23124. getPoint( /* t, optionalTarget */ ) {
  23125. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  23126. }
  23127. /**
  23128. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23129. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  23130. * of the curve which equidistant samples.
  23131. *
  23132. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23133. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23134. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23135. */
  23136. getPointAt( u, optionalTarget ) {
  23137. const t = this.getUtoTmapping( u );
  23138. return this.getPoint( t, optionalTarget );
  23139. }
  23140. /**
  23141. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  23142. * the curve shape.
  23143. *
  23144. * @param {number} [divisions=5] - The number of divisions.
  23145. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23146. */
  23147. getPoints( divisions = 5 ) {
  23148. const points = [];
  23149. for ( let d = 0; d <= divisions; d ++ ) {
  23150. points.push( this.getPoint( d / divisions ) );
  23151. }
  23152. return points;
  23153. }
  23154. // Get sequence of points using getPointAt( u )
  23155. /**
  23156. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  23157. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  23158. * curve.
  23159. *
  23160. * @param {number} [divisions=5] - The number of divisions.
  23161. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23162. */
  23163. getSpacedPoints( divisions = 5 ) {
  23164. const points = [];
  23165. for ( let d = 0; d <= divisions; d ++ ) {
  23166. points.push( this.getPointAt( d / divisions ) );
  23167. }
  23168. return points;
  23169. }
  23170. /**
  23171. * Returns the total arc length of the curve.
  23172. *
  23173. * @return {number} The length of the curve.
  23174. */
  23175. getLength() {
  23176. const lengths = this.getLengths();
  23177. return lengths[ lengths.length - 1 ];
  23178. }
  23179. /**
  23180. * Returns an array of cumulative segment lengths of the curve.
  23181. *
  23182. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  23183. * @return {Array<number>} An array holding the cumulative segment lengths.
  23184. */
  23185. getLengths( divisions = this.arcLengthDivisions ) {
  23186. if ( this.cacheArcLengths &&
  23187. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23188. ! this.needsUpdate ) {
  23189. return this.cacheArcLengths;
  23190. }
  23191. this.needsUpdate = false;
  23192. const cache = [];
  23193. let current, last = this.getPoint( 0 );
  23194. let sum = 0;
  23195. cache.push( 0 );
  23196. for ( let p = 1; p <= divisions; p ++ ) {
  23197. current = this.getPoint( p / divisions );
  23198. sum += current.distanceTo( last );
  23199. cache.push( sum );
  23200. last = current;
  23201. }
  23202. this.cacheArcLengths = cache;
  23203. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23204. }
  23205. /**
  23206. * Update the cumulative segment distance cache. The method must be called
  23207. * every time curve parameters are changed. If an updated curve is part of a
  23208. * composed curve like {@link CurvePath}, this method must be called on the
  23209. * composed curve, too.
  23210. */
  23211. updateArcLengths() {
  23212. this.needsUpdate = true;
  23213. this.getLengths();
  23214. }
  23215. /**
  23216. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  23217. * interpolation factor in the same range that can be ued to sample equidistant points
  23218. * from a curve.
  23219. *
  23220. * @param {number} u - The interpolation factor.
  23221. * @param {?number} distance - An optional distance on the curve.
  23222. * @return {number} The updated interpolation factor.
  23223. */
  23224. getUtoTmapping( u, distance = null ) {
  23225. const arcLengths = this.getLengths();
  23226. let i = 0;
  23227. const il = arcLengths.length;
  23228. let targetArcLength; // The targeted u distance value to get
  23229. if ( distance ) {
  23230. targetArcLength = distance;
  23231. } else {
  23232. targetArcLength = u * arcLengths[ il - 1 ];
  23233. }
  23234. // binary search for the index with largest value smaller than target u distance
  23235. let low = 0, high = il - 1, comparison;
  23236. while ( low <= high ) {
  23237. 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
  23238. comparison = arcLengths[ i ] - targetArcLength;
  23239. if ( comparison < 0 ) {
  23240. low = i + 1;
  23241. } else if ( comparison > 0 ) {
  23242. high = i - 1;
  23243. } else {
  23244. high = i;
  23245. break;
  23246. // DONE
  23247. }
  23248. }
  23249. i = high;
  23250. if ( arcLengths[ i ] === targetArcLength ) {
  23251. return i / ( il - 1 );
  23252. }
  23253. // we could get finer grain at lengths, or use simple interpolation between two points
  23254. const lengthBefore = arcLengths[ i ];
  23255. const lengthAfter = arcLengths[ i + 1 ];
  23256. const segmentLength = lengthAfter - lengthBefore;
  23257. // determine where we are between the 'before' and 'after' points
  23258. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23259. // add that fractional amount to t
  23260. const t = ( i + segmentFraction ) / ( il - 1 );
  23261. return t;
  23262. }
  23263. /**
  23264. * Returns a unit vector tangent for the given interpolation factor.
  23265. * If the derived curve does not implement its tangent derivation,
  23266. * two points a small delta apart will be used to find its gradient
  23267. * which seems to give a reasonable approximation.
  23268. *
  23269. * @param {number} t - The interpolation factor.
  23270. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23271. * @return {(Vector2|Vector3)} The tangent vector.
  23272. */
  23273. getTangent( t, optionalTarget ) {
  23274. const delta = 0.0001;
  23275. let t1 = t - delta;
  23276. let t2 = t + delta;
  23277. // Capping in case of danger
  23278. if ( t1 < 0 ) t1 = 0;
  23279. if ( t2 > 1 ) t2 = 1;
  23280. const pt1 = this.getPoint( t1 );
  23281. const pt2 = this.getPoint( t2 );
  23282. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  23283. tangent.copy( pt2 ).sub( pt1 ).normalize();
  23284. return tangent;
  23285. }
  23286. /**
  23287. * Same as {@link Curve#getTangent} but with equidistant samples.
  23288. *
  23289. * @param {number} u - The interpolation factor.
  23290. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23291. * @return {(Vector2|Vector3)} The tangent vector.
  23292. * @see {@link Curve#getPointAt}
  23293. */
  23294. getTangentAt( u, optionalTarget ) {
  23295. const t = this.getUtoTmapping( u );
  23296. return this.getTangent( t, optionalTarget );
  23297. }
  23298. /**
  23299. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  23300. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  23301. *
  23302. * @param {number} segments - The number of segments.
  23303. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23304. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  23305. */
  23306. computeFrenetFrames( segments, closed = false ) {
  23307. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23308. const normal = new Vector3();
  23309. const tangents = [];
  23310. const normals = [];
  23311. const binormals = [];
  23312. const vec = new Vector3();
  23313. const mat = new Matrix4();
  23314. // compute the tangent vectors for each segment on the curve
  23315. for ( let i = 0; i <= segments; i ++ ) {
  23316. const u = i / segments;
  23317. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23318. }
  23319. // select an initial normal vector perpendicular to the first tangent vector,
  23320. // and in the direction of the minimum tangent xyz component
  23321. normals[ 0 ] = new Vector3();
  23322. binormals[ 0 ] = new Vector3();
  23323. let min = Number.MAX_VALUE;
  23324. const tx = Math.abs( tangents[ 0 ].x );
  23325. const ty = Math.abs( tangents[ 0 ].y );
  23326. const tz = Math.abs( tangents[ 0 ].z );
  23327. if ( tx <= min ) {
  23328. min = tx;
  23329. normal.set( 1, 0, 0 );
  23330. }
  23331. if ( ty <= min ) {
  23332. min = ty;
  23333. normal.set( 0, 1, 0 );
  23334. }
  23335. if ( tz <= min ) {
  23336. normal.set( 0, 0, 1 );
  23337. }
  23338. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23339. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23340. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23341. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23342. for ( let i = 1; i <= segments; i ++ ) {
  23343. normals[ i ] = normals[ i - 1 ].clone();
  23344. binormals[ i ] = binormals[ i - 1 ].clone();
  23345. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23346. if ( vec.length() > Number.EPSILON ) {
  23347. vec.normalize();
  23348. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  23349. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23350. }
  23351. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23352. }
  23353. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23354. if ( closed === true ) {
  23355. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  23356. theta /= segments;
  23357. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23358. theta = - theta;
  23359. }
  23360. for ( let i = 1; i <= segments; i ++ ) {
  23361. // twist a little...
  23362. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23363. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23364. }
  23365. }
  23366. return {
  23367. tangents: tangents,
  23368. normals: normals,
  23369. binormals: binormals
  23370. };
  23371. }
  23372. /**
  23373. * Returns a new curve with copied values from this instance.
  23374. *
  23375. * @return {Curve} A clone of this instance.
  23376. */
  23377. clone() {
  23378. return new this.constructor().copy( this );
  23379. }
  23380. /**
  23381. * Copies the values of the given curve to this instance.
  23382. *
  23383. * @param {Curve} source - The curve to copy.
  23384. * @return {Curve} A reference to this curve.
  23385. */
  23386. copy( source ) {
  23387. this.arcLengthDivisions = source.arcLengthDivisions;
  23388. return this;
  23389. }
  23390. /**
  23391. * Serializes the curve into JSON.
  23392. *
  23393. * @return {Object} A JSON object representing the serialized curve.
  23394. * @see {@link ObjectLoader#parse}
  23395. */
  23396. toJSON() {
  23397. const data = {
  23398. metadata: {
  23399. version: 4.7,
  23400. type: 'Curve',
  23401. generator: 'Curve.toJSON'
  23402. }
  23403. };
  23404. data.arcLengthDivisions = this.arcLengthDivisions;
  23405. data.type = this.type;
  23406. return data;
  23407. }
  23408. /**
  23409. * Deserializes the curve from the given JSON.
  23410. *
  23411. * @param {Object} json - The JSON holding the serialized curve.
  23412. * @return {Curve} A reference to this curve.
  23413. */
  23414. fromJSON( json ) {
  23415. this.arcLengthDivisions = json.arcLengthDivisions;
  23416. return this;
  23417. }
  23418. }
  23419. /**
  23420. * A curve representing an ellipse.
  23421. *
  23422. * ```js
  23423. * const curve = new THREE.EllipseCurve(
  23424. * 0, 0,
  23425. * 10, 10,
  23426. * 0, 2 * Math.PI,
  23427. * false,
  23428. * 0
  23429. * );
  23430. *
  23431. * const points = curve.getPoints( 50 );
  23432. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23433. *
  23434. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23435. *
  23436. * // Create the final object to add to the scene
  23437. * const ellipse = new THREE.Line( geometry, material );
  23438. * ```
  23439. *
  23440. * @augments Curve
  23441. */
  23442. class EllipseCurve extends Curve {
  23443. /**
  23444. * Constructs a new ellipse curve.
  23445. *
  23446. * @param {number} [aX=0] - The X center of the ellipse.
  23447. * @param {number} [aY=0] - The Y center of the ellipse.
  23448. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  23449. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  23450. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23451. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23452. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23453. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23454. */
  23455. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  23456. super();
  23457. /**
  23458. * This flag can be used for type testing.
  23459. *
  23460. * @type {boolean}
  23461. * @readonly
  23462. * @default true
  23463. */
  23464. this.isEllipseCurve = true;
  23465. this.type = 'EllipseCurve';
  23466. /**
  23467. * The X center of the ellipse.
  23468. *
  23469. * @type {number}
  23470. * @default 0
  23471. */
  23472. this.aX = aX;
  23473. /**
  23474. * The Y center of the ellipse.
  23475. *
  23476. * @type {number}
  23477. * @default 0
  23478. */
  23479. this.aY = aY;
  23480. /**
  23481. * The radius of the ellipse in the x direction.
  23482. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  23483. *
  23484. * @type {number}
  23485. * @default 1
  23486. */
  23487. this.xRadius = xRadius;
  23488. /**
  23489. * The radius of the ellipse in the y direction.
  23490. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  23491. *
  23492. * @type {number}
  23493. * @default 1
  23494. */
  23495. this.yRadius = yRadius;
  23496. /**
  23497. * The start angle of the curve in radians starting from the positive X axis.
  23498. *
  23499. * @type {number}
  23500. * @default 0
  23501. */
  23502. this.aStartAngle = aStartAngle;
  23503. /**
  23504. * The end angle of the curve in radians starting from the positive X axis.
  23505. *
  23506. * @type {number}
  23507. * @default Math.PI*2
  23508. */
  23509. this.aEndAngle = aEndAngle;
  23510. /**
  23511. * Whether the ellipse is drawn clockwise or not.
  23512. *
  23513. * @type {boolean}
  23514. * @default false
  23515. */
  23516. this.aClockwise = aClockwise;
  23517. /**
  23518. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23519. *
  23520. * @type {number}
  23521. * @default 0
  23522. */
  23523. this.aRotation = aRotation;
  23524. }
  23525. /**
  23526. * Returns a point on the curve.
  23527. *
  23528. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23529. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23530. * @return {Vector2} The position on the curve.
  23531. */
  23532. getPoint( t, optionalTarget = new Vector2() ) {
  23533. const point = optionalTarget;
  23534. const twoPi = Math.PI * 2;
  23535. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23536. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23537. // ensures that deltaAngle is 0 .. 2 PI
  23538. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23539. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23540. if ( deltaAngle < Number.EPSILON ) {
  23541. if ( samePoints ) {
  23542. deltaAngle = 0;
  23543. } else {
  23544. deltaAngle = twoPi;
  23545. }
  23546. }
  23547. if ( this.aClockwise === true && ! samePoints ) {
  23548. if ( deltaAngle === twoPi ) {
  23549. deltaAngle = - twoPi;
  23550. } else {
  23551. deltaAngle = deltaAngle - twoPi;
  23552. }
  23553. }
  23554. const angle = this.aStartAngle + t * deltaAngle;
  23555. let x = this.aX + this.xRadius * Math.cos( angle );
  23556. let y = this.aY + this.yRadius * Math.sin( angle );
  23557. if ( this.aRotation !== 0 ) {
  23558. const cos = Math.cos( this.aRotation );
  23559. const sin = Math.sin( this.aRotation );
  23560. const tx = x - this.aX;
  23561. const ty = y - this.aY;
  23562. // Rotate the point about the center of the ellipse.
  23563. x = tx * cos - ty * sin + this.aX;
  23564. y = tx * sin + ty * cos + this.aY;
  23565. }
  23566. return point.set( x, y );
  23567. }
  23568. copy( source ) {
  23569. super.copy( source );
  23570. this.aX = source.aX;
  23571. this.aY = source.aY;
  23572. this.xRadius = source.xRadius;
  23573. this.yRadius = source.yRadius;
  23574. this.aStartAngle = source.aStartAngle;
  23575. this.aEndAngle = source.aEndAngle;
  23576. this.aClockwise = source.aClockwise;
  23577. this.aRotation = source.aRotation;
  23578. return this;
  23579. }
  23580. toJSON() {
  23581. const data = super.toJSON();
  23582. data.aX = this.aX;
  23583. data.aY = this.aY;
  23584. data.xRadius = this.xRadius;
  23585. data.yRadius = this.yRadius;
  23586. data.aStartAngle = this.aStartAngle;
  23587. data.aEndAngle = this.aEndAngle;
  23588. data.aClockwise = this.aClockwise;
  23589. data.aRotation = this.aRotation;
  23590. return data;
  23591. }
  23592. fromJSON( json ) {
  23593. super.fromJSON( json );
  23594. this.aX = json.aX;
  23595. this.aY = json.aY;
  23596. this.xRadius = json.xRadius;
  23597. this.yRadius = json.yRadius;
  23598. this.aStartAngle = json.aStartAngle;
  23599. this.aEndAngle = json.aEndAngle;
  23600. this.aClockwise = json.aClockwise;
  23601. this.aRotation = json.aRotation;
  23602. return this;
  23603. }
  23604. }
  23605. /**
  23606. * A curve representing an arc.
  23607. *
  23608. * @augments EllipseCurve
  23609. */
  23610. class ArcCurve extends EllipseCurve {
  23611. /**
  23612. * Constructs a new arc curve.
  23613. *
  23614. * @param {number} [aX=0] - The X center of the ellipse.
  23615. * @param {number} [aY=0] - The Y center of the ellipse.
  23616. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  23617. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23618. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23619. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23620. */
  23621. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23622. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23623. /**
  23624. * This flag can be used for type testing.
  23625. *
  23626. * @type {boolean}
  23627. * @readonly
  23628. * @default true
  23629. */
  23630. this.isArcCurve = true;
  23631. this.type = 'ArcCurve';
  23632. }
  23633. }
  23634. function CubicPoly() {
  23635. /**
  23636. * Centripetal CatmullRom Curve - which is useful for avoiding
  23637. * cusps and self-intersections in non-uniform catmull rom curves.
  23638. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23639. *
  23640. * curve.type accepts centripetal(default), chordal and catmullrom
  23641. * curve.tension is used for catmullrom which defaults to 0.5
  23642. */
  23643. /*
  23644. Based on an optimized c++ solution in
  23645. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23646. - http://ideone.com/NoEbVM
  23647. This CubicPoly class could be used for reusing some variables and calculations,
  23648. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23649. which can be placed in CurveUtils.
  23650. */
  23651. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23652. /*
  23653. * Compute coefficients for a cubic polynomial
  23654. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23655. * such that
  23656. * p(0) = x0, p(1) = x1
  23657. * and
  23658. * p'(0) = t0, p'(1) = t1.
  23659. */
  23660. function init( x0, x1, t0, t1 ) {
  23661. c0 = x0;
  23662. c1 = t0;
  23663. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23664. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23665. }
  23666. return {
  23667. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23668. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23669. },
  23670. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23671. // compute tangents when parameterized in [t1,t2]
  23672. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23673. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23674. // rescale tangents for parametrization in [0,1]
  23675. t1 *= dt1;
  23676. t2 *= dt1;
  23677. init( x1, x2, t1, t2 );
  23678. },
  23679. calc: function ( t ) {
  23680. const t2 = t * t;
  23681. const t3 = t2 * t;
  23682. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23683. }
  23684. };
  23685. }
  23686. //
  23687. const tmp = /*@__PURE__*/ new Vector3();
  23688. const px = /*@__PURE__*/ new CubicPoly();
  23689. const py = /*@__PURE__*/ new CubicPoly();
  23690. const pz = /*@__PURE__*/ new CubicPoly();
  23691. /**
  23692. * A curve representing a Catmull-Rom spline.
  23693. *
  23694. * ```js
  23695. * //Create a closed wavey loop
  23696. * const curve = new THREE.CatmullRomCurve3( [
  23697. * new THREE.Vector3( -10, 0, 10 ),
  23698. * new THREE.Vector3( -5, 5, 5 ),
  23699. * new THREE.Vector3( 0, 0, 0 ),
  23700. * new THREE.Vector3( 5, -5, 5 ),
  23701. * new THREE.Vector3( 10, 0, 10 )
  23702. * ] );
  23703. *
  23704. * const points = curve.getPoints( 50 );
  23705. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23706. *
  23707. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23708. *
  23709. * // Create the final object to add to the scene
  23710. * const curveObject = new THREE.Line( geometry, material );
  23711. * ```
  23712. *
  23713. * @augments Curve
  23714. */
  23715. class CatmullRomCurve3 extends Curve {
  23716. /**
  23717. * Constructs a new Catmull-Rom curve.
  23718. *
  23719. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  23720. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23721. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  23722. * @param {number} [tension=0.5] - Tension of the curve.
  23723. */
  23724. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23725. super();
  23726. /**
  23727. * This flag can be used for type testing.
  23728. *
  23729. * @type {boolean}
  23730. * @readonly
  23731. * @default true
  23732. */
  23733. this.isCatmullRomCurve3 = true;
  23734. this.type = 'CatmullRomCurve3';
  23735. /**
  23736. * An array of 3D points defining the curve.
  23737. *
  23738. * @type {Array<Vector3>}
  23739. */
  23740. this.points = points;
  23741. /**
  23742. * Whether the curve is closed or not.
  23743. *
  23744. * @type {boolean}
  23745. * @default false
  23746. */
  23747. this.closed = closed;
  23748. /**
  23749. * The curve type.
  23750. *
  23751. * @type {('centripetal'|'chordal'|'catmullrom')}
  23752. * @default 'centripetal'
  23753. */
  23754. this.curveType = curveType;
  23755. /**
  23756. * Tension of the curve.
  23757. *
  23758. * @type {number}
  23759. * @default 0.5
  23760. */
  23761. this.tension = tension;
  23762. }
  23763. /**
  23764. * Returns a point on the curve.
  23765. *
  23766. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23767. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23768. * @return {Vector3} The position on the curve.
  23769. */
  23770. getPoint( t, optionalTarget = new Vector3() ) {
  23771. const point = optionalTarget;
  23772. const points = this.points;
  23773. const l = points.length;
  23774. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23775. let intPoint = Math.floor( p );
  23776. let weight = p - intPoint;
  23777. if ( this.closed ) {
  23778. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23779. } else if ( weight === 0 && intPoint === l - 1 ) {
  23780. intPoint = l - 2;
  23781. weight = 1;
  23782. }
  23783. let p0, p3; // 4 points (p1 & p2 defined below)
  23784. if ( this.closed || intPoint > 0 ) {
  23785. p0 = points[ ( intPoint - 1 ) % l ];
  23786. } else {
  23787. // extrapolate first point
  23788. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23789. p0 = tmp;
  23790. }
  23791. const p1 = points[ intPoint % l ];
  23792. const p2 = points[ ( intPoint + 1 ) % l ];
  23793. if ( this.closed || intPoint + 2 < l ) {
  23794. p3 = points[ ( intPoint + 2 ) % l ];
  23795. } else {
  23796. // extrapolate last point
  23797. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23798. p3 = tmp;
  23799. }
  23800. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23801. // init Centripetal / Chordal Catmull-Rom
  23802. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23803. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23804. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23805. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23806. // safety check for repeated points
  23807. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23808. if ( dt0 < 1e-4 ) dt0 = dt1;
  23809. if ( dt2 < 1e-4 ) dt2 = dt1;
  23810. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  23811. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  23812. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  23813. } else if ( this.curveType === 'catmullrom' ) {
  23814. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  23815. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  23816. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  23817. }
  23818. point.set(
  23819. px.calc( weight ),
  23820. py.calc( weight ),
  23821. pz.calc( weight )
  23822. );
  23823. return point;
  23824. }
  23825. copy( source ) {
  23826. super.copy( source );
  23827. this.points = [];
  23828. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23829. const point = source.points[ i ];
  23830. this.points.push( point.clone() );
  23831. }
  23832. this.closed = source.closed;
  23833. this.curveType = source.curveType;
  23834. this.tension = source.tension;
  23835. return this;
  23836. }
  23837. toJSON() {
  23838. const data = super.toJSON();
  23839. data.points = [];
  23840. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23841. const point = this.points[ i ];
  23842. data.points.push( point.toArray() );
  23843. }
  23844. data.closed = this.closed;
  23845. data.curveType = this.curveType;
  23846. data.tension = this.tension;
  23847. return data;
  23848. }
  23849. fromJSON( json ) {
  23850. super.fromJSON( json );
  23851. this.points = [];
  23852. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23853. const point = json.points[ i ];
  23854. this.points.push( new Vector3().fromArray( point ) );
  23855. }
  23856. this.closed = json.closed;
  23857. this.curveType = json.curveType;
  23858. this.tension = json.tension;
  23859. return this;
  23860. }
  23861. }
  23862. // Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  23863. /**
  23864. * Computes a point on a Catmull-Rom spline.
  23865. *
  23866. * @param {number} t - The interpolation factor.
  23867. * @param {number} p0 - The first control point.
  23868. * @param {number} p1 - The second control point.
  23869. * @param {number} p2 - The third control point.
  23870. * @param {number} p3 - The fourth control point.
  23871. * @return {number} The calculated point on a Catmull-Rom spline.
  23872. */
  23873. function CatmullRom( t, p0, p1, p2, p3 ) {
  23874. const v0 = ( p2 - p0 ) * 0.5;
  23875. const v1 = ( p3 - p1 ) * 0.5;
  23876. const t2 = t * t;
  23877. const t3 = t * t2;
  23878. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23879. }
  23880. //
  23881. function QuadraticBezierP0( t, p ) {
  23882. const k = 1 - t;
  23883. return k * k * p;
  23884. }
  23885. function QuadraticBezierP1( t, p ) {
  23886. return 2 * ( 1 - t ) * t * p;
  23887. }
  23888. function QuadraticBezierP2( t, p ) {
  23889. return t * t * p;
  23890. }
  23891. /**
  23892. * Computes a point on a Quadratic Bezier curve.
  23893. *
  23894. * @param {number} t - The interpolation factor.
  23895. * @param {number} p0 - The first control point.
  23896. * @param {number} p1 - The second control point.
  23897. * @param {number} p2 - The third control point.
  23898. * @return {number} The calculated point on a Quadratic Bezier curve.
  23899. */
  23900. function QuadraticBezier( t, p0, p1, p2 ) {
  23901. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  23902. QuadraticBezierP2( t, p2 );
  23903. }
  23904. //
  23905. function CubicBezierP0( t, p ) {
  23906. const k = 1 - t;
  23907. return k * k * k * p;
  23908. }
  23909. function CubicBezierP1( t, p ) {
  23910. const k = 1 - t;
  23911. return 3 * k * k * t * p;
  23912. }
  23913. function CubicBezierP2( t, p ) {
  23914. return 3 * ( 1 - t ) * t * t * p;
  23915. }
  23916. function CubicBezierP3( t, p ) {
  23917. return t * t * t * p;
  23918. }
  23919. /**
  23920. * Computes a point on a Cubic Bezier curve.
  23921. *
  23922. * @param {number} t - The interpolation factor.
  23923. * @param {number} p0 - The first control point.
  23924. * @param {number} p1 - The second control point.
  23925. * @param {number} p2 - The third control point.
  23926. * @param {number} p3 - The fourth control point.
  23927. * @return {number} The calculated point on a Cubic Bezier curve.
  23928. */
  23929. function CubicBezier( t, p0, p1, p2, p3 ) {
  23930. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  23931. CubicBezierP3( t, p3 );
  23932. }
  23933. /**
  23934. * A curve representing a 2D Cubic Bezier curve.
  23935. *
  23936. * ```js
  23937. * const curve = new THREE.CubicBezierCurve(
  23938. * new THREE.Vector2( - 0, 0 ),
  23939. * new THREE.Vector2( - 5, 15 ),
  23940. * new THREE.Vector2( 20, 15 ),
  23941. * new THREE.Vector2( 10, 0 )
  23942. * );
  23943. *
  23944. * const points = curve.getPoints( 50 );
  23945. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23946. *
  23947. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23948. *
  23949. * // Create the final object to add to the scene
  23950. * const curveObject = new THREE.Line( geometry, material );
  23951. * ```
  23952. *
  23953. * @augments Curve
  23954. */
  23955. class CubicBezierCurve extends Curve {
  23956. /**
  23957. * Constructs a new Cubic Bezier curve.
  23958. *
  23959. * @param {Vector2} [v0] - The start point.
  23960. * @param {Vector2} [v1] - The first control point.
  23961. * @param {Vector2} [v2] - The second control point.
  23962. * @param {Vector2} [v3] - The end point.
  23963. */
  23964. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  23965. super();
  23966. /**
  23967. * This flag can be used for type testing.
  23968. *
  23969. * @type {boolean}
  23970. * @readonly
  23971. * @default true
  23972. */
  23973. this.isCubicBezierCurve = true;
  23974. this.type = 'CubicBezierCurve';
  23975. /**
  23976. * The start point.
  23977. *
  23978. * @type {Vector2}
  23979. */
  23980. this.v0 = v0;
  23981. /**
  23982. * The first control point.
  23983. *
  23984. * @type {Vector2}
  23985. */
  23986. this.v1 = v1;
  23987. /**
  23988. * The second control point.
  23989. *
  23990. * @type {Vector2}
  23991. */
  23992. this.v2 = v2;
  23993. /**
  23994. * The end point.
  23995. *
  23996. * @type {Vector2}
  23997. */
  23998. this.v3 = v3;
  23999. }
  24000. /**
  24001. * Returns a point on the curve.
  24002. *
  24003. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24004. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24005. * @return {Vector2} The position on the curve.
  24006. */
  24007. getPoint( t, optionalTarget = new Vector2() ) {
  24008. const point = optionalTarget;
  24009. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24010. point.set(
  24011. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24012. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  24013. );
  24014. return point;
  24015. }
  24016. copy( source ) {
  24017. super.copy( source );
  24018. this.v0.copy( source.v0 );
  24019. this.v1.copy( source.v1 );
  24020. this.v2.copy( source.v2 );
  24021. this.v3.copy( source.v3 );
  24022. return this;
  24023. }
  24024. toJSON() {
  24025. const data = super.toJSON();
  24026. data.v0 = this.v0.toArray();
  24027. data.v1 = this.v1.toArray();
  24028. data.v2 = this.v2.toArray();
  24029. data.v3 = this.v3.toArray();
  24030. return data;
  24031. }
  24032. fromJSON( json ) {
  24033. super.fromJSON( json );
  24034. this.v0.fromArray( json.v0 );
  24035. this.v1.fromArray( json.v1 );
  24036. this.v2.fromArray( json.v2 );
  24037. this.v3.fromArray( json.v3 );
  24038. return this;
  24039. }
  24040. }
  24041. /**
  24042. * A curve representing a 3D Cubic Bezier curve.
  24043. *
  24044. * @augments Curve
  24045. */
  24046. class CubicBezierCurve3 extends Curve {
  24047. /**
  24048. * Constructs a new Cubic Bezier curve.
  24049. *
  24050. * @param {Vector3} [v0] - The start point.
  24051. * @param {Vector3} [v1] - The first control point.
  24052. * @param {Vector3} [v2] - The second control point.
  24053. * @param {Vector3} [v3] - The end point.
  24054. */
  24055. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  24056. super();
  24057. /**
  24058. * This flag can be used for type testing.
  24059. *
  24060. * @type {boolean}
  24061. * @readonly
  24062. * @default true
  24063. */
  24064. this.isCubicBezierCurve3 = true;
  24065. this.type = 'CubicBezierCurve3';
  24066. /**
  24067. * The start point.
  24068. *
  24069. * @type {Vector3}
  24070. */
  24071. this.v0 = v0;
  24072. /**
  24073. * The first control point.
  24074. *
  24075. * @type {Vector3}
  24076. */
  24077. this.v1 = v1;
  24078. /**
  24079. * The second control point.
  24080. *
  24081. * @type {Vector3}
  24082. */
  24083. this.v2 = v2;
  24084. /**
  24085. * The end point.
  24086. *
  24087. * @type {Vector3}
  24088. */
  24089. this.v3 = v3;
  24090. }
  24091. /**
  24092. * Returns a point on the curve.
  24093. *
  24094. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24095. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24096. * @return {Vector3} The position on the curve.
  24097. */
  24098. getPoint( t, optionalTarget = new Vector3() ) {
  24099. const point = optionalTarget;
  24100. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24101. point.set(
  24102. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24103. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  24104. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  24105. );
  24106. return point;
  24107. }
  24108. copy( source ) {
  24109. super.copy( source );
  24110. this.v0.copy( source.v0 );
  24111. this.v1.copy( source.v1 );
  24112. this.v2.copy( source.v2 );
  24113. this.v3.copy( source.v3 );
  24114. return this;
  24115. }
  24116. toJSON() {
  24117. const data = super.toJSON();
  24118. data.v0 = this.v0.toArray();
  24119. data.v1 = this.v1.toArray();
  24120. data.v2 = this.v2.toArray();
  24121. data.v3 = this.v3.toArray();
  24122. return data;
  24123. }
  24124. fromJSON( json ) {
  24125. super.fromJSON( json );
  24126. this.v0.fromArray( json.v0 );
  24127. this.v1.fromArray( json.v1 );
  24128. this.v2.fromArray( json.v2 );
  24129. this.v3.fromArray( json.v3 );
  24130. return this;
  24131. }
  24132. }
  24133. /**
  24134. * A curve representing a 2D line segment.
  24135. *
  24136. * @augments Curve
  24137. */
  24138. class LineCurve extends Curve {
  24139. /**
  24140. * Constructs a new line curve.
  24141. *
  24142. * @param {Vector2} [v1] - The start point.
  24143. * @param {Vector2} [v2] - The end point.
  24144. */
  24145. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  24146. super();
  24147. /**
  24148. * This flag can be used for type testing.
  24149. *
  24150. * @type {boolean}
  24151. * @readonly
  24152. * @default true
  24153. */
  24154. this.isLineCurve = true;
  24155. this.type = 'LineCurve';
  24156. /**
  24157. * The start point.
  24158. *
  24159. * @type {Vector2}
  24160. */
  24161. this.v1 = v1;
  24162. /**
  24163. * The end point.
  24164. *
  24165. * @type {Vector2}
  24166. */
  24167. this.v2 = v2;
  24168. }
  24169. /**
  24170. * Returns a point on the line.
  24171. *
  24172. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24173. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24174. * @return {Vector2} The position on the line.
  24175. */
  24176. getPoint( t, optionalTarget = new Vector2() ) {
  24177. const point = optionalTarget;
  24178. if ( t === 1 ) {
  24179. point.copy( this.v2 );
  24180. } else {
  24181. point.copy( this.v2 ).sub( this.v1 );
  24182. point.multiplyScalar( t ).add( this.v1 );
  24183. }
  24184. return point;
  24185. }
  24186. // Line curve is linear, so we can overwrite default getPointAt
  24187. getPointAt( u, optionalTarget ) {
  24188. return this.getPoint( u, optionalTarget );
  24189. }
  24190. getTangent( t, optionalTarget = new Vector2() ) {
  24191. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24192. }
  24193. getTangentAt( u, optionalTarget ) {
  24194. return this.getTangent( u, optionalTarget );
  24195. }
  24196. copy( source ) {
  24197. super.copy( source );
  24198. this.v1.copy( source.v1 );
  24199. this.v2.copy( source.v2 );
  24200. return this;
  24201. }
  24202. toJSON() {
  24203. const data = super.toJSON();
  24204. data.v1 = this.v1.toArray();
  24205. data.v2 = this.v2.toArray();
  24206. return data;
  24207. }
  24208. fromJSON( json ) {
  24209. super.fromJSON( json );
  24210. this.v1.fromArray( json.v1 );
  24211. this.v2.fromArray( json.v2 );
  24212. return this;
  24213. }
  24214. }
  24215. /**
  24216. * A curve representing a 3D line segment.
  24217. *
  24218. * @augments Curve
  24219. */
  24220. class LineCurve3 extends Curve {
  24221. /**
  24222. * Constructs a new line curve.
  24223. *
  24224. * @param {Vector3} [v1] - The start point.
  24225. * @param {Vector3} [v2] - The end point.
  24226. */
  24227. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  24228. super();
  24229. /**
  24230. * This flag can be used for type testing.
  24231. *
  24232. * @type {boolean}
  24233. * @readonly
  24234. * @default true
  24235. */
  24236. this.isLineCurve3 = true;
  24237. this.type = 'LineCurve3';
  24238. /**
  24239. * The start point.
  24240. *
  24241. * @type {Vector3}
  24242. */
  24243. this.v1 = v1;
  24244. /**
  24245. * The end point.
  24246. *
  24247. * @type {Vector2}
  24248. */
  24249. this.v2 = v2;
  24250. }
  24251. /**
  24252. * Returns a point on the line.
  24253. *
  24254. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24255. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24256. * @return {Vector3} The position on the line.
  24257. */
  24258. getPoint( t, optionalTarget = new Vector3() ) {
  24259. const point = optionalTarget;
  24260. if ( t === 1 ) {
  24261. point.copy( this.v2 );
  24262. } else {
  24263. point.copy( this.v2 ).sub( this.v1 );
  24264. point.multiplyScalar( t ).add( this.v1 );
  24265. }
  24266. return point;
  24267. }
  24268. // Line curve is linear, so we can overwrite default getPointAt
  24269. getPointAt( u, optionalTarget ) {
  24270. return this.getPoint( u, optionalTarget );
  24271. }
  24272. getTangent( t, optionalTarget = new Vector3() ) {
  24273. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24274. }
  24275. getTangentAt( u, optionalTarget ) {
  24276. return this.getTangent( u, optionalTarget );
  24277. }
  24278. copy( source ) {
  24279. super.copy( source );
  24280. this.v1.copy( source.v1 );
  24281. this.v2.copy( source.v2 );
  24282. return this;
  24283. }
  24284. toJSON() {
  24285. const data = super.toJSON();
  24286. data.v1 = this.v1.toArray();
  24287. data.v2 = this.v2.toArray();
  24288. return data;
  24289. }
  24290. fromJSON( json ) {
  24291. super.fromJSON( json );
  24292. this.v1.fromArray( json.v1 );
  24293. this.v2.fromArray( json.v2 );
  24294. return this;
  24295. }
  24296. }
  24297. /**
  24298. * A curve representing a 2D Quadratic Bezier curve.
  24299. *
  24300. * ```js
  24301. * const curve = new THREE.QuadraticBezierCurve(
  24302. * new THREE.Vector2( - 10, 0 ),
  24303. * new THREE.Vector2( 20, 15 ),
  24304. * new THREE.Vector2( 10, 0 )
  24305. * )
  24306. *
  24307. * const points = curve.getPoints( 50 );
  24308. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24309. *
  24310. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24311. *
  24312. * // Create the final object to add to the scene
  24313. * const curveObject = new THREE.Line( geometry, material );
  24314. * ```
  24315. *
  24316. * @augments Curve
  24317. */
  24318. class QuadraticBezierCurve extends Curve {
  24319. /**
  24320. * Constructs a new Quadratic Bezier curve.
  24321. *
  24322. * @param {Vector2} [v0] - The start point.
  24323. * @param {Vector2} [v1] - The control point.
  24324. * @param {Vector2} [v2] - The end point.
  24325. */
  24326. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  24327. super();
  24328. /**
  24329. * This flag can be used for type testing.
  24330. *
  24331. * @type {boolean}
  24332. * @readonly
  24333. * @default true
  24334. */
  24335. this.isQuadraticBezierCurve = true;
  24336. this.type = 'QuadraticBezierCurve';
  24337. /**
  24338. * The start point.
  24339. *
  24340. * @type {Vector2}
  24341. */
  24342. this.v0 = v0;
  24343. /**
  24344. * The control point.
  24345. *
  24346. * @type {Vector2}
  24347. */
  24348. this.v1 = v1;
  24349. /**
  24350. * The end point.
  24351. *
  24352. * @type {Vector2}
  24353. */
  24354. this.v2 = v2;
  24355. }
  24356. /**
  24357. * Returns a point on the curve.
  24358. *
  24359. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24360. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24361. * @return {Vector2} The position on the curve.
  24362. */
  24363. getPoint( t, optionalTarget = new Vector2() ) {
  24364. const point = optionalTarget;
  24365. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24366. point.set(
  24367. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24368. QuadraticBezier( t, v0.y, v1.y, v2.y )
  24369. );
  24370. return point;
  24371. }
  24372. copy( source ) {
  24373. super.copy( source );
  24374. this.v0.copy( source.v0 );
  24375. this.v1.copy( source.v1 );
  24376. this.v2.copy( source.v2 );
  24377. return this;
  24378. }
  24379. toJSON() {
  24380. const data = super.toJSON();
  24381. data.v0 = this.v0.toArray();
  24382. data.v1 = this.v1.toArray();
  24383. data.v2 = this.v2.toArray();
  24384. return data;
  24385. }
  24386. fromJSON( json ) {
  24387. super.fromJSON( json );
  24388. this.v0.fromArray( json.v0 );
  24389. this.v1.fromArray( json.v1 );
  24390. this.v2.fromArray( json.v2 );
  24391. return this;
  24392. }
  24393. }
  24394. /**
  24395. * A curve representing a 3D Quadratic Bezier curve.
  24396. *
  24397. * @augments Curve
  24398. */
  24399. class QuadraticBezierCurve3 extends Curve {
  24400. /**
  24401. * Constructs a new Quadratic Bezier curve.
  24402. *
  24403. * @param {Vector3} [v0] - The start point.
  24404. * @param {Vector3} [v1] - The control point.
  24405. * @param {Vector3} [v2] - The end point.
  24406. */
  24407. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  24408. super();
  24409. /**
  24410. * This flag can be used for type testing.
  24411. *
  24412. * @type {boolean}
  24413. * @readonly
  24414. * @default true
  24415. */
  24416. this.isQuadraticBezierCurve3 = true;
  24417. this.type = 'QuadraticBezierCurve3';
  24418. /**
  24419. * The start point.
  24420. *
  24421. * @type {Vector3}
  24422. */
  24423. this.v0 = v0;
  24424. /**
  24425. * The control point.
  24426. *
  24427. * @type {Vector3}
  24428. */
  24429. this.v1 = v1;
  24430. /**
  24431. * The end point.
  24432. *
  24433. * @type {Vector3}
  24434. */
  24435. this.v2 = v2;
  24436. }
  24437. /**
  24438. * Returns a point on the curve.
  24439. *
  24440. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24441. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24442. * @return {Vector3} The position on the curve.
  24443. */
  24444. getPoint( t, optionalTarget = new Vector3() ) {
  24445. const point = optionalTarget;
  24446. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24447. point.set(
  24448. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24449. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  24450. QuadraticBezier( t, v0.z, v1.z, v2.z )
  24451. );
  24452. return point;
  24453. }
  24454. copy( source ) {
  24455. super.copy( source );
  24456. this.v0.copy( source.v0 );
  24457. this.v1.copy( source.v1 );
  24458. this.v2.copy( source.v2 );
  24459. return this;
  24460. }
  24461. toJSON() {
  24462. const data = super.toJSON();
  24463. data.v0 = this.v0.toArray();
  24464. data.v1 = this.v1.toArray();
  24465. data.v2 = this.v2.toArray();
  24466. return data;
  24467. }
  24468. fromJSON( json ) {
  24469. super.fromJSON( json );
  24470. this.v0.fromArray( json.v0 );
  24471. this.v1.fromArray( json.v1 );
  24472. this.v2.fromArray( json.v2 );
  24473. return this;
  24474. }
  24475. }
  24476. /**
  24477. * A curve representing a 2D spline curve.
  24478. *
  24479. * ```js
  24480. * // Create a sine-like wave
  24481. * const curve = new THREE.SplineCurve( [
  24482. * new THREE.Vector2( -10, 0 ),
  24483. * new THREE.Vector2( -5, 5 ),
  24484. * new THREE.Vector2( 0, 0 ),
  24485. * new THREE.Vector2( 5, -5 ),
  24486. * new THREE.Vector2( 10, 0 )
  24487. * ] );
  24488. *
  24489. * const points = curve.getPoints( 50 );
  24490. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24491. *
  24492. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24493. *
  24494. * // Create the final object to add to the scene
  24495. * const splineObject = new THREE.Line( geometry, material );
  24496. * ```
  24497. *
  24498. * @augments Curve
  24499. */
  24500. class SplineCurve extends Curve {
  24501. /**
  24502. * Constructs a new 2D spline curve.
  24503. *
  24504. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  24505. */
  24506. constructor( points = [] ) {
  24507. super();
  24508. /**
  24509. * This flag can be used for type testing.
  24510. *
  24511. * @type {boolean}
  24512. * @readonly
  24513. * @default true
  24514. */
  24515. this.isSplineCurve = true;
  24516. this.type = 'SplineCurve';
  24517. /**
  24518. * An array of 2D points defining the curve.
  24519. *
  24520. * @type {Array<Vector2>}
  24521. */
  24522. this.points = points;
  24523. }
  24524. /**
  24525. * Returns a point on the curve.
  24526. *
  24527. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24528. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24529. * @return {Vector2} The position on the curve.
  24530. */
  24531. getPoint( t, optionalTarget = new Vector2() ) {
  24532. const point = optionalTarget;
  24533. const points = this.points;
  24534. const p = ( points.length - 1 ) * t;
  24535. const intPoint = Math.floor( p );
  24536. const weight = p - intPoint;
  24537. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24538. const p1 = points[ intPoint ];
  24539. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24540. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24541. point.set(
  24542. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24543. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  24544. );
  24545. return point;
  24546. }
  24547. copy( source ) {
  24548. super.copy( source );
  24549. this.points = [];
  24550. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24551. const point = source.points[ i ];
  24552. this.points.push( point.clone() );
  24553. }
  24554. return this;
  24555. }
  24556. toJSON() {
  24557. const data = super.toJSON();
  24558. data.points = [];
  24559. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24560. const point = this.points[ i ];
  24561. data.points.push( point.toArray() );
  24562. }
  24563. return data;
  24564. }
  24565. fromJSON( json ) {
  24566. super.fromJSON( json );
  24567. this.points = [];
  24568. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24569. const point = json.points[ i ];
  24570. this.points.push( new Vector2().fromArray( point ) );
  24571. }
  24572. return this;
  24573. }
  24574. }
  24575. var Curves = /*#__PURE__*/Object.freeze({
  24576. __proto__: null,
  24577. ArcCurve: ArcCurve,
  24578. CatmullRomCurve3: CatmullRomCurve3,
  24579. CubicBezierCurve: CubicBezierCurve,
  24580. CubicBezierCurve3: CubicBezierCurve3,
  24581. EllipseCurve: EllipseCurve,
  24582. LineCurve: LineCurve,
  24583. LineCurve3: LineCurve3,
  24584. QuadraticBezierCurve: QuadraticBezierCurve,
  24585. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24586. SplineCurve: SplineCurve
  24587. });
  24588. /**
  24589. * A base class extending {@link Curve}. `CurvePath` is simply an
  24590. * array of connected curves, but retains the API of a curve.
  24591. *
  24592. * @augments Curve
  24593. */
  24594. class CurvePath extends Curve {
  24595. /**
  24596. * Constructs a new curve path.
  24597. */
  24598. constructor() {
  24599. super();
  24600. this.type = 'CurvePath';
  24601. /**
  24602. * An array of curves defining the
  24603. * path.
  24604. *
  24605. * @type {Array<Curve>}
  24606. */
  24607. this.curves = [];
  24608. /**
  24609. * Whether the path should automatically be closed
  24610. * by a line curve.
  24611. *
  24612. * @type {boolean}
  24613. * @default false
  24614. */
  24615. this.autoClose = false;
  24616. }
  24617. /**
  24618. * Adds a curve to this curve path.
  24619. *
  24620. * @param {Curve} curve - The curve to add.
  24621. */
  24622. add( curve ) {
  24623. this.curves.push( curve );
  24624. }
  24625. /**
  24626. * Adds a line curve to close the path.
  24627. *
  24628. * @return {CurvePath} A reference to this curve path.
  24629. */
  24630. closePath() {
  24631. // Add a line curve if start and end of lines are not connected
  24632. const startPoint = this.curves[ 0 ].getPoint( 0 );
  24633. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24634. if ( ! startPoint.equals( endPoint ) ) {
  24635. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  24636. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  24637. }
  24638. return this;
  24639. }
  24640. /**
  24641. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  24642. * for the given interpolation factor.
  24643. *
  24644. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24645. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  24646. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  24647. */
  24648. getPoint( t, optionalTarget ) {
  24649. // To get accurate point with reference to
  24650. // entire path distance at time t,
  24651. // following has to be done:
  24652. // 1. Length of each sub path have to be known
  24653. // 2. Locate and identify type of curve
  24654. // 3. Get t for the curve
  24655. // 4. Return curve.getPointAt(t')
  24656. const d = t * this.getLength();
  24657. const curveLengths = this.getCurveLengths();
  24658. let i = 0;
  24659. // To think about boundaries points.
  24660. while ( i < curveLengths.length ) {
  24661. if ( curveLengths[ i ] >= d ) {
  24662. const diff = curveLengths[ i ] - d;
  24663. const curve = this.curves[ i ];
  24664. const segmentLength = curve.getLength();
  24665. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24666. return curve.getPointAt( u, optionalTarget );
  24667. }
  24668. i ++;
  24669. }
  24670. return null;
  24671. // loop where sum != 0, sum > d , sum+1 <d
  24672. }
  24673. getLength() {
  24674. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24675. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24676. // getPoint() depends on getLength
  24677. const lens = this.getCurveLengths();
  24678. return lens[ lens.length - 1 ];
  24679. }
  24680. updateArcLengths() {
  24681. // cacheLengths must be recalculated.
  24682. this.needsUpdate = true;
  24683. this.cacheLengths = null;
  24684. this.getCurveLengths();
  24685. }
  24686. /**
  24687. * Returns list of cumulative curve lengths of the defined curves.
  24688. *
  24689. * @return {Array<number>} The curve lengths.
  24690. */
  24691. getCurveLengths() {
  24692. // Compute lengths and cache them
  24693. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24694. // We use cache values if curves and cache array are same length
  24695. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24696. return this.cacheLengths;
  24697. }
  24698. // Get length of sub-curve
  24699. // Push sums into cached array
  24700. const lengths = [];
  24701. let sums = 0;
  24702. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24703. sums += this.curves[ i ].getLength();
  24704. lengths.push( sums );
  24705. }
  24706. this.cacheLengths = lengths;
  24707. return lengths;
  24708. }
  24709. getSpacedPoints( divisions = 40 ) {
  24710. const points = [];
  24711. for ( let i = 0; i <= divisions; i ++ ) {
  24712. points.push( this.getPoint( i / divisions ) );
  24713. }
  24714. if ( this.autoClose ) {
  24715. points.push( points[ 0 ] );
  24716. }
  24717. return points;
  24718. }
  24719. getPoints( divisions = 12 ) {
  24720. const points = [];
  24721. let last;
  24722. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24723. const curve = curves[ i ];
  24724. const resolution = curve.isEllipseCurve ? divisions * 2
  24725. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  24726. : curve.isSplineCurve ? divisions * curve.points.length
  24727. : divisions;
  24728. const pts = curve.getPoints( resolution );
  24729. for ( let j = 0; j < pts.length; j ++ ) {
  24730. const point = pts[ j ];
  24731. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24732. points.push( point );
  24733. last = point;
  24734. }
  24735. }
  24736. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24737. points.push( points[ 0 ] );
  24738. }
  24739. return points;
  24740. }
  24741. copy( source ) {
  24742. super.copy( source );
  24743. this.curves = [];
  24744. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  24745. const curve = source.curves[ i ];
  24746. this.curves.push( curve.clone() );
  24747. }
  24748. this.autoClose = source.autoClose;
  24749. return this;
  24750. }
  24751. toJSON() {
  24752. const data = super.toJSON();
  24753. data.autoClose = this.autoClose;
  24754. data.curves = [];
  24755. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24756. const curve = this.curves[ i ];
  24757. data.curves.push( curve.toJSON() );
  24758. }
  24759. return data;
  24760. }
  24761. fromJSON( json ) {
  24762. super.fromJSON( json );
  24763. this.autoClose = json.autoClose;
  24764. this.curves = [];
  24765. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  24766. const curve = json.curves[ i ];
  24767. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24768. }
  24769. return this;
  24770. }
  24771. }
  24772. /**
  24773. * A 2D path representation. The class provides methods for creating paths
  24774. * and contours of 2D shapes similar to the 2D Canvas API.
  24775. *
  24776. * ```js
  24777. * const path = new THREE.Path();
  24778. *
  24779. * path.lineTo( 0, 0.8 );
  24780. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  24781. * path.lineTo( 1, 1 );
  24782. *
  24783. * const points = path.getPoints();
  24784. *
  24785. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24786. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  24787. *
  24788. * const line = new THREE.Line( geometry, material );
  24789. * scene.add( line );
  24790. * ```
  24791. *
  24792. * @augments CurvePath
  24793. */
  24794. class Path extends CurvePath {
  24795. /**
  24796. * Constructs a new path.
  24797. *
  24798. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  24799. */
  24800. constructor( points ) {
  24801. super();
  24802. this.type = 'Path';
  24803. /**
  24804. * The current offset of the path. Any new curve added will start here.
  24805. *
  24806. * @type {Vector2}
  24807. */
  24808. this.currentPoint = new Vector2();
  24809. if ( points ) {
  24810. this.setFromPoints( points );
  24811. }
  24812. }
  24813. /**
  24814. * Creates a path from the given list of points. The points are added
  24815. * to the path as instances of {@link LineCurve}.
  24816. *
  24817. * @param {Array<Vector2>} points - An array of 2D points.
  24818. * @return {Path} A reference to this path.
  24819. */
  24820. setFromPoints( points ) {
  24821. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  24822. for ( let i = 1, l = points.length; i < l; i ++ ) {
  24823. this.lineTo( points[ i ].x, points[ i ].y );
  24824. }
  24825. return this;
  24826. }
  24827. /**
  24828. * Moves {@link Path#currentPoint} to the given point.
  24829. *
  24830. * @param {number} x - The x coordinate.
  24831. * @param {number} y - The y coordinate.
  24832. * @return {Path} A reference to this path.
  24833. */
  24834. moveTo( x, y ) {
  24835. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  24836. return this;
  24837. }
  24838. /**
  24839. * Adds an instance of {@link LineCurve} to the path by connecting
  24840. * the current point with the given one.
  24841. *
  24842. * @param {number} x - The x coordinate of the end point.
  24843. * @param {number} y - The y coordinate of the end point.
  24844. * @return {Path} A reference to this path.
  24845. */
  24846. lineTo( x, y ) {
  24847. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  24848. this.curves.push( curve );
  24849. this.currentPoint.set( x, y );
  24850. return this;
  24851. }
  24852. /**
  24853. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  24854. * the current point with the given one.
  24855. *
  24856. * @param {number} aCPx - The x coordinate of the control point.
  24857. * @param {number} aCPy - The y coordinate of the control point.
  24858. * @param {number} aX - The x coordinate of the end point.
  24859. * @param {number} aY - The y coordinate of the end point.
  24860. * @return {Path} A reference to this path.
  24861. */
  24862. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  24863. const curve = new QuadraticBezierCurve(
  24864. this.currentPoint.clone(),
  24865. new Vector2( aCPx, aCPy ),
  24866. new Vector2( aX, aY )
  24867. );
  24868. this.curves.push( curve );
  24869. this.currentPoint.set( aX, aY );
  24870. return this;
  24871. }
  24872. /**
  24873. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  24874. * the current point with the given one.
  24875. *
  24876. * @param {number} aCP1x - The x coordinate of the first control point.
  24877. * @param {number} aCP1y - The y coordinate of the first control point.
  24878. * @param {number} aCP2x - The x coordinate of the second control point.
  24879. * @param {number} aCP2y - The y coordinate of the second control point.
  24880. * @param {number} aX - The x coordinate of the end point.
  24881. * @param {number} aY - The y coordinate of the end point.
  24882. * @return {Path} A reference to this path.
  24883. */
  24884. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24885. const curve = new CubicBezierCurve(
  24886. this.currentPoint.clone(),
  24887. new Vector2( aCP1x, aCP1y ),
  24888. new Vector2( aCP2x, aCP2y ),
  24889. new Vector2( aX, aY )
  24890. );
  24891. this.curves.push( curve );
  24892. this.currentPoint.set( aX, aY );
  24893. return this;
  24894. }
  24895. /**
  24896. * Adds an instance of {@link SplineCurve} to the path by connecting
  24897. * the current point with the given list of points.
  24898. *
  24899. * @param {Array<Vector2>} pts - An array of points in 2D space.
  24900. * @return {Path} A reference to this path.
  24901. */
  24902. splineThru( pts ) {
  24903. const npts = [ this.currentPoint.clone() ].concat( pts );
  24904. const curve = new SplineCurve( npts );
  24905. this.curves.push( curve );
  24906. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24907. return this;
  24908. }
  24909. /**
  24910. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  24911. * to the current point.
  24912. *
  24913. * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
  24914. * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
  24915. * @param {number} [aRadius=1] - The radius of the arc.
  24916. * @param {number} [aStartAngle=0] - The start angle in radians.
  24917. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24918. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24919. * @return {Path} A reference to this path.
  24920. */
  24921. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24922. const x0 = this.currentPoint.x;
  24923. const y0 = this.currentPoint.y;
  24924. this.absarc( aX + x0, aY + y0, aRadius,
  24925. aStartAngle, aEndAngle, aClockwise );
  24926. return this;
  24927. }
  24928. /**
  24929. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  24930. *
  24931. * @param {number} [aX=0] - The x coordinate of the center of the arc.
  24932. * @param {number} [aY=0] - The y coordinate of the center of the arc.
  24933. * @param {number} [aRadius=1] - The radius of the arc.
  24934. * @param {number} [aStartAngle=0] - The start angle in radians.
  24935. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24936. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24937. * @return {Path} A reference to this path.
  24938. */
  24939. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24940. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24941. return this;
  24942. }
  24943. /**
  24944. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  24945. * to the current point
  24946. *
  24947. * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
  24948. * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
  24949. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24950. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24951. * @param {number} [aStartAngle=0] - The start angle in radians.
  24952. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24953. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24954. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24955. * @return {Path} A reference to this path.
  24956. */
  24957. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24958. const x0 = this.currentPoint.x;
  24959. const y0 = this.currentPoint.y;
  24960. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24961. return this;
  24962. }
  24963. /**
  24964. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  24965. *
  24966. * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
  24967. * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
  24968. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24969. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24970. * @param {number} [aStartAngle=0] - The start angle in radians.
  24971. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24972. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24973. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24974. * @return {Path} A reference to this path.
  24975. */
  24976. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24977. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24978. if ( this.curves.length > 0 ) {
  24979. // if a previous curve is present, attempt to join
  24980. const firstPoint = curve.getPoint( 0 );
  24981. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24982. this.lineTo( firstPoint.x, firstPoint.y );
  24983. }
  24984. }
  24985. this.curves.push( curve );
  24986. const lastPoint = curve.getPoint( 1 );
  24987. this.currentPoint.copy( lastPoint );
  24988. return this;
  24989. }
  24990. copy( source ) {
  24991. super.copy( source );
  24992. this.currentPoint.copy( source.currentPoint );
  24993. return this;
  24994. }
  24995. toJSON() {
  24996. const data = super.toJSON();
  24997. data.currentPoint = this.currentPoint.toArray();
  24998. return data;
  24999. }
  25000. fromJSON( json ) {
  25001. super.fromJSON( json );
  25002. this.currentPoint.fromArray( json.currentPoint );
  25003. return this;
  25004. }
  25005. }
  25006. /**
  25007. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  25008. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  25009. * points, or to get triangulated faces.
  25010. *
  25011. * ```js
  25012. * const heartShape = new THREE.Shape();
  25013. *
  25014. * heartShape.moveTo( 25, 25 );
  25015. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  25016. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  25017. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  25018. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  25019. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  25020. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  25021. *
  25022. * const extrudeSettings = {
  25023. * depth: 8,
  25024. * bevelEnabled: true,
  25025. * bevelSegments: 2,
  25026. * steps: 2,
  25027. * bevelSize: 1,
  25028. * bevelThickness: 1
  25029. * };
  25030. *
  25031. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  25032. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  25033. * ```
  25034. *
  25035. * @augments Path
  25036. */
  25037. class Shape extends Path {
  25038. /**
  25039. * Constructs a new shape.
  25040. *
  25041. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  25042. */
  25043. constructor( points ) {
  25044. super( points );
  25045. /**
  25046. * The UUID of the shape.
  25047. *
  25048. * @type {string}
  25049. * @readonly
  25050. */
  25051. this.uuid = generateUUID();
  25052. this.type = 'Shape';
  25053. /**
  25054. * Defines the holes in the shape. Hole definitions must use the
  25055. * opposite winding order (CW/CCW) than the outer shape.
  25056. *
  25057. * @type {Array<Path>}
  25058. * @readonly
  25059. */
  25060. this.holes = [];
  25061. }
  25062. /**
  25063. * Returns an array representing each contour of the holes
  25064. * as a list of 2D points.
  25065. *
  25066. * @param {number} divisions - The fineness of the result.
  25067. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  25068. */
  25069. getPointsHoles( divisions ) {
  25070. const holesPts = [];
  25071. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25072. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  25073. }
  25074. return holesPts;
  25075. }
  25076. // get points of shape and holes (keypoints based on segments parameter)
  25077. /**
  25078. * Returns an object that holds contour data for the shape and its holes as
  25079. * arrays of 2D points.
  25080. *
  25081. * @param {number} divisions - The fineness of the result.
  25082. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  25083. */
  25084. extractPoints( divisions ) {
  25085. return {
  25086. shape: this.getPoints( divisions ),
  25087. holes: this.getPointsHoles( divisions )
  25088. };
  25089. }
  25090. copy( source ) {
  25091. super.copy( source );
  25092. this.holes = [];
  25093. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  25094. const hole = source.holes[ i ];
  25095. this.holes.push( hole.clone() );
  25096. }
  25097. return this;
  25098. }
  25099. toJSON() {
  25100. const data = super.toJSON();
  25101. data.uuid = this.uuid;
  25102. data.holes = [];
  25103. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25104. const hole = this.holes[ i ];
  25105. data.holes.push( hole.toJSON() );
  25106. }
  25107. return data;
  25108. }
  25109. fromJSON( json ) {
  25110. super.fromJSON( json );
  25111. this.uuid = json.uuid;
  25112. this.holes = [];
  25113. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  25114. const hole = json.holes[ i ];
  25115. this.holes.push( new Path().fromJSON( hole ) );
  25116. }
  25117. return this;
  25118. }
  25119. }
  25120. /* eslint-disable */
  25121. // copy of mapbox/earcut version 3.0.1
  25122. // https://github.com/mapbox/earcut/tree/v3.0.1
  25123. function earcut(data, holeIndices, dim = 2) {
  25124. const hasHoles = holeIndices && holeIndices.length;
  25125. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  25126. let outerNode = linkedList(data, 0, outerLen, dim, true);
  25127. const triangles = [];
  25128. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  25129. let minX, minY, invSize;
  25130. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  25131. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  25132. if (data.length > 80 * dim) {
  25133. minX = Infinity;
  25134. minY = Infinity;
  25135. let maxX = -Infinity;
  25136. let maxY = -Infinity;
  25137. for (let i = dim; i < outerLen; i += dim) {
  25138. const x = data[i];
  25139. const y = data[i + 1];
  25140. if (x < minX) minX = x;
  25141. if (y < minY) minY = y;
  25142. if (x > maxX) maxX = x;
  25143. if (y > maxY) maxY = y;
  25144. }
  25145. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  25146. invSize = Math.max(maxX - minX, maxY - minY);
  25147. invSize = invSize !== 0 ? 32767 / invSize : 0;
  25148. }
  25149. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  25150. return triangles;
  25151. }
  25152. // create a circular doubly linked list from polygon points in the specified winding order
  25153. function linkedList(data, start, end, dim, clockwise) {
  25154. let last;
  25155. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  25156. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25157. } else {
  25158. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25159. }
  25160. if (last && equals(last, last.next)) {
  25161. removeNode(last);
  25162. last = last.next;
  25163. }
  25164. return last;
  25165. }
  25166. // eliminate colinear or duplicate points
  25167. function filterPoints(start, end) {
  25168. if (!start) return start;
  25169. if (!end) end = start;
  25170. let p = start,
  25171. again;
  25172. do {
  25173. again = false;
  25174. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  25175. removeNode(p);
  25176. p = end = p.prev;
  25177. if (p === p.next) break;
  25178. again = true;
  25179. } else {
  25180. p = p.next;
  25181. }
  25182. } while (again || p !== end);
  25183. return end;
  25184. }
  25185. // main ear slicing loop which triangulates a polygon (given as a linked list)
  25186. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  25187. if (!ear) return;
  25188. // interlink polygon nodes in z-order
  25189. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  25190. let stop = ear;
  25191. // iterate through ears, slicing them one by one
  25192. while (ear.prev !== ear.next) {
  25193. const prev = ear.prev;
  25194. const next = ear.next;
  25195. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  25196. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  25197. removeNode(ear);
  25198. // skipping the next vertex leads to less sliver triangles
  25199. ear = next.next;
  25200. stop = next.next;
  25201. continue;
  25202. }
  25203. ear = next;
  25204. // if we looped through the whole remaining polygon and can't find any more ears
  25205. if (ear === stop) {
  25206. // try filtering points and slicing again
  25207. if (!pass) {
  25208. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  25209. // if this didn't work, try curing all small self-intersections locally
  25210. } else if (pass === 1) {
  25211. ear = cureLocalIntersections(filterPoints(ear), triangles);
  25212. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  25213. // as a last resort, try splitting the remaining polygon into two
  25214. } else if (pass === 2) {
  25215. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  25216. }
  25217. break;
  25218. }
  25219. }
  25220. }
  25221. // check whether a polygon node forms a valid ear with adjacent nodes
  25222. function isEar(ear) {
  25223. const a = ear.prev,
  25224. b = ear,
  25225. c = ear.next;
  25226. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25227. // now make sure we don't have other points inside the potential ear
  25228. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25229. // triangle bbox
  25230. const x0 = Math.min(ax, bx, cx),
  25231. y0 = Math.min(ay, by, cy),
  25232. x1 = Math.max(ax, bx, cx),
  25233. y1 = Math.max(ay, by, cy);
  25234. let p = c.next;
  25235. while (p !== a) {
  25236. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  25237. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  25238. area(p.prev, p, p.next) >= 0) return false;
  25239. p = p.next;
  25240. }
  25241. return true;
  25242. }
  25243. function isEarHashed(ear, minX, minY, invSize) {
  25244. const a = ear.prev,
  25245. b = ear,
  25246. c = ear.next;
  25247. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25248. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25249. // triangle bbox
  25250. const x0 = Math.min(ax, bx, cx),
  25251. y0 = Math.min(ay, by, cy),
  25252. x1 = Math.max(ax, bx, cx),
  25253. y1 = Math.max(ay, by, cy);
  25254. // z-order range for the current triangle bbox;
  25255. const minZ = zOrder(x0, y0, minX, minY, invSize),
  25256. maxZ = zOrder(x1, y1, minX, minY, invSize);
  25257. let p = ear.prevZ,
  25258. n = ear.nextZ;
  25259. // look for points inside the triangle in both directions
  25260. while (p && p.z >= minZ && n && n.z <= maxZ) {
  25261. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25262. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25263. p = p.prevZ;
  25264. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25265. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25266. n = n.nextZ;
  25267. }
  25268. // look for remaining points in decreasing z-order
  25269. while (p && p.z >= minZ) {
  25270. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25271. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25272. p = p.prevZ;
  25273. }
  25274. // look for remaining points in increasing z-order
  25275. while (n && n.z <= maxZ) {
  25276. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25277. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25278. n = n.nextZ;
  25279. }
  25280. return true;
  25281. }
  25282. // go through all polygon nodes and cure small local self-intersections
  25283. function cureLocalIntersections(start, triangles) {
  25284. let p = start;
  25285. do {
  25286. const a = p.prev,
  25287. b = p.next.next;
  25288. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  25289. triangles.push(a.i, p.i, b.i);
  25290. // remove two nodes involved
  25291. removeNode(p);
  25292. removeNode(p.next);
  25293. p = start = b;
  25294. }
  25295. p = p.next;
  25296. } while (p !== start);
  25297. return filterPoints(p);
  25298. }
  25299. // try splitting polygon into two and triangulate them independently
  25300. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  25301. // look for a valid diagonal that divides the polygon into two
  25302. let a = start;
  25303. do {
  25304. let b = a.next.next;
  25305. while (b !== a.prev) {
  25306. if (a.i !== b.i && isValidDiagonal(a, b)) {
  25307. // split the polygon in two by the diagonal
  25308. let c = splitPolygon(a, b);
  25309. // filter colinear points around the cuts
  25310. a = filterPoints(a, a.next);
  25311. c = filterPoints(c, c.next);
  25312. // run earcut on each half
  25313. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  25314. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  25315. return;
  25316. }
  25317. b = b.next;
  25318. }
  25319. a = a.next;
  25320. } while (a !== start);
  25321. }
  25322. // link every hole into the outer loop, producing a single-ring polygon without holes
  25323. function eliminateHoles(data, holeIndices, outerNode, dim) {
  25324. const queue = [];
  25325. for (let i = 0, len = holeIndices.length; i < len; i++) {
  25326. const start = holeIndices[i] * dim;
  25327. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  25328. const list = linkedList(data, start, end, dim, false);
  25329. if (list === list.next) list.steiner = true;
  25330. queue.push(getLeftmost(list));
  25331. }
  25332. queue.sort(compareXYSlope);
  25333. // process holes from left to right
  25334. for (let i = 0; i < queue.length; i++) {
  25335. outerNode = eliminateHole(queue[i], outerNode);
  25336. }
  25337. return outerNode;
  25338. }
  25339. function compareXYSlope(a, b) {
  25340. let result = a.x - b.x;
  25341. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  25342. // the bridge to the outer shell is always the point that they meet at.
  25343. if (result === 0) {
  25344. result = a.y - b.y;
  25345. if (result === 0) {
  25346. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  25347. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  25348. result = aSlope - bSlope;
  25349. }
  25350. }
  25351. return result;
  25352. }
  25353. // find a bridge between vertices that connects hole with an outer ring and and link it
  25354. function eliminateHole(hole, outerNode) {
  25355. const bridge = findHoleBridge(hole, outerNode);
  25356. if (!bridge) {
  25357. return outerNode;
  25358. }
  25359. const bridgeReverse = splitPolygon(bridge, hole);
  25360. // filter collinear points around the cuts
  25361. filterPoints(bridgeReverse, bridgeReverse.next);
  25362. return filterPoints(bridge, bridge.next);
  25363. }
  25364. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  25365. function findHoleBridge(hole, outerNode) {
  25366. let p = outerNode;
  25367. const hx = hole.x;
  25368. const hy = hole.y;
  25369. let qx = -Infinity;
  25370. let m;
  25371. // find a segment intersected by a ray from the hole's leftmost point to the left;
  25372. // segment's endpoint with lesser x will be potential connection point
  25373. // unless they intersect at a vertex, then choose the vertex
  25374. if (equals(hole, p)) return p;
  25375. do {
  25376. if (equals(hole, p.next)) return p.next;
  25377. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  25378. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  25379. if (x <= hx && x > qx) {
  25380. qx = x;
  25381. m = p.x < p.next.x ? p : p.next;
  25382. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  25383. }
  25384. }
  25385. p = p.next;
  25386. } while (p !== outerNode);
  25387. if (!m) return null;
  25388. // look for points inside the triangle of hole point, segment intersection and endpoint;
  25389. // if there are no points found, we have a valid connection;
  25390. // otherwise choose the point of the minimum angle with the ray as connection point
  25391. const stop = m;
  25392. const mx = m.x;
  25393. const my = m.y;
  25394. let tanMin = Infinity;
  25395. p = m;
  25396. do {
  25397. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  25398. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  25399. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  25400. if (locallyInside(p, hole) &&
  25401. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  25402. m = p;
  25403. tanMin = tan;
  25404. }
  25405. }
  25406. p = p.next;
  25407. } while (p !== stop);
  25408. return m;
  25409. }
  25410. // whether sector in vertex m contains sector in vertex p in the same coordinates
  25411. function sectorContainsSector(m, p) {
  25412. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  25413. }
  25414. // interlink polygon nodes in z-order
  25415. function indexCurve(start, minX, minY, invSize) {
  25416. let p = start;
  25417. do {
  25418. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  25419. p.prevZ = p.prev;
  25420. p.nextZ = p.next;
  25421. p = p.next;
  25422. } while (p !== start);
  25423. p.prevZ.nextZ = null;
  25424. p.prevZ = null;
  25425. sortLinked(p);
  25426. }
  25427. // Simon Tatham's linked list merge sort algorithm
  25428. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  25429. function sortLinked(list) {
  25430. let numMerges;
  25431. let inSize = 1;
  25432. do {
  25433. let p = list;
  25434. let e;
  25435. list = null;
  25436. let tail = null;
  25437. numMerges = 0;
  25438. while (p) {
  25439. numMerges++;
  25440. let q = p;
  25441. let pSize = 0;
  25442. for (let i = 0; i < inSize; i++) {
  25443. pSize++;
  25444. q = q.nextZ;
  25445. if (!q) break;
  25446. }
  25447. let qSize = inSize;
  25448. while (pSize > 0 || (qSize > 0 && q)) {
  25449. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  25450. e = p;
  25451. p = p.nextZ;
  25452. pSize--;
  25453. } else {
  25454. e = q;
  25455. q = q.nextZ;
  25456. qSize--;
  25457. }
  25458. if (tail) tail.nextZ = e;
  25459. else list = e;
  25460. e.prevZ = tail;
  25461. tail = e;
  25462. }
  25463. p = q;
  25464. }
  25465. tail.nextZ = null;
  25466. inSize *= 2;
  25467. } while (numMerges > 1);
  25468. return list;
  25469. }
  25470. // z-order of a point given coords and inverse of the longer side of data bbox
  25471. function zOrder(x, y, minX, minY, invSize) {
  25472. // coords are transformed into non-negative 15-bit integer range
  25473. x = (x - minX) * invSize | 0;
  25474. y = (y - minY) * invSize | 0;
  25475. x = (x | (x << 8)) & 0x00FF00FF;
  25476. x = (x | (x << 4)) & 0x0F0F0F0F;
  25477. x = (x | (x << 2)) & 0x33333333;
  25478. x = (x | (x << 1)) & 0x55555555;
  25479. y = (y | (y << 8)) & 0x00FF00FF;
  25480. y = (y | (y << 4)) & 0x0F0F0F0F;
  25481. y = (y | (y << 2)) & 0x33333333;
  25482. y = (y | (y << 1)) & 0x55555555;
  25483. return x | (y << 1);
  25484. }
  25485. // find the leftmost node of a polygon ring
  25486. function getLeftmost(start) {
  25487. let p = start,
  25488. leftmost = start;
  25489. do {
  25490. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  25491. p = p.next;
  25492. } while (p !== start);
  25493. return leftmost;
  25494. }
  25495. // check if a point lies within a convex triangle
  25496. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  25497. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  25498. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  25499. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  25500. }
  25501. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  25502. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  25503. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  25504. }
  25505. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25506. function isValidDiagonal(a, b) {
  25507. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges
  25508. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  25509. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25510. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25511. }
  25512. // signed area of a triangle
  25513. function area(p, q, r) {
  25514. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25515. }
  25516. // check if two points are equal
  25517. function equals(p1, p2) {
  25518. return p1.x === p2.x && p1.y === p2.y;
  25519. }
  25520. // check if two segments intersect
  25521. function intersects(p1, q1, p2, q2) {
  25522. const o1 = sign(area(p1, q1, p2));
  25523. const o2 = sign(area(p1, q1, q2));
  25524. const o3 = sign(area(p2, q2, p1));
  25525. const o4 = sign(area(p2, q2, q1));
  25526. if (o1 !== o2 && o3 !== o4) return true; // general case
  25527. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25528. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25529. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25530. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25531. return false;
  25532. }
  25533. // for collinear points p, q, r, check if point q lies on segment pr
  25534. function onSegment(p, q, r) {
  25535. 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);
  25536. }
  25537. function sign(num) {
  25538. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25539. }
  25540. // check if a polygon diagonal intersects any polygon segments
  25541. function intersectsPolygon(a, b) {
  25542. let p = a;
  25543. do {
  25544. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25545. intersects(p, p.next, a, b)) return true;
  25546. p = p.next;
  25547. } while (p !== a);
  25548. return false;
  25549. }
  25550. // check if a polygon diagonal is locally inside the polygon
  25551. function locallyInside(a, b) {
  25552. return area(a.prev, a, a.next) < 0 ?
  25553. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  25554. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  25555. }
  25556. // check if the middle point of a polygon diagonal is inside the polygon
  25557. function middleInside(a, b) {
  25558. let p = a;
  25559. let inside = false;
  25560. const px = (a.x + b.x) / 2;
  25561. const py = (a.y + b.y) / 2;
  25562. do {
  25563. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  25564. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  25565. inside = !inside;
  25566. p = p.next;
  25567. } while (p !== a);
  25568. return inside;
  25569. }
  25570. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25571. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25572. function splitPolygon(a, b) {
  25573. const a2 = createNode(a.i, a.x, a.y),
  25574. b2 = createNode(b.i, b.x, b.y),
  25575. an = a.next,
  25576. bp = b.prev;
  25577. a.next = b;
  25578. b.prev = a;
  25579. a2.next = an;
  25580. an.prev = a2;
  25581. b2.next = a2;
  25582. a2.prev = b2;
  25583. bp.next = b2;
  25584. b2.prev = bp;
  25585. return b2;
  25586. }
  25587. // create a node and optionally link it with previous one (in a circular doubly linked list)
  25588. function insertNode(i, x, y, last) {
  25589. const p = createNode(i, x, y);
  25590. if (!last) {
  25591. p.prev = p;
  25592. p.next = p;
  25593. } else {
  25594. p.next = last.next;
  25595. p.prev = last;
  25596. last.next.prev = p;
  25597. last.next = p;
  25598. }
  25599. return p;
  25600. }
  25601. function removeNode(p) {
  25602. p.next.prev = p.prev;
  25603. p.prev.next = p.next;
  25604. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  25605. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  25606. }
  25607. function createNode(i, x, y) {
  25608. return {
  25609. i, // vertex index in coordinates array
  25610. x, y, // vertex coordinates
  25611. prev: null, // previous and next vertex nodes in a polygon ring
  25612. next: null,
  25613. z: 0, // z-order curve value
  25614. prevZ: null, // previous and next nodes in z-order
  25615. nextZ: null,
  25616. steiner: false // indicates whether this is a steiner point
  25617. };
  25618. }
  25619. function signedArea(data, start, end, dim) {
  25620. let sum = 0;
  25621. for (let i = start, j = end - dim; i < end; i += dim) {
  25622. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  25623. j = i;
  25624. }
  25625. return sum;
  25626. }
  25627. class Earcut {
  25628. /**
  25629. * Triangulates the given shape definition by returning an array of triangles.
  25630. *
  25631. * @param {Array<number>} data - An array with 2D points.
  25632. * @param {Array<number>} holeIndices - An array with indices defining holes.
  25633. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  25634. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  25635. * representing vertex indices.
  25636. */
  25637. static triangulate( data, holeIndices, dim = 2 ) {
  25638. return earcut( data, holeIndices, dim );
  25639. }
  25640. }
  25641. /**
  25642. * A class containing utility functions for shapes.
  25643. *
  25644. * @hideconstructor
  25645. */
  25646. class ShapeUtils {
  25647. /**
  25648. * Calculate area of a ( 2D ) contour polygon.
  25649. *
  25650. * @param {Array<Vector2>} contour - An array of 2D points.
  25651. * @return {number} The area.
  25652. */
  25653. static area( contour ) {
  25654. const n = contour.length;
  25655. let a = 0.0;
  25656. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  25657. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  25658. }
  25659. return a * 0.5;
  25660. }
  25661. /**
  25662. * Returns `true` if the given contour uses a clockwise winding order.
  25663. *
  25664. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  25665. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  25666. */
  25667. static isClockWise( pts ) {
  25668. return ShapeUtils.area( pts ) < 0;
  25669. }
  25670. /**
  25671. * Triangulates the given shape definition.
  25672. *
  25673. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  25674. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  25675. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  25676. */
  25677. static triangulateShape( contour, holes ) {
  25678. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25679. const holeIndices = []; // array of hole indices
  25680. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25681. removeDupEndPts( contour );
  25682. addContour( vertices, contour );
  25683. //
  25684. let holeIndex = contour.length;
  25685. holes.forEach( removeDupEndPts );
  25686. for ( let i = 0; i < holes.length; i ++ ) {
  25687. holeIndices.push( holeIndex );
  25688. holeIndex += holes[ i ].length;
  25689. addContour( vertices, holes[ i ] );
  25690. }
  25691. //
  25692. const triangles = Earcut.triangulate( vertices, holeIndices );
  25693. //
  25694. for ( let i = 0; i < triangles.length; i += 3 ) {
  25695. faces.push( triangles.slice( i, i + 3 ) );
  25696. }
  25697. return faces;
  25698. }
  25699. }
  25700. function removeDupEndPts( points ) {
  25701. const l = points.length;
  25702. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  25703. points.pop();
  25704. }
  25705. }
  25706. function addContour( vertices, contour ) {
  25707. for ( let i = 0; i < contour.length; i ++ ) {
  25708. vertices.push( contour[ i ].x );
  25709. vertices.push( contour[ i ].y );
  25710. }
  25711. }
  25712. /**
  25713. * Creates extruded geometry from a path shape.
  25714. *
  25715. * ```js
  25716. * const length = 12, width = 8;
  25717. *
  25718. * const shape = new THREE.Shape();
  25719. * shape.moveTo( 0,0 );
  25720. * shape.lineTo( 0, width );
  25721. * shape.lineTo( length, width );
  25722. * shape.lineTo( length, 0 );
  25723. * shape.lineTo( 0, 0 );
  25724. *
  25725. * const geometry = new THREE.ExtrudeGeometry( shape );
  25726. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  25727. * const mesh = new THREE.Mesh( geometry, material ) ;
  25728. * scene.add( mesh );
  25729. * ```
  25730. *
  25731. * @augments BufferGeometry
  25732. */
  25733. class ExtrudeGeometry extends BufferGeometry {
  25734. /**
  25735. * Constructs a new extrude geometry.
  25736. *
  25737. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  25738. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  25739. */
  25740. 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 = {} ) {
  25741. super();
  25742. this.type = 'ExtrudeGeometry';
  25743. /**
  25744. * Holds the constructor parameters that have been
  25745. * used to generate the geometry. Any modification
  25746. * after instantiation does not change the geometry.
  25747. *
  25748. * @type {Object}
  25749. */
  25750. this.parameters = {
  25751. shapes: shapes,
  25752. options: options
  25753. };
  25754. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  25755. const scope = this;
  25756. const verticesArray = [];
  25757. const uvArray = [];
  25758. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25759. const shape = shapes[ i ];
  25760. addShape( shape );
  25761. }
  25762. // build geometry
  25763. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  25764. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  25765. this.computeVertexNormals();
  25766. // functions
  25767. function addShape( shape ) {
  25768. const placeholder = [];
  25769. // options
  25770. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  25771. const steps = options.steps !== undefined ? options.steps : 1;
  25772. const depth = options.depth !== undefined ? options.depth : 1;
  25773. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  25774. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  25775. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  25776. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  25777. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  25778. const extrudePath = options.extrudePath;
  25779. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  25780. //
  25781. let extrudePts, extrudeByPath = false;
  25782. let splineTube, binormal, normal, position2;
  25783. if ( extrudePath ) {
  25784. extrudePts = extrudePath.getSpacedPoints( steps );
  25785. extrudeByPath = true;
  25786. bevelEnabled = false; // bevels not supported for path extrusion
  25787. // SETUP TNB variables
  25788. // TODO1 - have a .isClosed in spline?
  25789. splineTube = extrudePath.computeFrenetFrames( steps, false );
  25790. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  25791. binormal = new Vector3();
  25792. normal = new Vector3();
  25793. position2 = new Vector3();
  25794. }
  25795. // Safeguards if bevels are not enabled
  25796. if ( ! bevelEnabled ) {
  25797. bevelSegments = 0;
  25798. bevelThickness = 0;
  25799. bevelSize = 0;
  25800. bevelOffset = 0;
  25801. }
  25802. // Variables initialization
  25803. const shapePoints = shape.extractPoints( curveSegments );
  25804. let vertices = shapePoints.shape;
  25805. const holes = shapePoints.holes;
  25806. const reverse = ! ShapeUtils.isClockWise( vertices );
  25807. if ( reverse ) {
  25808. vertices = vertices.reverse();
  25809. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  25810. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25811. const ahole = holes[ h ];
  25812. if ( ShapeUtils.isClockWise( ahole ) ) {
  25813. holes[ h ] = ahole.reverse();
  25814. }
  25815. }
  25816. }
  25817. /**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.
  25818. * @param {Array<Vector2>} points
  25819. */
  25820. function mergeOverlappingPoints( points ) {
  25821. const THRESHOLD = 1e-10;
  25822. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  25823. let prevPos = points[ 0 ];
  25824. for ( let i = 1; i <= points.length; i ++ ) {
  25825. const currentIndex = i % points.length;
  25826. const currentPos = points[ currentIndex ];
  25827. const dx = currentPos.x - prevPos.x;
  25828. const dy = currentPos.y - prevPos.y;
  25829. const distSq = dx * dx + dy * dy;
  25830. const scalingFactorSqrt = Math.max(
  25831. Math.abs( currentPos.x ),
  25832. Math.abs( currentPos.y ),
  25833. Math.abs( prevPos.x ),
  25834. Math.abs( prevPos.y )
  25835. );
  25836. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  25837. if ( distSq <= thresholdSqScaled ) {
  25838. points.splice( currentIndex, 1 );
  25839. i --;
  25840. continue;
  25841. }
  25842. prevPos = currentPos;
  25843. }
  25844. }
  25845. mergeOverlappingPoints( vertices );
  25846. holes.forEach( mergeOverlappingPoints );
  25847. const numHoles = holes.length;
  25848. /* Vertices */
  25849. const contour = vertices; // vertices has all points but contour has only points of circumference
  25850. for ( let h = 0; h < numHoles; h ++ ) {
  25851. const ahole = holes[ h ];
  25852. vertices = vertices.concat( ahole );
  25853. }
  25854. function scalePt2( pt, vec, size ) {
  25855. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  25856. return pt.clone().addScaledVector( vec, size );
  25857. }
  25858. const vlen = vertices.length;
  25859. // Find directions for point movement
  25860. function getBevelVec( inPt, inPrev, inNext ) {
  25861. // computes for inPt the corresponding point inPt' on a new contour
  25862. // shifted by 1 unit (length of normalized vector) to the left
  25863. // if we walk along contour clockwise, this new contour is outside the old one
  25864. //
  25865. // inPt' is the intersection of the two lines parallel to the two
  25866. // adjacent edges of inPt at a distance of 1 unit on the left side.
  25867. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  25868. // good reading for geometry algorithms (here: line-line intersection)
  25869. // http://geomalgorithms.com/a05-_intersect-1.html
  25870. const v_prev_x = inPt.x - inPrev.x,
  25871. v_prev_y = inPt.y - inPrev.y;
  25872. const v_next_x = inNext.x - inPt.x,
  25873. v_next_y = inNext.y - inPt.y;
  25874. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  25875. // check for collinear edges
  25876. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25877. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  25878. // not collinear
  25879. // length of vectors for normalizing
  25880. const v_prev_len = Math.sqrt( v_prev_lensq );
  25881. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  25882. // shift adjacent points by unit vectors to the left
  25883. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  25884. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  25885. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  25886. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  25887. // scaling factor for v_prev to intersection point
  25888. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  25889. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  25890. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25891. // vector from inPt to intersection point
  25892. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  25893. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  25894. // Don't normalize!, otherwise sharp corners become ugly
  25895. // but prevent crazy spikes
  25896. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  25897. if ( v_trans_lensq <= 2 ) {
  25898. return new Vector2( v_trans_x, v_trans_y );
  25899. } else {
  25900. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  25901. }
  25902. } else {
  25903. // handle special case of collinear edges
  25904. let direction_eq = false; // assumes: opposite
  25905. if ( v_prev_x > Number.EPSILON ) {
  25906. if ( v_next_x > Number.EPSILON ) {
  25907. direction_eq = true;
  25908. }
  25909. } else {
  25910. if ( v_prev_x < - Number.EPSILON ) {
  25911. if ( v_next_x < - Number.EPSILON ) {
  25912. direction_eq = true;
  25913. }
  25914. } else {
  25915. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  25916. direction_eq = true;
  25917. }
  25918. }
  25919. }
  25920. if ( direction_eq ) {
  25921. // console.log("Warning: lines are a straight sequence");
  25922. v_trans_x = - v_prev_y;
  25923. v_trans_y = v_prev_x;
  25924. shrink_by = Math.sqrt( v_prev_lensq );
  25925. } else {
  25926. // console.log("Warning: lines are a straight spike");
  25927. v_trans_x = v_prev_x;
  25928. v_trans_y = v_prev_y;
  25929. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  25930. }
  25931. }
  25932. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  25933. }
  25934. const contourMovements = [];
  25935. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25936. if ( j === il ) j = 0;
  25937. if ( k === il ) k = 0;
  25938. // (j)---(i)---(k)
  25939. // console.log('i,j,k', i, j , k)
  25940. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  25941. }
  25942. const holesMovements = [];
  25943. let oneHoleMovements, verticesMovements = contourMovements.concat();
  25944. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25945. const ahole = holes[ h ];
  25946. oneHoleMovements = [];
  25947. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25948. if ( j === il ) j = 0;
  25949. if ( k === il ) k = 0;
  25950. // (j)---(i)---(k)
  25951. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  25952. }
  25953. holesMovements.push( oneHoleMovements );
  25954. verticesMovements = verticesMovements.concat( oneHoleMovements );
  25955. }
  25956. let faces;
  25957. if ( bevelSegments === 0 ) {
  25958. faces = ShapeUtils.triangulateShape( contour, holes );
  25959. } else {
  25960. const contractedContourVertices = [];
  25961. const expandedHoleVertices = [];
  25962. // Loop bevelSegments, 1 for the front, 1 for the back
  25963. for ( let b = 0; b < bevelSegments; b ++ ) {
  25964. //for ( b = bevelSegments; b > 0; b -- ) {
  25965. const t = b / bevelSegments;
  25966. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25967. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25968. // contract shape
  25969. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25970. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25971. v( vert.x, vert.y, - z );
  25972. if ( t === 0 ) contractedContourVertices.push( vert );
  25973. }
  25974. // expand holes
  25975. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25976. const ahole = holes[ h ];
  25977. oneHoleMovements = holesMovements[ h ];
  25978. const oneHoleVertices = [];
  25979. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25980. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25981. v( vert.x, vert.y, - z );
  25982. if ( t === 0 ) oneHoleVertices.push( vert );
  25983. }
  25984. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  25985. }
  25986. }
  25987. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  25988. }
  25989. const flen = faces.length;
  25990. const bs = bevelSize + bevelOffset;
  25991. // Back facing vertices
  25992. for ( let i = 0; i < vlen; i ++ ) {
  25993. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25994. if ( ! extrudeByPath ) {
  25995. v( vert.x, vert.y, 0 );
  25996. } else {
  25997. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  25998. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  25999. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  26000. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  26001. v( position2.x, position2.y, position2.z );
  26002. }
  26003. }
  26004. // Add stepped vertices...
  26005. // Including front facing vertices
  26006. for ( let s = 1; s <= steps; s ++ ) {
  26007. for ( let i = 0; i < vlen; i ++ ) {
  26008. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  26009. if ( ! extrudeByPath ) {
  26010. v( vert.x, vert.y, depth / steps * s );
  26011. } else {
  26012. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  26013. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  26014. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  26015. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  26016. v( position2.x, position2.y, position2.z );
  26017. }
  26018. }
  26019. }
  26020. // Add bevel segments planes
  26021. //for ( b = 1; b <= bevelSegments; b ++ ) {
  26022. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  26023. const t = b / bevelSegments;
  26024. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  26025. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  26026. // contract shape
  26027. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  26028. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  26029. v( vert.x, vert.y, depth + z );
  26030. }
  26031. // expand holes
  26032. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26033. const ahole = holes[ h ];
  26034. oneHoleMovements = holesMovements[ h ];
  26035. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  26036. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  26037. if ( ! extrudeByPath ) {
  26038. v( vert.x, vert.y, depth + z );
  26039. } else {
  26040. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  26041. }
  26042. }
  26043. }
  26044. }
  26045. /* Faces */
  26046. // Top and bottom faces
  26047. buildLidFaces();
  26048. // Sides faces
  26049. buildSideFaces();
  26050. ///// Internal functions
  26051. function buildLidFaces() {
  26052. const start = verticesArray.length / 3;
  26053. if ( bevelEnabled ) {
  26054. let layer = 0; // steps + 1
  26055. let offset = vlen * layer;
  26056. // Bottom faces
  26057. for ( let i = 0; i < flen; i ++ ) {
  26058. const face = faces[ i ];
  26059. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  26060. }
  26061. layer = steps + bevelSegments * 2;
  26062. offset = vlen * layer;
  26063. // Top faces
  26064. for ( let i = 0; i < flen; i ++ ) {
  26065. const face = faces[ i ];
  26066. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  26067. }
  26068. } else {
  26069. // Bottom faces
  26070. for ( let i = 0; i < flen; i ++ ) {
  26071. const face = faces[ i ];
  26072. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  26073. }
  26074. // Top faces
  26075. for ( let i = 0; i < flen; i ++ ) {
  26076. const face = faces[ i ];
  26077. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  26078. }
  26079. }
  26080. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  26081. }
  26082. // Create faces for the z-sides of the shape
  26083. function buildSideFaces() {
  26084. const start = verticesArray.length / 3;
  26085. let layeroffset = 0;
  26086. sidewalls( contour, layeroffset );
  26087. layeroffset += contour.length;
  26088. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26089. const ahole = holes[ h ];
  26090. sidewalls( ahole, layeroffset );
  26091. //, true
  26092. layeroffset += ahole.length;
  26093. }
  26094. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  26095. }
  26096. function sidewalls( contour, layeroffset ) {
  26097. let i = contour.length;
  26098. while ( -- i >= 0 ) {
  26099. const j = i;
  26100. let k = i - 1;
  26101. if ( k < 0 ) k = contour.length - 1;
  26102. //console.log('b', i,j, i-1, k,vertices.length);
  26103. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  26104. const slen1 = vlen * s;
  26105. const slen2 = vlen * ( s + 1 );
  26106. const a = layeroffset + j + slen1,
  26107. b = layeroffset + k + slen1,
  26108. c = layeroffset + k + slen2,
  26109. d = layeroffset + j + slen2;
  26110. f4( a, b, c, d );
  26111. }
  26112. }
  26113. }
  26114. function v( x, y, z ) {
  26115. placeholder.push( x );
  26116. placeholder.push( y );
  26117. placeholder.push( z );
  26118. }
  26119. function f3( a, b, c ) {
  26120. addVertex( a );
  26121. addVertex( b );
  26122. addVertex( c );
  26123. const nextIndex = verticesArray.length / 3;
  26124. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26125. addUV( uvs[ 0 ] );
  26126. addUV( uvs[ 1 ] );
  26127. addUV( uvs[ 2 ] );
  26128. }
  26129. function f4( a, b, c, d ) {
  26130. addVertex( a );
  26131. addVertex( b );
  26132. addVertex( d );
  26133. addVertex( b );
  26134. addVertex( c );
  26135. addVertex( d );
  26136. const nextIndex = verticesArray.length / 3;
  26137. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26138. addUV( uvs[ 0 ] );
  26139. addUV( uvs[ 1 ] );
  26140. addUV( uvs[ 3 ] );
  26141. addUV( uvs[ 1 ] );
  26142. addUV( uvs[ 2 ] );
  26143. addUV( uvs[ 3 ] );
  26144. }
  26145. function addVertex( index ) {
  26146. verticesArray.push( placeholder[ index * 3 + 0 ] );
  26147. verticesArray.push( placeholder[ index * 3 + 1 ] );
  26148. verticesArray.push( placeholder[ index * 3 + 2 ] );
  26149. }
  26150. function addUV( vector2 ) {
  26151. uvArray.push( vector2.x );
  26152. uvArray.push( vector2.y );
  26153. }
  26154. }
  26155. }
  26156. copy( source ) {
  26157. super.copy( source );
  26158. this.parameters = Object.assign( {}, source.parameters );
  26159. return this;
  26160. }
  26161. toJSON() {
  26162. const data = super.toJSON();
  26163. const shapes = this.parameters.shapes;
  26164. const options = this.parameters.options;
  26165. return toJSON$1( shapes, options, data );
  26166. }
  26167. /**
  26168. * Factory method for creating an instance of this class from the given
  26169. * JSON object.
  26170. *
  26171. * @param {Object} data - A JSON object representing the serialized geometry.
  26172. * @param {Array<Shape>} shapes - An array of shapes.
  26173. * @return {ExtrudeGeometry} A new instance.
  26174. */
  26175. static fromJSON( data, shapes ) {
  26176. const geometryShapes = [];
  26177. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26178. const shape = shapes[ data.shapes[ j ] ];
  26179. geometryShapes.push( shape );
  26180. }
  26181. const extrudePath = data.options.extrudePath;
  26182. if ( extrudePath !== undefined ) {
  26183. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  26184. }
  26185. return new ExtrudeGeometry( geometryShapes, data.options );
  26186. }
  26187. }
  26188. const WorldUVGenerator = {
  26189. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  26190. const a_x = vertices[ indexA * 3 ];
  26191. const a_y = vertices[ indexA * 3 + 1 ];
  26192. const b_x = vertices[ indexB * 3 ];
  26193. const b_y = vertices[ indexB * 3 + 1 ];
  26194. const c_x = vertices[ indexC * 3 ];
  26195. const c_y = vertices[ indexC * 3 + 1 ];
  26196. return [
  26197. new Vector2( a_x, a_y ),
  26198. new Vector2( b_x, b_y ),
  26199. new Vector2( c_x, c_y )
  26200. ];
  26201. },
  26202. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  26203. const a_x = vertices[ indexA * 3 ];
  26204. const a_y = vertices[ indexA * 3 + 1 ];
  26205. const a_z = vertices[ indexA * 3 + 2 ];
  26206. const b_x = vertices[ indexB * 3 ];
  26207. const b_y = vertices[ indexB * 3 + 1 ];
  26208. const b_z = vertices[ indexB * 3 + 2 ];
  26209. const c_x = vertices[ indexC * 3 ];
  26210. const c_y = vertices[ indexC * 3 + 1 ];
  26211. const c_z = vertices[ indexC * 3 + 2 ];
  26212. const d_x = vertices[ indexD * 3 ];
  26213. const d_y = vertices[ indexD * 3 + 1 ];
  26214. const d_z = vertices[ indexD * 3 + 2 ];
  26215. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  26216. return [
  26217. new Vector2( a_x, 1 - a_z ),
  26218. new Vector2( b_x, 1 - b_z ),
  26219. new Vector2( c_x, 1 - c_z ),
  26220. new Vector2( d_x, 1 - d_z )
  26221. ];
  26222. } else {
  26223. return [
  26224. new Vector2( a_y, 1 - a_z ),
  26225. new Vector2( b_y, 1 - b_z ),
  26226. new Vector2( c_y, 1 - c_z ),
  26227. new Vector2( d_y, 1 - d_z )
  26228. ];
  26229. }
  26230. }
  26231. };
  26232. function toJSON$1( shapes, options, data ) {
  26233. data.shapes = [];
  26234. if ( Array.isArray( shapes ) ) {
  26235. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26236. const shape = shapes[ i ];
  26237. data.shapes.push( shape.uuid );
  26238. }
  26239. } else {
  26240. data.shapes.push( shapes.uuid );
  26241. }
  26242. data.options = Object.assign( {}, options );
  26243. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  26244. return data;
  26245. }
  26246. /**
  26247. * A geometry class for representing an icosahedron.
  26248. *
  26249. * ```js
  26250. * const geometry = new THREE.IcosahedronGeometry();
  26251. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26252. * const icosahedron = new THREE.Mesh( geometry, material );
  26253. * scene.add( icosahedron );
  26254. * ```
  26255. *
  26256. * @augments PolyhedronGeometry
  26257. */
  26258. class IcosahedronGeometry extends PolyhedronGeometry {
  26259. /**
  26260. * Constructs a new icosahedron geometry.
  26261. *
  26262. * @param {number} [radius=1] - Radius of the icosahedron.
  26263. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  26264. */
  26265. constructor( radius = 1, detail = 0 ) {
  26266. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  26267. const vertices = [
  26268. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  26269. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  26270. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  26271. ];
  26272. const indices = [
  26273. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  26274. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  26275. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  26276. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  26277. ];
  26278. super( vertices, indices, radius, detail );
  26279. this.type = 'IcosahedronGeometry';
  26280. /**
  26281. * Holds the constructor parameters that have been
  26282. * used to generate the geometry. Any modification
  26283. * after instantiation does not change the geometry.
  26284. *
  26285. * @type {Object}
  26286. */
  26287. this.parameters = {
  26288. radius: radius,
  26289. detail: detail
  26290. };
  26291. }
  26292. /**
  26293. * Factory method for creating an instance of this class from the given
  26294. * JSON object.
  26295. *
  26296. * @param {Object} data - A JSON object representing the serialized geometry.
  26297. * @return {IcosahedronGeometry} A new instance.
  26298. */
  26299. static fromJSON( data ) {
  26300. return new IcosahedronGeometry( data.radius, data.detail );
  26301. }
  26302. }
  26303. /**
  26304. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  26305. *
  26306. * ```js
  26307. * const points = [];
  26308. * for ( let i = 0; i < 10; i ++ ) {
  26309. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  26310. * }
  26311. * const geometry = new THREE.LatheGeometry( points );
  26312. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26313. * const lathe = new THREE.Mesh( geometry, material );
  26314. * scene.add( lathe );
  26315. * ```
  26316. *
  26317. * @augments BufferGeometry
  26318. */
  26319. class LatheGeometry extends BufferGeometry {
  26320. /**
  26321. * Constructs a new lathe geometry.
  26322. *
  26323. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  26324. * must be greater than zero.
  26325. * @param {number} [segments=12] - The number of circumference segments to generate.
  26326. * @param {number} [phiStart=0] - The starting angle in radians.
  26327. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  26328. * closed lathe, less than 2PI is a portion.
  26329. */
  26330. 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 ) {
  26331. super();
  26332. this.type = 'LatheGeometry';
  26333. /**
  26334. * Holds the constructor parameters that have been
  26335. * used to generate the geometry. Any modification
  26336. * after instantiation does not change the geometry.
  26337. *
  26338. * @type {Object}
  26339. */
  26340. this.parameters = {
  26341. points: points,
  26342. segments: segments,
  26343. phiStart: phiStart,
  26344. phiLength: phiLength
  26345. };
  26346. segments = Math.floor( segments );
  26347. // clamp phiLength so it's in range of [ 0, 2PI ]
  26348. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  26349. // buffers
  26350. const indices = [];
  26351. const vertices = [];
  26352. const uvs = [];
  26353. const initNormals = [];
  26354. const normals = [];
  26355. // helper variables
  26356. const inverseSegments = 1.0 / segments;
  26357. const vertex = new Vector3();
  26358. const uv = new Vector2();
  26359. const normal = new Vector3();
  26360. const curNormal = new Vector3();
  26361. const prevNormal = new Vector3();
  26362. let dx = 0;
  26363. let dy = 0;
  26364. // pre-compute normals for initial "meridian"
  26365. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26366. switch ( j ) {
  26367. case 0: // special handling for 1st vertex on path
  26368. dx = points[ j + 1 ].x - points[ j ].x;
  26369. dy = points[ j + 1 ].y - points[ j ].y;
  26370. normal.x = dy * 1.0;
  26371. normal.y = - dx;
  26372. normal.z = dy * 0.0;
  26373. prevNormal.copy( normal );
  26374. normal.normalize();
  26375. initNormals.push( normal.x, normal.y, normal.z );
  26376. break;
  26377. case ( points.length - 1 ): // special handling for last Vertex on path
  26378. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  26379. break;
  26380. default: // default handling for all vertices in between
  26381. dx = points[ j + 1 ].x - points[ j ].x;
  26382. dy = points[ j + 1 ].y - points[ j ].y;
  26383. normal.x = dy * 1.0;
  26384. normal.y = - dx;
  26385. normal.z = dy * 0.0;
  26386. curNormal.copy( normal );
  26387. normal.x += prevNormal.x;
  26388. normal.y += prevNormal.y;
  26389. normal.z += prevNormal.z;
  26390. normal.normalize();
  26391. initNormals.push( normal.x, normal.y, normal.z );
  26392. prevNormal.copy( curNormal );
  26393. }
  26394. }
  26395. // generate vertices, uvs and normals
  26396. for ( let i = 0; i <= segments; i ++ ) {
  26397. const phi = phiStart + i * inverseSegments * phiLength;
  26398. const sin = Math.sin( phi );
  26399. const cos = Math.cos( phi );
  26400. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26401. // vertex
  26402. vertex.x = points[ j ].x * sin;
  26403. vertex.y = points[ j ].y;
  26404. vertex.z = points[ j ].x * cos;
  26405. vertices.push( vertex.x, vertex.y, vertex.z );
  26406. // uv
  26407. uv.x = i / segments;
  26408. uv.y = j / ( points.length - 1 );
  26409. uvs.push( uv.x, uv.y );
  26410. // normal
  26411. const x = initNormals[ 3 * j + 0 ] * sin;
  26412. const y = initNormals[ 3 * j + 1 ];
  26413. const z = initNormals[ 3 * j + 0 ] * cos;
  26414. normals.push( x, y, z );
  26415. }
  26416. }
  26417. // indices
  26418. for ( let i = 0; i < segments; i ++ ) {
  26419. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  26420. const base = j + i * points.length;
  26421. const a = base;
  26422. const b = base + points.length;
  26423. const c = base + points.length + 1;
  26424. const d = base + 1;
  26425. // faces
  26426. indices.push( a, b, d );
  26427. indices.push( c, d, b );
  26428. }
  26429. }
  26430. // build geometry
  26431. this.setIndex( indices );
  26432. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26433. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26434. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26435. }
  26436. copy( source ) {
  26437. super.copy( source );
  26438. this.parameters = Object.assign( {}, source.parameters );
  26439. return this;
  26440. }
  26441. /**
  26442. * Factory method for creating an instance of this class from the given
  26443. * JSON object.
  26444. *
  26445. * @param {Object} data - A JSON object representing the serialized geometry.
  26446. * @return {LatheGeometry} A new instance.
  26447. */
  26448. static fromJSON( data ) {
  26449. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  26450. }
  26451. }
  26452. /**
  26453. * A geometry class for representing an octahedron.
  26454. *
  26455. * ```js
  26456. * const geometry = new THREE.OctahedronGeometry();
  26457. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26458. * const octahedron = new THREE.Mesh( geometry, material );
  26459. * scene.add( octahedron );
  26460. * ```
  26461. *
  26462. * @augments PolyhedronGeometry
  26463. */
  26464. class OctahedronGeometry extends PolyhedronGeometry {
  26465. /**
  26466. * Constructs a new octahedron geometry.
  26467. *
  26468. * @param {number} [radius=1] - Radius of the octahedron.
  26469. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  26470. */
  26471. constructor( radius = 1, detail = 0 ) {
  26472. const vertices = [
  26473. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  26474. 0, -1, 0, 0, 0, 1, 0, 0, -1
  26475. ];
  26476. const indices = [
  26477. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  26478. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  26479. 1, 3, 4, 1, 4, 2
  26480. ];
  26481. super( vertices, indices, radius, detail );
  26482. this.type = 'OctahedronGeometry';
  26483. /**
  26484. * Holds the constructor parameters that have been
  26485. * used to generate the geometry. Any modification
  26486. * after instantiation does not change the geometry.
  26487. *
  26488. * @type {Object}
  26489. */
  26490. this.parameters = {
  26491. radius: radius,
  26492. detail: detail
  26493. };
  26494. }
  26495. /**
  26496. * Factory method for creating an instance of this class from the given
  26497. * JSON object.
  26498. *
  26499. * @param {Object} data - A JSON object representing the serialized geometry.
  26500. * @return {OctahedronGeometry} A new instance.
  26501. */
  26502. static fromJSON( data ) {
  26503. return new OctahedronGeometry( data.radius, data.detail );
  26504. }
  26505. }
  26506. /**
  26507. * A geometry class for representing a plane.
  26508. *
  26509. * ```js
  26510. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  26511. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26512. * const plane = new THREE.Mesh( geometry, material );
  26513. * scene.add( plane );
  26514. * ```
  26515. *
  26516. * @augments BufferGeometry
  26517. */
  26518. class PlaneGeometry extends BufferGeometry {
  26519. /**
  26520. * Constructs a new plane geometry.
  26521. *
  26522. * @param {number} [width=1] - The width along the X axis.
  26523. * @param {number} [height=1] - The height along the Y axis
  26524. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  26525. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  26526. */
  26527. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  26528. super();
  26529. this.type = 'PlaneGeometry';
  26530. /**
  26531. * Holds the constructor parameters that have been
  26532. * used to generate the geometry. Any modification
  26533. * after instantiation does not change the geometry.
  26534. *
  26535. * @type {Object}
  26536. */
  26537. this.parameters = {
  26538. width: width,
  26539. height: height,
  26540. widthSegments: widthSegments,
  26541. heightSegments: heightSegments
  26542. };
  26543. const width_half = width / 2;
  26544. const height_half = height / 2;
  26545. const gridX = Math.floor( widthSegments );
  26546. const gridY = Math.floor( heightSegments );
  26547. const gridX1 = gridX + 1;
  26548. const gridY1 = gridY + 1;
  26549. const segment_width = width / gridX;
  26550. const segment_height = height / gridY;
  26551. //
  26552. const indices = [];
  26553. const vertices = [];
  26554. const normals = [];
  26555. const uvs = [];
  26556. for ( let iy = 0; iy < gridY1; iy ++ ) {
  26557. const y = iy * segment_height - height_half;
  26558. for ( let ix = 0; ix < gridX1; ix ++ ) {
  26559. const x = ix * segment_width - width_half;
  26560. vertices.push( x, - y, 0 );
  26561. normals.push( 0, 0, 1 );
  26562. uvs.push( ix / gridX );
  26563. uvs.push( 1 - ( iy / gridY ) );
  26564. }
  26565. }
  26566. for ( let iy = 0; iy < gridY; iy ++ ) {
  26567. for ( let ix = 0; ix < gridX; ix ++ ) {
  26568. const a = ix + gridX1 * iy;
  26569. const b = ix + gridX1 * ( iy + 1 );
  26570. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  26571. const d = ( ix + 1 ) + gridX1 * iy;
  26572. indices.push( a, b, d );
  26573. indices.push( b, c, d );
  26574. }
  26575. }
  26576. this.setIndex( indices );
  26577. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26578. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26579. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26580. }
  26581. copy( source ) {
  26582. super.copy( source );
  26583. this.parameters = Object.assign( {}, source.parameters );
  26584. return this;
  26585. }
  26586. /**
  26587. * Factory method for creating an instance of this class from the given
  26588. * JSON object.
  26589. *
  26590. * @param {Object} data - A JSON object representing the serialized geometry.
  26591. * @return {PlaneGeometry} A new instance.
  26592. */
  26593. static fromJSON( data ) {
  26594. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  26595. }
  26596. }
  26597. /**
  26598. * A class for generating a two-dimensional ring geometry.
  26599. *
  26600. * ```js
  26601. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  26602. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26603. * const mesh = new THREE.Mesh( geometry, material );
  26604. * scene.add( mesh );
  26605. * ```
  26606. *
  26607. * @augments BufferGeometry
  26608. */
  26609. class RingGeometry extends BufferGeometry {
  26610. /**
  26611. * Constructs a new ring geometry.
  26612. *
  26613. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  26614. * @param {number} [outerRadius=1] - The outer radius of the ring.
  26615. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  26616. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  26617. * @param {number} [thetaStart=0] - Starting angle in radians.
  26618. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  26619. */
  26620. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26621. super();
  26622. this.type = 'RingGeometry';
  26623. /**
  26624. * Holds the constructor parameters that have been
  26625. * used to generate the geometry. Any modification
  26626. * after instantiation does not change the geometry.
  26627. *
  26628. * @type {Object}
  26629. */
  26630. this.parameters = {
  26631. innerRadius: innerRadius,
  26632. outerRadius: outerRadius,
  26633. thetaSegments: thetaSegments,
  26634. phiSegments: phiSegments,
  26635. thetaStart: thetaStart,
  26636. thetaLength: thetaLength
  26637. };
  26638. thetaSegments = Math.max( 3, thetaSegments );
  26639. phiSegments = Math.max( 1, phiSegments );
  26640. // buffers
  26641. const indices = [];
  26642. const vertices = [];
  26643. const normals = [];
  26644. const uvs = [];
  26645. // some helper variables
  26646. let radius = innerRadius;
  26647. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  26648. const vertex = new Vector3();
  26649. const uv = new Vector2();
  26650. // generate vertices, normals and uvs
  26651. for ( let j = 0; j <= phiSegments; j ++ ) {
  26652. for ( let i = 0; i <= thetaSegments; i ++ ) {
  26653. // values are generate from the inside of the ring to the outside
  26654. const segment = thetaStart + i / thetaSegments * thetaLength;
  26655. // vertex
  26656. vertex.x = radius * Math.cos( segment );
  26657. vertex.y = radius * Math.sin( segment );
  26658. vertices.push( vertex.x, vertex.y, vertex.z );
  26659. // normal
  26660. normals.push( 0, 0, 1 );
  26661. // uv
  26662. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  26663. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  26664. uvs.push( uv.x, uv.y );
  26665. }
  26666. // increase the radius for next row of vertices
  26667. radius += radiusStep;
  26668. }
  26669. // indices
  26670. for ( let j = 0; j < phiSegments; j ++ ) {
  26671. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  26672. for ( let i = 0; i < thetaSegments; i ++ ) {
  26673. const segment = i + thetaSegmentLevel;
  26674. const a = segment;
  26675. const b = segment + thetaSegments + 1;
  26676. const c = segment + thetaSegments + 2;
  26677. const d = segment + 1;
  26678. // faces
  26679. indices.push( a, b, d );
  26680. indices.push( b, c, d );
  26681. }
  26682. }
  26683. // build geometry
  26684. this.setIndex( indices );
  26685. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26686. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26687. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26688. }
  26689. copy( source ) {
  26690. super.copy( source );
  26691. this.parameters = Object.assign( {}, source.parameters );
  26692. return this;
  26693. }
  26694. /**
  26695. * Factory method for creating an instance of this class from the given
  26696. * JSON object.
  26697. *
  26698. * @param {Object} data - A JSON object representing the serialized geometry.
  26699. * @return {RingGeometry} A new instance.
  26700. */
  26701. static fromJSON( data ) {
  26702. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  26703. }
  26704. }
  26705. /**
  26706. * Creates an one-sided polygonal geometry from one or more path shapes.
  26707. *
  26708. * ```js
  26709. * const arcShape = new THREE.Shape()
  26710. * .moveTo( 5, 1 )
  26711. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  26712. *
  26713. * const geometry = new THREE.ShapeGeometry( arcShape );
  26714. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  26715. * const mesh = new THREE.Mesh( geometry, material ) ;
  26716. * scene.add( mesh );
  26717. * ```
  26718. *
  26719. * @augments BufferGeometry
  26720. */
  26721. class ShapeGeometry extends BufferGeometry {
  26722. /**
  26723. * Constructs a new shape geometry.
  26724. *
  26725. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26726. * @param {number} [curveSegments=12] - Number of segments per shape.
  26727. */
  26728. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  26729. super();
  26730. this.type = 'ShapeGeometry';
  26731. /**
  26732. * Holds the constructor parameters that have been
  26733. * used to generate the geometry. Any modification
  26734. * after instantiation does not change the geometry.
  26735. *
  26736. * @type {Object}
  26737. */
  26738. this.parameters = {
  26739. shapes: shapes,
  26740. curveSegments: curveSegments
  26741. };
  26742. // buffers
  26743. const indices = [];
  26744. const vertices = [];
  26745. const normals = [];
  26746. const uvs = [];
  26747. // helper variables
  26748. let groupStart = 0;
  26749. let groupCount = 0;
  26750. // allow single and array values for "shapes" parameter
  26751. if ( Array.isArray( shapes ) === false ) {
  26752. addShape( shapes );
  26753. } else {
  26754. for ( let i = 0; i < shapes.length; i ++ ) {
  26755. addShape( shapes[ i ] );
  26756. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  26757. groupStart += groupCount;
  26758. groupCount = 0;
  26759. }
  26760. }
  26761. // build geometry
  26762. this.setIndex( indices );
  26763. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26764. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26765. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26766. // helper functions
  26767. function addShape( shape ) {
  26768. const indexOffset = vertices.length / 3;
  26769. const points = shape.extractPoints( curveSegments );
  26770. let shapeVertices = points.shape;
  26771. const shapeHoles = points.holes;
  26772. // check direction of vertices
  26773. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  26774. shapeVertices = shapeVertices.reverse();
  26775. }
  26776. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26777. const shapeHole = shapeHoles[ i ];
  26778. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  26779. shapeHoles[ i ] = shapeHole.reverse();
  26780. }
  26781. }
  26782. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  26783. // join vertices of inner and outer paths to a single array
  26784. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26785. const shapeHole = shapeHoles[ i ];
  26786. shapeVertices = shapeVertices.concat( shapeHole );
  26787. }
  26788. // vertices, normals, uvs
  26789. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  26790. const vertex = shapeVertices[ i ];
  26791. vertices.push( vertex.x, vertex.y, 0 );
  26792. normals.push( 0, 0, 1 );
  26793. uvs.push( vertex.x, vertex.y ); // world uvs
  26794. }
  26795. // indices
  26796. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  26797. const face = faces[ i ];
  26798. const a = face[ 0 ] + indexOffset;
  26799. const b = face[ 1 ] + indexOffset;
  26800. const c = face[ 2 ] + indexOffset;
  26801. indices.push( a, b, c );
  26802. groupCount += 3;
  26803. }
  26804. }
  26805. }
  26806. copy( source ) {
  26807. super.copy( source );
  26808. this.parameters = Object.assign( {}, source.parameters );
  26809. return this;
  26810. }
  26811. toJSON() {
  26812. const data = super.toJSON();
  26813. const shapes = this.parameters.shapes;
  26814. return toJSON( shapes, data );
  26815. }
  26816. /**
  26817. * Factory method for creating an instance of this class from the given
  26818. * JSON object.
  26819. *
  26820. * @param {Object} data - A JSON object representing the serialized geometry.
  26821. * @param {Array<Shape>} shapes - An array of shapes.
  26822. * @return {ShapeGeometry} A new instance.
  26823. */
  26824. static fromJSON( data, shapes ) {
  26825. const geometryShapes = [];
  26826. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26827. const shape = shapes[ data.shapes[ j ] ];
  26828. geometryShapes.push( shape );
  26829. }
  26830. return new ShapeGeometry( geometryShapes, data.curveSegments );
  26831. }
  26832. }
  26833. function toJSON( shapes, data ) {
  26834. data.shapes = [];
  26835. if ( Array.isArray( shapes ) ) {
  26836. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26837. const shape = shapes[ i ];
  26838. data.shapes.push( shape.uuid );
  26839. }
  26840. } else {
  26841. data.shapes.push( shapes.uuid );
  26842. }
  26843. return data;
  26844. }
  26845. /**
  26846. * A class for generating a sphere geometry.
  26847. *
  26848. * ```js
  26849. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  26850. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26851. * const sphere = new THREE.Mesh( geometry, material );
  26852. * scene.add( sphere );
  26853. * ```
  26854. *
  26855. * @augments BufferGeometry
  26856. */
  26857. class SphereGeometry extends BufferGeometry {
  26858. /**
  26859. * Constructs a new sphere geometry.
  26860. *
  26861. * @param {number} [radius=1] - The sphere radius.
  26862. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  26863. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  26864. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  26865. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  26866. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  26867. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  26868. */
  26869. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  26870. super();
  26871. this.type = 'SphereGeometry';
  26872. /**
  26873. * Holds the constructor parameters that have been
  26874. * used to generate the geometry. Any modification
  26875. * after instantiation does not change the geometry.
  26876. *
  26877. * @type {Object}
  26878. */
  26879. this.parameters = {
  26880. radius: radius,
  26881. widthSegments: widthSegments,
  26882. heightSegments: heightSegments,
  26883. phiStart: phiStart,
  26884. phiLength: phiLength,
  26885. thetaStart: thetaStart,
  26886. thetaLength: thetaLength
  26887. };
  26888. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  26889. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  26890. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  26891. let index = 0;
  26892. const grid = [];
  26893. const vertex = new Vector3();
  26894. const normal = new Vector3();
  26895. // buffers
  26896. const indices = [];
  26897. const vertices = [];
  26898. const normals = [];
  26899. const uvs = [];
  26900. // generate vertices, normals and uvs
  26901. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  26902. const verticesRow = [];
  26903. const v = iy / heightSegments;
  26904. // special case for the poles
  26905. let uOffset = 0;
  26906. if ( iy === 0 && thetaStart === 0 ) {
  26907. uOffset = 0.5 / widthSegments;
  26908. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  26909. uOffset = -0.5 / widthSegments;
  26910. }
  26911. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  26912. const u = ix / widthSegments;
  26913. // vertex
  26914. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26915. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  26916. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26917. vertices.push( vertex.x, vertex.y, vertex.z );
  26918. // normal
  26919. normal.copy( vertex ).normalize();
  26920. normals.push( normal.x, normal.y, normal.z );
  26921. // uv
  26922. uvs.push( u + uOffset, 1 - v );
  26923. verticesRow.push( index ++ );
  26924. }
  26925. grid.push( verticesRow );
  26926. }
  26927. // indices
  26928. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  26929. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  26930. const a = grid[ iy ][ ix + 1 ];
  26931. const b = grid[ iy ][ ix ];
  26932. const c = grid[ iy + 1 ][ ix ];
  26933. const d = grid[ iy + 1 ][ ix + 1 ];
  26934. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  26935. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  26936. }
  26937. }
  26938. // build geometry
  26939. this.setIndex( indices );
  26940. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26941. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26942. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26943. }
  26944. copy( source ) {
  26945. super.copy( source );
  26946. this.parameters = Object.assign( {}, source.parameters );
  26947. return this;
  26948. }
  26949. /**
  26950. * Factory method for creating an instance of this class from the given
  26951. * JSON object.
  26952. *
  26953. * @param {Object} data - A JSON object representing the serialized geometry.
  26954. * @return {SphereGeometry} A new instance.
  26955. */
  26956. static fromJSON( data ) {
  26957. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  26958. }
  26959. }
  26960. /**
  26961. * A geometry class for representing an tetrahedron.
  26962. *
  26963. * ```js
  26964. * const geometry = new THREE.TetrahedronGeometry();
  26965. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26966. * const tetrahedron = new THREE.Mesh( geometry, material );
  26967. * scene.add( tetrahedron );
  26968. * ```
  26969. *
  26970. * @augments PolyhedronGeometry
  26971. */
  26972. class TetrahedronGeometry extends PolyhedronGeometry {
  26973. /**
  26974. * Constructs a new tetrahedron geometry.
  26975. *
  26976. * @param {number} [radius=1] - Radius of the tetrahedron.
  26977. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  26978. */
  26979. constructor( radius = 1, detail = 0 ) {
  26980. const vertices = [
  26981. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  26982. ];
  26983. const indices = [
  26984. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  26985. ];
  26986. super( vertices, indices, radius, detail );
  26987. this.type = 'TetrahedronGeometry';
  26988. /**
  26989. * Holds the constructor parameters that have been
  26990. * used to generate the geometry. Any modification
  26991. * after instantiation does not change the geometry.
  26992. *
  26993. * @type {Object}
  26994. */
  26995. this.parameters = {
  26996. radius: radius,
  26997. detail: detail
  26998. };
  26999. }
  27000. /**
  27001. * Factory method for creating an instance of this class from the given
  27002. * JSON object.
  27003. *
  27004. * @param {Object} data - A JSON object representing the serialized geometry.
  27005. * @return {TetrahedronGeometry} A new instance.
  27006. */
  27007. static fromJSON( data ) {
  27008. return new TetrahedronGeometry( data.radius, data.detail );
  27009. }
  27010. }
  27011. /**
  27012. * A geometry class for representing an torus.
  27013. *
  27014. * ```js
  27015. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  27016. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27017. * const torus = new THREE.Mesh( geometry, material );
  27018. * scene.add( torus );
  27019. * ```
  27020. *
  27021. * @augments BufferGeometry
  27022. */
  27023. class TorusGeometry extends BufferGeometry {
  27024. /**
  27025. * Constructs a new torus geometry.
  27026. *
  27027. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  27028. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  27029. * @param {number} [radialSegments=12] - The number of radial segments.
  27030. * @param {number} [tubularSegments=48] - The number of tubular segments.
  27031. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  27032. */
  27033. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  27034. super();
  27035. this.type = 'TorusGeometry';
  27036. /**
  27037. * Holds the constructor parameters that have been
  27038. * used to generate the geometry. Any modification
  27039. * after instantiation does not change the geometry.
  27040. *
  27041. * @type {Object}
  27042. */
  27043. this.parameters = {
  27044. radius: radius,
  27045. tube: tube,
  27046. radialSegments: radialSegments,
  27047. tubularSegments: tubularSegments,
  27048. arc: arc
  27049. };
  27050. radialSegments = Math.floor( radialSegments );
  27051. tubularSegments = Math.floor( tubularSegments );
  27052. // buffers
  27053. const indices = [];
  27054. const vertices = [];
  27055. const normals = [];
  27056. const uvs = [];
  27057. // helper variables
  27058. const center = new Vector3();
  27059. const vertex = new Vector3();
  27060. const normal = new Vector3();
  27061. // generate vertices, normals and uvs
  27062. for ( let j = 0; j <= radialSegments; j ++ ) {
  27063. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27064. const u = i / tubularSegments * arc;
  27065. const v = j / radialSegments * Math.PI * 2;
  27066. // vertex
  27067. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  27068. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  27069. vertex.z = tube * Math.sin( v );
  27070. vertices.push( vertex.x, vertex.y, vertex.z );
  27071. // normal
  27072. center.x = radius * Math.cos( u );
  27073. center.y = radius * Math.sin( u );
  27074. normal.subVectors( vertex, center ).normalize();
  27075. normals.push( normal.x, normal.y, normal.z );
  27076. // uv
  27077. uvs.push( i / tubularSegments );
  27078. uvs.push( j / radialSegments );
  27079. }
  27080. }
  27081. // generate indices
  27082. for ( let j = 1; j <= radialSegments; j ++ ) {
  27083. for ( let i = 1; i <= tubularSegments; i ++ ) {
  27084. // indices
  27085. const a = ( tubularSegments + 1 ) * j + i - 1;
  27086. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  27087. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  27088. const d = ( tubularSegments + 1 ) * j + i;
  27089. // faces
  27090. indices.push( a, b, d );
  27091. indices.push( b, c, d );
  27092. }
  27093. }
  27094. // build geometry
  27095. this.setIndex( indices );
  27096. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27097. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27098. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27099. }
  27100. copy( source ) {
  27101. super.copy( source );
  27102. this.parameters = Object.assign( {}, source.parameters );
  27103. return this;
  27104. }
  27105. /**
  27106. * Factory method for creating an instance of this class from the given
  27107. * JSON object.
  27108. *
  27109. * @param {Object} data - A JSON object representing the serialized geometry.
  27110. * @return {TorusGeometry} A new instance.
  27111. */
  27112. static fromJSON( data ) {
  27113. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  27114. }
  27115. }
  27116. /**
  27117. * Creates a torus knot, the particular shape of which is defined by a pair
  27118. * of coprime integers, p and q. If p and q are not coprime, the result will
  27119. * be a torus link.
  27120. *
  27121. * ```js
  27122. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  27123. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27124. * const torusKnot = new THREE.Mesh( geometry, material );
  27125. * scene.add( torusKnot );
  27126. * ```
  27127. *
  27128. * @augments BufferGeometry
  27129. */
  27130. class TorusKnotGeometry extends BufferGeometry {
  27131. /**
  27132. * Constructs a new torus knot geometry.
  27133. *
  27134. * @param {number} [radius=1] - Radius of the torus knot.
  27135. * @param {number} [tube=0.4] - Radius of the tube.
  27136. * @param {number} [tubularSegments=64] - The number of tubular segments.
  27137. * @param {number} [radialSegments=8] - The number of radial segments.
  27138. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  27139. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  27140. */
  27141. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  27142. super();
  27143. this.type = 'TorusKnotGeometry';
  27144. /**
  27145. * Holds the constructor parameters that have been
  27146. * used to generate the geometry. Any modification
  27147. * after instantiation does not change the geometry.
  27148. *
  27149. * @type {Object}
  27150. */
  27151. this.parameters = {
  27152. radius: radius,
  27153. tube: tube,
  27154. tubularSegments: tubularSegments,
  27155. radialSegments: radialSegments,
  27156. p: p,
  27157. q: q
  27158. };
  27159. tubularSegments = Math.floor( tubularSegments );
  27160. radialSegments = Math.floor( radialSegments );
  27161. // buffers
  27162. const indices = [];
  27163. const vertices = [];
  27164. const normals = [];
  27165. const uvs = [];
  27166. // helper variables
  27167. const vertex = new Vector3();
  27168. const normal = new Vector3();
  27169. const P1 = new Vector3();
  27170. const P2 = new Vector3();
  27171. const B = new Vector3();
  27172. const T = new Vector3();
  27173. const N = new Vector3();
  27174. // generate vertices, normals and uvs
  27175. for ( let i = 0; i <= tubularSegments; ++ i ) {
  27176. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  27177. const u = i / tubularSegments * p * Math.PI * 2;
  27178. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  27179. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  27180. calculatePositionOnCurve( u, p, q, radius, P1 );
  27181. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  27182. // calculate orthonormal basis
  27183. T.subVectors( P2, P1 );
  27184. N.addVectors( P2, P1 );
  27185. B.crossVectors( T, N );
  27186. N.crossVectors( B, T );
  27187. // normalize B, N. T can be ignored, we don't use it
  27188. B.normalize();
  27189. N.normalize();
  27190. for ( let j = 0; j <= radialSegments; ++ j ) {
  27191. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  27192. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  27193. const v = j / radialSegments * Math.PI * 2;
  27194. const cx = - tube * Math.cos( v );
  27195. const cy = tube * Math.sin( v );
  27196. // now calculate the final vertex position.
  27197. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  27198. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  27199. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  27200. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  27201. vertices.push( vertex.x, vertex.y, vertex.z );
  27202. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  27203. normal.subVectors( vertex, P1 ).normalize();
  27204. normals.push( normal.x, normal.y, normal.z );
  27205. // uv
  27206. uvs.push( i / tubularSegments );
  27207. uvs.push( j / radialSegments );
  27208. }
  27209. }
  27210. // generate indices
  27211. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27212. for ( let i = 1; i <= radialSegments; i ++ ) {
  27213. // indices
  27214. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27215. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27216. const c = ( radialSegments + 1 ) * j + i;
  27217. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27218. // faces
  27219. indices.push( a, b, d );
  27220. indices.push( b, c, d );
  27221. }
  27222. }
  27223. // build geometry
  27224. this.setIndex( indices );
  27225. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27226. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27227. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27228. // this function calculates the current position on the torus curve
  27229. function calculatePositionOnCurve( u, p, q, radius, position ) {
  27230. const cu = Math.cos( u );
  27231. const su = Math.sin( u );
  27232. const quOverP = q / p * u;
  27233. const cs = Math.cos( quOverP );
  27234. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  27235. position.y = radius * ( 2 + cs ) * su * 0.5;
  27236. position.z = radius * Math.sin( quOverP ) * 0.5;
  27237. }
  27238. }
  27239. copy( source ) {
  27240. super.copy( source );
  27241. this.parameters = Object.assign( {}, source.parameters );
  27242. return this;
  27243. }
  27244. /**
  27245. * Factory method for creating an instance of this class from the given
  27246. * JSON object.
  27247. *
  27248. * @param {Object} data - A JSON object representing the serialized geometry.
  27249. * @return {TorusKnotGeometry} A new instance.
  27250. */
  27251. static fromJSON( data ) {
  27252. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  27253. }
  27254. }
  27255. /**
  27256. * Creates a tube that extrudes along a 3D curve.
  27257. *
  27258. * ```js
  27259. * class CustomSinCurve extends THREE.Curve {
  27260. *
  27261. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  27262. *
  27263. * const tx = t * 3 - 1.5;
  27264. * const ty = Math.sin( 2 * Math.PI * t );
  27265. * const tz = 0;
  27266. *
  27267. * return optionalTarget.set( tx, ty, tz );
  27268. * }
  27269. *
  27270. * }
  27271. *
  27272. * const path = new CustomSinCurve( 10 );
  27273. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  27274. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  27275. * const mesh = new THREE.Mesh( geometry, material );
  27276. * scene.add( mesh );
  27277. * ```
  27278. *
  27279. * @augments BufferGeometry
  27280. */
  27281. class TubeGeometry extends BufferGeometry {
  27282. /**
  27283. * Constructs a new tube geometry.
  27284. *
  27285. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  27286. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  27287. * @param {number} [radius=1] -The radius of the tube.
  27288. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  27289. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  27290. */
  27291. 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 ) {
  27292. super();
  27293. this.type = 'TubeGeometry';
  27294. /**
  27295. * Holds the constructor parameters that have been
  27296. * used to generate the geometry. Any modification
  27297. * after instantiation does not change the geometry.
  27298. *
  27299. * @type {Object}
  27300. */
  27301. this.parameters = {
  27302. path: path,
  27303. tubularSegments: tubularSegments,
  27304. radius: radius,
  27305. radialSegments: radialSegments,
  27306. closed: closed
  27307. };
  27308. const frames = path.computeFrenetFrames( tubularSegments, closed );
  27309. // expose internals
  27310. this.tangents = frames.tangents;
  27311. this.normals = frames.normals;
  27312. this.binormals = frames.binormals;
  27313. // helper variables
  27314. const vertex = new Vector3();
  27315. const normal = new Vector3();
  27316. const uv = new Vector2();
  27317. let P = new Vector3();
  27318. // buffer
  27319. const vertices = [];
  27320. const normals = [];
  27321. const uvs = [];
  27322. const indices = [];
  27323. // create buffer data
  27324. generateBufferData();
  27325. // build geometry
  27326. this.setIndex( indices );
  27327. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27328. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27329. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27330. // functions
  27331. function generateBufferData() {
  27332. for ( let i = 0; i < tubularSegments; i ++ ) {
  27333. generateSegment( i );
  27334. }
  27335. // if the geometry is not closed, generate the last row of vertices and normals
  27336. // at the regular position on the given path
  27337. //
  27338. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  27339. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  27340. // uvs are generated in a separate function.
  27341. // this makes it easy compute correct values for closed geometries
  27342. generateUVs();
  27343. // finally create faces
  27344. generateIndices();
  27345. }
  27346. function generateSegment( i ) {
  27347. // we use getPointAt to sample evenly distributed points from the given path
  27348. P = path.getPointAt( i / tubularSegments, P );
  27349. // retrieve corresponding normal and binormal
  27350. const N = frames.normals[ i ];
  27351. const B = frames.binormals[ i ];
  27352. // generate normals and vertices for the current segment
  27353. for ( let j = 0; j <= radialSegments; j ++ ) {
  27354. const v = j / radialSegments * Math.PI * 2;
  27355. const sin = Math.sin( v );
  27356. const cos = - Math.cos( v );
  27357. // normal
  27358. normal.x = ( cos * N.x + sin * B.x );
  27359. normal.y = ( cos * N.y + sin * B.y );
  27360. normal.z = ( cos * N.z + sin * B.z );
  27361. normal.normalize();
  27362. normals.push( normal.x, normal.y, normal.z );
  27363. // vertex
  27364. vertex.x = P.x + radius * normal.x;
  27365. vertex.y = P.y + radius * normal.y;
  27366. vertex.z = P.z + radius * normal.z;
  27367. vertices.push( vertex.x, vertex.y, vertex.z );
  27368. }
  27369. }
  27370. function generateIndices() {
  27371. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27372. for ( let i = 1; i <= radialSegments; i ++ ) {
  27373. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27374. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27375. const c = ( radialSegments + 1 ) * j + i;
  27376. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27377. // faces
  27378. indices.push( a, b, d );
  27379. indices.push( b, c, d );
  27380. }
  27381. }
  27382. }
  27383. function generateUVs() {
  27384. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27385. for ( let j = 0; j <= radialSegments; j ++ ) {
  27386. uv.x = i / tubularSegments;
  27387. uv.y = j / radialSegments;
  27388. uvs.push( uv.x, uv.y );
  27389. }
  27390. }
  27391. }
  27392. }
  27393. copy( source ) {
  27394. super.copy( source );
  27395. this.parameters = Object.assign( {}, source.parameters );
  27396. return this;
  27397. }
  27398. toJSON() {
  27399. const data = super.toJSON();
  27400. data.path = this.parameters.path.toJSON();
  27401. return data;
  27402. }
  27403. /**
  27404. * Factory method for creating an instance of this class from the given
  27405. * JSON object.
  27406. *
  27407. * @param {Object} data - A JSON object representing the serialized geometry.
  27408. * @return {TubeGeometry} A new instance.
  27409. */
  27410. static fromJSON( data ) {
  27411. // This only works for built-in curves (e.g. CatmullRomCurve3).
  27412. // User defined curves or instances of CurvePath will not be deserialized.
  27413. return new TubeGeometry(
  27414. new Curves[ data.path.type ]().fromJSON( data.path ),
  27415. data.tubularSegments,
  27416. data.radius,
  27417. data.radialSegments,
  27418. data.closed
  27419. );
  27420. }
  27421. }
  27422. /**
  27423. * Can be used as a helper object to visualize a geometry as a wireframe.
  27424. *
  27425. * ```js
  27426. * const geometry = new THREE.SphereGeometry();
  27427. *
  27428. * const wireframe = new THREE.WireframeGeometry( geometry );
  27429. *
  27430. * const line = new THREE.LineSegments( wireframe );
  27431. * line.material.depthWrite = false;
  27432. * line.material.opacity = 0.25;
  27433. * line.material.transparent = true;
  27434. *
  27435. * scene.add( line );
  27436. * ```
  27437. *
  27438. * Note: It is not yet possible to serialize/deserialize instances of this class.
  27439. *
  27440. * @augments BufferGeometry
  27441. */
  27442. class WireframeGeometry extends BufferGeometry {
  27443. /**
  27444. * Constructs a new wireframe geometry.
  27445. *
  27446. * @param {?BufferGeometry} [geometry=null] - The geometry.
  27447. */
  27448. constructor( geometry = null ) {
  27449. super();
  27450. this.type = 'WireframeGeometry';
  27451. /**
  27452. * Holds the constructor parameters that have been
  27453. * used to generate the geometry. Any modification
  27454. * after instantiation does not change the geometry.
  27455. *
  27456. * @type {Object}
  27457. */
  27458. this.parameters = {
  27459. geometry: geometry
  27460. };
  27461. if ( geometry !== null ) {
  27462. // buffer
  27463. const vertices = [];
  27464. const edges = new Set();
  27465. // helper variables
  27466. const start = new Vector3();
  27467. const end = new Vector3();
  27468. if ( geometry.index !== null ) {
  27469. // indexed BufferGeometry
  27470. const position = geometry.attributes.position;
  27471. const indices = geometry.index;
  27472. let groups = geometry.groups;
  27473. if ( groups.length === 0 ) {
  27474. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  27475. }
  27476. // create a data structure that contains all edges without duplicates
  27477. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  27478. const group = groups[ o ];
  27479. const groupStart = group.start;
  27480. const groupCount = group.count;
  27481. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  27482. for ( let j = 0; j < 3; j ++ ) {
  27483. const index1 = indices.getX( i + j );
  27484. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  27485. start.fromBufferAttribute( position, index1 );
  27486. end.fromBufferAttribute( position, index2 );
  27487. if ( isUniqueEdge( start, end, edges ) === true ) {
  27488. vertices.push( start.x, start.y, start.z );
  27489. vertices.push( end.x, end.y, end.z );
  27490. }
  27491. }
  27492. }
  27493. }
  27494. } else {
  27495. // non-indexed BufferGeometry
  27496. const position = geometry.attributes.position;
  27497. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  27498. for ( let j = 0; j < 3; j ++ ) {
  27499. // three edges per triangle, an edge is represented as (index1, index2)
  27500. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  27501. const index1 = 3 * i + j;
  27502. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  27503. start.fromBufferAttribute( position, index1 );
  27504. end.fromBufferAttribute( position, index2 );
  27505. if ( isUniqueEdge( start, end, edges ) === true ) {
  27506. vertices.push( start.x, start.y, start.z );
  27507. vertices.push( end.x, end.y, end.z );
  27508. }
  27509. }
  27510. }
  27511. }
  27512. // build geometry
  27513. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27514. }
  27515. }
  27516. copy( source ) {
  27517. super.copy( source );
  27518. this.parameters = Object.assign( {}, source.parameters );
  27519. return this;
  27520. }
  27521. }
  27522. function isUniqueEdge( start, end, edges ) {
  27523. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  27524. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  27525. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  27526. return false;
  27527. } else {
  27528. edges.add( hash1 );
  27529. edges.add( hash2 );
  27530. return true;
  27531. }
  27532. }
  27533. var Geometries = /*#__PURE__*/Object.freeze({
  27534. __proto__: null,
  27535. BoxGeometry: BoxGeometry,
  27536. CapsuleGeometry: CapsuleGeometry,
  27537. CircleGeometry: CircleGeometry,
  27538. ConeGeometry: ConeGeometry,
  27539. CylinderGeometry: CylinderGeometry,
  27540. DodecahedronGeometry: DodecahedronGeometry,
  27541. EdgesGeometry: EdgesGeometry,
  27542. ExtrudeGeometry: ExtrudeGeometry,
  27543. IcosahedronGeometry: IcosahedronGeometry,
  27544. LatheGeometry: LatheGeometry,
  27545. OctahedronGeometry: OctahedronGeometry,
  27546. PlaneGeometry: PlaneGeometry,
  27547. PolyhedronGeometry: PolyhedronGeometry,
  27548. RingGeometry: RingGeometry,
  27549. ShapeGeometry: ShapeGeometry,
  27550. SphereGeometry: SphereGeometry,
  27551. TetrahedronGeometry: TetrahedronGeometry,
  27552. TorusGeometry: TorusGeometry,
  27553. TorusKnotGeometry: TorusKnotGeometry,
  27554. TubeGeometry: TubeGeometry,
  27555. WireframeGeometry: WireframeGeometry
  27556. });
  27557. /**
  27558. * This material can receive shadows, but otherwise is completely transparent.
  27559. *
  27560. * ```js
  27561. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  27562. * geometry.rotateX( - Math.PI / 2 );
  27563. *
  27564. * const material = new THREE.ShadowMaterial();
  27565. * material.opacity = 0.2;
  27566. *
  27567. * const plane = new THREE.Mesh( geometry, material );
  27568. * plane.position.y = -200;
  27569. * plane.receiveShadow = true;
  27570. * scene.add( plane );
  27571. * ```
  27572. *
  27573. * @augments Material
  27574. */
  27575. class ShadowMaterial extends Material {
  27576. /**
  27577. * Constructs a new shadow material.
  27578. *
  27579. * @param {Object} [parameters] - An object with one or more properties
  27580. * defining the material's appearance. Any property of the material
  27581. * (including any property from inherited materials) can be passed
  27582. * in here. Color values can be passed any type of value accepted
  27583. * by {@link Color#set}.
  27584. */
  27585. constructor( parameters ) {
  27586. super();
  27587. /**
  27588. * This flag can be used for type testing.
  27589. *
  27590. * @type {boolean}
  27591. * @readonly
  27592. * @default true
  27593. */
  27594. this.isShadowMaterial = true;
  27595. this.type = 'ShadowMaterial';
  27596. /**
  27597. * Color of the material.
  27598. *
  27599. * @type {Color}
  27600. * @default (0,0,0)
  27601. */
  27602. this.color = new Color( 0x000000 );
  27603. /**
  27604. * Overwritten since shadow materials are transparent
  27605. * by default.
  27606. *
  27607. * @type {boolean}
  27608. * @default true
  27609. */
  27610. this.transparent = true;
  27611. /**
  27612. * Whether the material is affected by fog or not.
  27613. *
  27614. * @type {boolean}
  27615. * @default true
  27616. */
  27617. this.fog = true;
  27618. this.setValues( parameters );
  27619. }
  27620. copy( source ) {
  27621. super.copy( source );
  27622. this.color.copy( source.color );
  27623. this.fog = source.fog;
  27624. return this;
  27625. }
  27626. }
  27627. /**
  27628. * This class works just like {@link ShaderMaterial}, except that definitions
  27629. * of built-in uniforms and attributes are not automatically prepended to the
  27630. * GLSL shader code.
  27631. *
  27632. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  27633. *
  27634. * @augments ShaderMaterial
  27635. */
  27636. class RawShaderMaterial extends ShaderMaterial {
  27637. /**
  27638. * Constructs a new raw shader material.
  27639. *
  27640. * @param {Object} [parameters] - An object with one or more properties
  27641. * defining the material's appearance. Any property of the material
  27642. * (including any property from inherited materials) can be passed
  27643. * in here. Color values can be passed any type of value accepted
  27644. * by {@link Color#set}.
  27645. */
  27646. constructor( parameters ) {
  27647. super( parameters );
  27648. /**
  27649. * This flag can be used for type testing.
  27650. *
  27651. * @type {boolean}
  27652. * @readonly
  27653. * @default true
  27654. */
  27655. this.isRawShaderMaterial = true;
  27656. this.type = 'RawShaderMaterial';
  27657. }
  27658. }
  27659. /**
  27660. * A standard physically based material, using Metallic-Roughness workflow.
  27661. *
  27662. * Physically based rendering (PBR) has recently become the standard in many
  27663. * 3D applications, such as [Unity]{@link https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/},
  27664. * [Unreal]{@link https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/} and
  27665. * [3D Studio Max]{@link http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017}.
  27666. *
  27667. * This approach differs from older approaches in that instead of using
  27668. * approximations for the way in which light interacts with a surface, a
  27669. * physically correct model is used. The idea is that, instead of tweaking
  27670. * materials to look good under specific lighting, a material can be created
  27671. * that will react 'correctly' under all lighting scenarios.
  27672. *
  27673. * In practice this gives a more accurate and realistic looking result than
  27674. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  27675. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  27676. * shading.
  27677. *
  27678. * Note that for best results you should always specify an environment map when using this material.
  27679. *
  27680. * For a non-technical introduction to the concept of PBR and how to set up a
  27681. * PBR material, check out these articles by the people at [marmoset]{@link https://www.marmoset.co}:
  27682. *
  27683. * - [Basic Theory of Physically Based Rendering]{@link https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/}
  27684. * - [Physically Based Rendering and You Can Too]{@link https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/}
  27685. *
  27686. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  27687. * [paper from Disney]{@link https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf}
  27688. * (pdf), by Brent Burley.
  27689. *
  27690. * @augments Material
  27691. */
  27692. class MeshStandardMaterial extends Material {
  27693. /**
  27694. * Constructs a new mesh standard material.
  27695. *
  27696. * @param {Object} [parameters] - An object with one or more properties
  27697. * defining the material's appearance. Any property of the material
  27698. * (including any property from inherited materials) can be passed
  27699. * in here. Color values can be passed any type of value accepted
  27700. * by {@link Color#set}.
  27701. */
  27702. constructor( parameters ) {
  27703. super();
  27704. /**
  27705. * This flag can be used for type testing.
  27706. *
  27707. * @type {boolean}
  27708. * @readonly
  27709. * @default true
  27710. */
  27711. this.isMeshStandardMaterial = true;
  27712. this.type = 'MeshStandardMaterial';
  27713. this.defines = { 'STANDARD': '' };
  27714. /**
  27715. * Color of the material.
  27716. *
  27717. * @type {Color}
  27718. * @default (1,1,1)
  27719. */
  27720. this.color = new Color( 0xffffff ); // diffuse
  27721. /**
  27722. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  27723. * means fully diffuse. If `roughnessMap` is also provided,
  27724. * both values are multiplied.
  27725. *
  27726. * @type {number}
  27727. * @default 1
  27728. */
  27729. this.roughness = 1.0;
  27730. /**
  27731. * How much the material is like a metal. Non-metallic materials such as wood
  27732. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  27733. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  27734. * If `metalnessMap` is also provided, both values are multiplied.
  27735. *
  27736. * @type {number}
  27737. * @default 0
  27738. */
  27739. this.metalness = 0.0;
  27740. /**
  27741. * The color map. May optionally include an alpha channel, typically combined
  27742. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27743. * color is modulated by the diffuse `color`.
  27744. *
  27745. * @type {?Texture}
  27746. * @default null
  27747. */
  27748. this.map = null;
  27749. /**
  27750. * The light map. Requires a second set of UVs.
  27751. *
  27752. * @type {?Texture}
  27753. * @default null
  27754. */
  27755. this.lightMap = null;
  27756. /**
  27757. * Intensity of the baked light.
  27758. *
  27759. * @type {number}
  27760. * @default 1
  27761. */
  27762. this.lightMapIntensity = 1.0;
  27763. /**
  27764. * The red channel of this texture is used as the ambient occlusion map.
  27765. * Requires a second set of UVs.
  27766. *
  27767. * @type {?Texture}
  27768. * @default null
  27769. */
  27770. this.aoMap = null;
  27771. /**
  27772. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  27773. * disables ambient occlusion. Where intensity is `1` and the AO map's
  27774. * red channel is also `1`, ambient light is fully occluded on a surface.
  27775. *
  27776. * @type {number}
  27777. * @default 1
  27778. */
  27779. this.aoMapIntensity = 1.0;
  27780. /**
  27781. * Emissive (light) color of the material, essentially a solid color
  27782. * unaffected by other lighting.
  27783. *
  27784. * @type {Color}
  27785. * @default (0,0,0)
  27786. */
  27787. this.emissive = new Color( 0x000000 );
  27788. /**
  27789. * Intensity of the emissive light. Modulates the emissive color.
  27790. *
  27791. * @type {number}
  27792. * @default 1
  27793. */
  27794. this.emissiveIntensity = 1.0;
  27795. /**
  27796. * Set emissive (glow) map. The emissive map color is modulated by the
  27797. * emissive color and the emissive intensity. If you have an emissive map,
  27798. * be sure to set the emissive color to something other than black.
  27799. *
  27800. * @type {?Texture}
  27801. * @default null
  27802. */
  27803. this.emissiveMap = null;
  27804. /**
  27805. * The texture to create a bump map. The black and white values map to the
  27806. * perceived depth in relation to the lights. Bump doesn't actually affect
  27807. * the geometry of the object, only the lighting. If a normal map is defined
  27808. * this will be ignored.
  27809. *
  27810. * @type {?Texture}
  27811. * @default null
  27812. */
  27813. this.bumpMap = null;
  27814. /**
  27815. * How much the bump map affects the material. Typical range is `[0,1]`.
  27816. *
  27817. * @type {number}
  27818. * @default 1
  27819. */
  27820. this.bumpScale = 1;
  27821. /**
  27822. * The texture to create a normal map. The RGB values affect the surface
  27823. * normal for each pixel fragment and change the way the color is lit. Normal
  27824. * maps do not change the actual shape of the surface, only the lighting. In
  27825. * case the material has a normal map authored using the left handed
  27826. * convention, the `y` component of `normalScale` should be negated to compensate
  27827. * for the different handedness.
  27828. *
  27829. * @type {?Texture}
  27830. * @default null
  27831. */
  27832. this.normalMap = null;
  27833. /**
  27834. * The type of normal map.
  27835. *
  27836. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  27837. * @default TangentSpaceNormalMap
  27838. */
  27839. this.normalMapType = TangentSpaceNormalMap;
  27840. /**
  27841. * How much the normal map affects the material. Typical value range is `[0,1]`.
  27842. *
  27843. * @type {Vector2}
  27844. * @default (1,1)
  27845. */
  27846. this.normalScale = new Vector2( 1, 1 );
  27847. /**
  27848. * The displacement map affects the position of the mesh's vertices. Unlike
  27849. * other maps which only affect the light and shade of the material the
  27850. * displaced vertices can cast shadows, block other objects, and otherwise
  27851. * act as real geometry. The displacement texture is an image where the value
  27852. * of each pixel (white being the highest) is mapped against, and
  27853. * repositions, the vertices of the mesh.
  27854. *
  27855. * @type {?Texture}
  27856. * @default null
  27857. */
  27858. this.displacementMap = null;
  27859. /**
  27860. * How much the displacement map affects the mesh (where black is no
  27861. * displacement, and white is maximum displacement). Without a displacement
  27862. * map set, this value is not applied.
  27863. *
  27864. * @type {number}
  27865. * @default 0
  27866. */
  27867. this.displacementScale = 1;
  27868. /**
  27869. * The offset of the displacement map's values on the mesh's vertices.
  27870. * The bias is added to the scaled sample of the displacement map.
  27871. * Without a displacement map set, this value is not applied.
  27872. *
  27873. * @type {number}
  27874. * @default 0
  27875. */
  27876. this.displacementBias = 0;
  27877. /**
  27878. * The green channel of this texture is used to alter the roughness of the
  27879. * material.
  27880. *
  27881. * @type {?Texture}
  27882. * @default null
  27883. */
  27884. this.roughnessMap = null;
  27885. /**
  27886. * The blue channel of this texture is used to alter the metalness of the
  27887. * material.
  27888. *
  27889. * @type {?Texture}
  27890. * @default null
  27891. */
  27892. this.metalnessMap = null;
  27893. /**
  27894. * The alpha map is a grayscale texture that controls the opacity across the
  27895. * surface (black: fully transparent; white: fully opaque).
  27896. *
  27897. * Only the color of the texture is used, ignoring the alpha channel if one
  27898. * exists. For RGB and RGBA textures, the renderer will use the green channel
  27899. * when sampling this texture due to the extra bit of precision provided for
  27900. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  27901. * luminance/alpha textures will also still work as expected.
  27902. *
  27903. * @type {?Texture}
  27904. * @default null
  27905. */
  27906. this.alphaMap = null;
  27907. /**
  27908. * The environment map. To ensure a physically correct rendering, environment maps
  27909. * are internally pre-processed with {@link PMREMGenerator}.
  27910. *
  27911. * @type {?Texture}
  27912. * @default null
  27913. */
  27914. this.envMap = null;
  27915. /**
  27916. * The rotation of the environment map in radians.
  27917. *
  27918. * @type {Euler}
  27919. * @default (0,0,0)
  27920. */
  27921. this.envMapRotation = new Euler();
  27922. /**
  27923. * Scales the effect of the environment map by multiplying its color.
  27924. *
  27925. * @type {number}
  27926. * @default 1
  27927. */
  27928. this.envMapIntensity = 1.0;
  27929. /**
  27930. * Renders the geometry as a wireframe.
  27931. *
  27932. * @type {boolean}
  27933. * @default false
  27934. */
  27935. this.wireframe = false;
  27936. /**
  27937. * Controls the thickness of the wireframe.
  27938. *
  27939. * Can only be used with {@link SVGRenderer}.
  27940. *
  27941. * @type {number}
  27942. * @default 1
  27943. */
  27944. this.wireframeLinewidth = 1;
  27945. /**
  27946. * Defines appearance of wireframe ends.
  27947. *
  27948. * Can only be used with {@link SVGRenderer}.
  27949. *
  27950. * @type {('round'|'bevel'|'miter')}
  27951. * @default 'round'
  27952. */
  27953. this.wireframeLinecap = 'round';
  27954. /**
  27955. * Defines appearance of wireframe joints.
  27956. *
  27957. * Can only be used with {@link SVGRenderer}.
  27958. *
  27959. * @type {('round'|'bevel'|'miter')}
  27960. * @default 'round'
  27961. */
  27962. this.wireframeLinejoin = 'round';
  27963. /**
  27964. * Whether the material is rendered with flat shading or not.
  27965. *
  27966. * @type {boolean}
  27967. * @default false
  27968. */
  27969. this.flatShading = false;
  27970. /**
  27971. * Whether the material is affected by fog or not.
  27972. *
  27973. * @type {boolean}
  27974. * @default true
  27975. */
  27976. this.fog = true;
  27977. this.setValues( parameters );
  27978. }
  27979. copy( source ) {
  27980. super.copy( source );
  27981. this.defines = { 'STANDARD': '' };
  27982. this.color.copy( source.color );
  27983. this.roughness = source.roughness;
  27984. this.metalness = source.metalness;
  27985. this.map = source.map;
  27986. this.lightMap = source.lightMap;
  27987. this.lightMapIntensity = source.lightMapIntensity;
  27988. this.aoMap = source.aoMap;
  27989. this.aoMapIntensity = source.aoMapIntensity;
  27990. this.emissive.copy( source.emissive );
  27991. this.emissiveMap = source.emissiveMap;
  27992. this.emissiveIntensity = source.emissiveIntensity;
  27993. this.bumpMap = source.bumpMap;
  27994. this.bumpScale = source.bumpScale;
  27995. this.normalMap = source.normalMap;
  27996. this.normalMapType = source.normalMapType;
  27997. this.normalScale.copy( source.normalScale );
  27998. this.displacementMap = source.displacementMap;
  27999. this.displacementScale = source.displacementScale;
  28000. this.displacementBias = source.displacementBias;
  28001. this.roughnessMap = source.roughnessMap;
  28002. this.metalnessMap = source.metalnessMap;
  28003. this.alphaMap = source.alphaMap;
  28004. this.envMap = source.envMap;
  28005. this.envMapRotation.copy( source.envMapRotation );
  28006. this.envMapIntensity = source.envMapIntensity;
  28007. this.wireframe = source.wireframe;
  28008. this.wireframeLinewidth = source.wireframeLinewidth;
  28009. this.wireframeLinecap = source.wireframeLinecap;
  28010. this.wireframeLinejoin = source.wireframeLinejoin;
  28011. this.flatShading = source.flatShading;
  28012. this.fog = source.fog;
  28013. return this;
  28014. }
  28015. }
  28016. /**
  28017. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  28018. * physically-based rendering properties:
  28019. *
  28020. * - Anisotropy: Ability to represent the anisotropic property of materials
  28021. * as observable with brushed metals.
  28022. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  28023. * a clear, reflective layer on top of another layer that may be irregular or rough.
  28024. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  28025. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  28026. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  28027. * wings of many insects.
  28028. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  28029. * transparent materials are less reflective. Physically-based transmission provides a more
  28030. * realistic option for thin, transparent surfaces like glass.
  28031. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  28032. * - Sheen: Can be used for representing cloth and fabric materials.
  28033. *
  28034. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  28035. * higher performance cost, per pixel, than other three.js materials. Most
  28036. * effects are disabled by default, and add cost as they are enabled. For
  28037. * best results, always specify an environment map when using this material.
  28038. *
  28039. * @augments MeshStandardMaterial
  28040. */
  28041. class MeshPhysicalMaterial extends MeshStandardMaterial {
  28042. /**
  28043. * Constructs a new mesh physical material.
  28044. *
  28045. * @param {Object} [parameters] - An object with one or more properties
  28046. * defining the material's appearance. Any property of the material
  28047. * (including any property from inherited materials) can be passed
  28048. * in here. Color values can be passed any type of value accepted
  28049. * by {@link Color#set}.
  28050. */
  28051. constructor( parameters ) {
  28052. super();
  28053. /**
  28054. * This flag can be used for type testing.
  28055. *
  28056. * @type {boolean}
  28057. * @readonly
  28058. * @default true
  28059. */
  28060. this.isMeshPhysicalMaterial = true;
  28061. this.defines = {
  28062. 'STANDARD': '',
  28063. 'PHYSICAL': ''
  28064. };
  28065. this.type = 'MeshPhysicalMaterial';
  28066. /**
  28067. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  28068. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  28069. * property provides additional rotation to the vectors in the texture.
  28070. *
  28071. * @type {number}
  28072. * @default 1
  28073. */
  28074. this.anisotropyRotation = 0;
  28075. /**
  28076. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  28077. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  28078. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  28079. *
  28080. * @type {?Texture}
  28081. * @default null
  28082. */
  28083. this.anisotropyMap = null;
  28084. /**
  28085. * The red channel of this texture is multiplied against `clearcoat`,
  28086. * for per-pixel control over a coating's intensity.
  28087. *
  28088. * @type {?Texture}
  28089. * @default null
  28090. */
  28091. this.clearcoatMap = null;
  28092. /**
  28093. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  28094. *
  28095. * @type {number}
  28096. * @default 0
  28097. */
  28098. this.clearcoatRoughness = 0.0;
  28099. /**
  28100. * The green channel of this texture is multiplied against
  28101. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  28102. *
  28103. * @type {?Texture}
  28104. * @default null
  28105. */
  28106. this.clearcoatRoughnessMap = null;
  28107. /**
  28108. * How much `clearcoatNormalMap` affects the clear coat layer, from
  28109. * `(0,0)` to `(1,1)`.
  28110. *
  28111. * @type {Vector2}
  28112. * @default (1,1)
  28113. */
  28114. this.clearcoatNormalScale = new Vector2( 1, 1 );
  28115. /**
  28116. * Can be used to enable independent normals for the clear coat layer.
  28117. *
  28118. * @type {?Texture}
  28119. * @default null
  28120. */
  28121. this.clearcoatNormalMap = null;
  28122. /**
  28123. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  28124. *
  28125. * @type {number}
  28126. * @default 1.5
  28127. */
  28128. this.ior = 1.5;
  28129. /**
  28130. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  28131. * corresponds to an index-of-refraction of `1.5`.
  28132. *
  28133. * This models the reflectivity of non-metallic materials. It has no effect
  28134. * when `metalness` is `1.0`
  28135. *
  28136. * @name MeshPhysicalMaterial#reflectivity
  28137. * @type {number}
  28138. * @default 0.5
  28139. */
  28140. Object.defineProperty( this, 'reflectivity', {
  28141. get: function () {
  28142. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  28143. },
  28144. set: function ( reflectivity ) {
  28145. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  28146. }
  28147. } );
  28148. /**
  28149. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  28150. * control over iridescence.
  28151. *
  28152. * @type {?Texture}
  28153. * @default null
  28154. */
  28155. this.iridescenceMap = null;
  28156. /**
  28157. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  28158. * Between `1.0` to `2.333`.
  28159. *
  28160. * @type {number}
  28161. * @default 1.3
  28162. */
  28163. this.iridescenceIOR = 1.3;
  28164. /**
  28165. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  28166. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  28167. *
  28168. * @type {Array<number,number>}
  28169. * @default [100,400]
  28170. */
  28171. this.iridescenceThicknessRange = [ 100, 400 ];
  28172. /**
  28173. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  28174. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  28175. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  28176. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  28177. * - Values in-between will linearly interpolate between the elements of the array.
  28178. *
  28179. * @type {?Texture}
  28180. * @default null
  28181. */
  28182. this.iridescenceThicknessMap = null;
  28183. /**
  28184. * The sheen tint.
  28185. *
  28186. * @type {Color}
  28187. * @default (0,0,0)
  28188. */
  28189. this.sheenColor = new Color( 0x000000 );
  28190. /**
  28191. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  28192. * over sheen tint.
  28193. *
  28194. * @type {?Texture}
  28195. * @default null
  28196. */
  28197. this.sheenColorMap = null;
  28198. /**
  28199. * Roughness of the sheen layer, from `0.0` to `1.0`.
  28200. *
  28201. * @type {number}
  28202. * @default 1
  28203. */
  28204. this.sheenRoughness = 1.0;
  28205. /**
  28206. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28207. * over sheen roughness.
  28208. *
  28209. * @type {?Texture}
  28210. * @default null
  28211. */
  28212. this.sheenRoughnessMap = null;
  28213. /**
  28214. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28215. * optical transparency.
  28216. *
  28217. * @type {?Texture}
  28218. * @default null
  28219. */
  28220. this.transmissionMap = null;
  28221. /**
  28222. * The thickness of the volume beneath the surface. The value is given in the
  28223. * coordinate space of the mesh. If the value is `0` the material is
  28224. * thin-walled. Otherwise the material is a volume boundary.
  28225. *
  28226. * @type {number}
  28227. * @default 0
  28228. */
  28229. this.thickness = 0;
  28230. /**
  28231. * A texture that defines the thickness, stored in the green channel. This will
  28232. * be multiplied by `thickness`.
  28233. *
  28234. * @type {?Texture}
  28235. * @default null
  28236. */
  28237. this.thicknessMap = null;
  28238. /**
  28239. * Density of the medium given as the average distance that light travels in
  28240. * the medium before interacting with a particle. The value is given in world
  28241. * space units, and must be greater than zero.
  28242. *
  28243. * @type {number}
  28244. * @default Infinity
  28245. */
  28246. this.attenuationDistance = Infinity;
  28247. /**
  28248. * The color that white light turns into due to absorption when reaching the
  28249. * attenuation distance.
  28250. *
  28251. * @type {Color}
  28252. * @default (1,1,1)
  28253. */
  28254. this.attenuationColor = new Color( 1, 1, 1 );
  28255. /**
  28256. * A float that scales the amount of specular reflection for non-metals only.
  28257. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28258. *
  28259. * @type {number}
  28260. * @default 1
  28261. */
  28262. this.specularIntensity = 1.0;
  28263. /**
  28264. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28265. * for per-pixel control over specular intensity.
  28266. *
  28267. * @type {?Texture}
  28268. * @default null
  28269. */
  28270. this.specularIntensityMap = null;
  28271. /**
  28272. * Tints the specular reflection at normal incidence for non-metals only.
  28273. *
  28274. * @type {Color}
  28275. * @default (1,1,1)
  28276. */
  28277. this.specularColor = new Color( 1, 1, 1 );
  28278. /**
  28279. * The RGB channels of this texture are multiplied against `specularColor`,
  28280. * for per-pixel control over specular color.
  28281. *
  28282. * @type {?Texture}
  28283. * @default null
  28284. */
  28285. this.specularColorMap = null;
  28286. this._anisotropy = 0;
  28287. this._clearcoat = 0;
  28288. this._dispersion = 0;
  28289. this._iridescence = 0;
  28290. this._sheen = 0.0;
  28291. this._transmission = 0;
  28292. this.setValues( parameters );
  28293. }
  28294. /**
  28295. * The anisotropy strength.
  28296. *
  28297. * @type {number}
  28298. * @default 0
  28299. */
  28300. get anisotropy() {
  28301. return this._anisotropy;
  28302. }
  28303. set anisotropy( value ) {
  28304. if ( this._anisotropy > 0 !== value > 0 ) {
  28305. this.version ++;
  28306. }
  28307. this._anisotropy = value;
  28308. }
  28309. /**
  28310. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28311. * clear coat related properties to enable multilayer materials that have a
  28312. * thin translucent layer over the base layer.
  28313. *
  28314. * @type {number}
  28315. * @default 0
  28316. */
  28317. get clearcoat() {
  28318. return this._clearcoat;
  28319. }
  28320. set clearcoat( value ) {
  28321. if ( this._clearcoat > 0 !== value > 0 ) {
  28322. this.version ++;
  28323. }
  28324. this._clearcoat = value;
  28325. }
  28326. /**
  28327. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28328. * the surface and the viewer, from `0.0` to `1.0`.
  28329. *
  28330. * @type {number}
  28331. * @default 0
  28332. */
  28333. get iridescence() {
  28334. return this._iridescence;
  28335. }
  28336. set iridescence( value ) {
  28337. if ( this._iridescence > 0 !== value > 0 ) {
  28338. this.version ++;
  28339. }
  28340. this._iridescence = value;
  28341. }
  28342. /**
  28343. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28344. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28345. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28346. *
  28347. * @type {number}
  28348. * @default 0
  28349. */
  28350. get dispersion() {
  28351. return this._dispersion;
  28352. }
  28353. set dispersion( value ) {
  28354. if ( this._dispersion > 0 !== value > 0 ) {
  28355. this.version ++;
  28356. }
  28357. this._dispersion = value;
  28358. }
  28359. /**
  28360. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28361. *
  28362. * @type {number}
  28363. * @default 0
  28364. */
  28365. get sheen() {
  28366. return this._sheen;
  28367. }
  28368. set sheen( value ) {
  28369. if ( this._sheen > 0 !== value > 0 ) {
  28370. this.version ++;
  28371. }
  28372. this._sheen = value;
  28373. }
  28374. /**
  28375. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28376. *
  28377. * Thin, transparent or semitransparent, plastic or glass materials remain
  28378. * largely reflective even if they are fully transmissive. The transmission
  28379. * property can be used to model these materials.
  28380. *
  28381. * When transmission is non-zero, `opacity` should be set to `1`.
  28382. *
  28383. * @type {number}
  28384. * @default 0
  28385. */
  28386. get transmission() {
  28387. return this._transmission;
  28388. }
  28389. set transmission( value ) {
  28390. if ( this._transmission > 0 !== value > 0 ) {
  28391. this.version ++;
  28392. }
  28393. this._transmission = value;
  28394. }
  28395. copy( source ) {
  28396. super.copy( source );
  28397. this.defines = {
  28398. 'STANDARD': '',
  28399. 'PHYSICAL': ''
  28400. };
  28401. this.anisotropy = source.anisotropy;
  28402. this.anisotropyRotation = source.anisotropyRotation;
  28403. this.anisotropyMap = source.anisotropyMap;
  28404. this.clearcoat = source.clearcoat;
  28405. this.clearcoatMap = source.clearcoatMap;
  28406. this.clearcoatRoughness = source.clearcoatRoughness;
  28407. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28408. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28409. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28410. this.dispersion = source.dispersion;
  28411. this.ior = source.ior;
  28412. this.iridescence = source.iridescence;
  28413. this.iridescenceMap = source.iridescenceMap;
  28414. this.iridescenceIOR = source.iridescenceIOR;
  28415. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28416. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28417. this.sheen = source.sheen;
  28418. this.sheenColor.copy( source.sheenColor );
  28419. this.sheenColorMap = source.sheenColorMap;
  28420. this.sheenRoughness = source.sheenRoughness;
  28421. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28422. this.transmission = source.transmission;
  28423. this.transmissionMap = source.transmissionMap;
  28424. this.thickness = source.thickness;
  28425. this.thicknessMap = source.thicknessMap;
  28426. this.attenuationDistance = source.attenuationDistance;
  28427. this.attenuationColor.copy( source.attenuationColor );
  28428. this.specularIntensity = source.specularIntensity;
  28429. this.specularIntensityMap = source.specularIntensityMap;
  28430. this.specularColor.copy( source.specularColor );
  28431. this.specularColorMap = source.specularColorMap;
  28432. return this;
  28433. }
  28434. }
  28435. /**
  28436. * A material for shiny surfaces with specular highlights.
  28437. *
  28438. * The material uses a non-physically based [Blinn-Phong]{@link https://en.wikipedia.org/wiki/Blinn-Phong_shading_model}
  28439. * model for calculating reflectance. Unlike the Lambertian model used in the
  28440. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28441. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28442. *
  28443. * Performance will generally be greater when using this material over the
  28444. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28445. * some graphical accuracy.
  28446. *
  28447. * @augments Material
  28448. */
  28449. class MeshPhongMaterial extends Material {
  28450. /**
  28451. * Constructs a new mesh phong material.
  28452. *
  28453. * @param {Object} [parameters] - An object with one or more properties
  28454. * defining the material's appearance. Any property of the material
  28455. * (including any property from inherited materials) can be passed
  28456. * in here. Color values can be passed any type of value accepted
  28457. * by {@link Color#set}.
  28458. */
  28459. constructor( parameters ) {
  28460. super();
  28461. /**
  28462. * This flag can be used for type testing.
  28463. *
  28464. * @type {boolean}
  28465. * @readonly
  28466. * @default true
  28467. */
  28468. this.isMeshPhongMaterial = true;
  28469. this.type = 'MeshPhongMaterial';
  28470. /**
  28471. * Color of the material.
  28472. *
  28473. * @type {Color}
  28474. * @default (1,1,1)
  28475. */
  28476. this.color = new Color( 0xffffff ); // diffuse
  28477. /**
  28478. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28479. *
  28480. * This defines how shiny the material is and the color of its shine.
  28481. *
  28482. * @type {Color}
  28483. */
  28484. this.specular = new Color( 0x111111 );
  28485. /**
  28486. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28487. *
  28488. * @type {number}
  28489. * @default 30
  28490. */
  28491. this.shininess = 30;
  28492. /**
  28493. * The color map. May optionally include an alpha channel, typically combined
  28494. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28495. * color is modulated by the diffuse `color`.
  28496. *
  28497. * @type {?Texture}
  28498. * @default null
  28499. */
  28500. this.map = null;
  28501. /**
  28502. * The light map. Requires a second set of UVs.
  28503. *
  28504. * @type {?Texture}
  28505. * @default null
  28506. */
  28507. this.lightMap = null;
  28508. /**
  28509. * Intensity of the baked light.
  28510. *
  28511. * @type {number}
  28512. * @default 1
  28513. */
  28514. this.lightMapIntensity = 1.0;
  28515. /**
  28516. * The red channel of this texture is used as the ambient occlusion map.
  28517. * Requires a second set of UVs.
  28518. *
  28519. * @type {?Texture}
  28520. * @default null
  28521. */
  28522. this.aoMap = null;
  28523. /**
  28524. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28525. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28526. * red channel is also `1`, ambient light is fully occluded on a surface.
  28527. *
  28528. * @type {number}
  28529. * @default 1
  28530. */
  28531. this.aoMapIntensity = 1.0;
  28532. /**
  28533. * Emissive (light) color of the material, essentially a solid color
  28534. * unaffected by other lighting.
  28535. *
  28536. * @type {Color}
  28537. * @default (0,0,0)
  28538. */
  28539. this.emissive = new Color( 0x000000 );
  28540. /**
  28541. * Intensity of the emissive light. Modulates the emissive color.
  28542. *
  28543. * @type {number}
  28544. * @default 1
  28545. */
  28546. this.emissiveIntensity = 1.0;
  28547. /**
  28548. * Set emissive (glow) map. The emissive map color is modulated by the
  28549. * emissive color and the emissive intensity. If you have an emissive map,
  28550. * be sure to set the emissive color to something other than black.
  28551. *
  28552. * @type {?Texture}
  28553. * @default null
  28554. */
  28555. this.emissiveMap = null;
  28556. /**
  28557. * The texture to create a bump map. The black and white values map to the
  28558. * perceived depth in relation to the lights. Bump doesn't actually affect
  28559. * the geometry of the object, only the lighting. If a normal map is defined
  28560. * this will be ignored.
  28561. *
  28562. * @type {?Texture}
  28563. * @default null
  28564. */
  28565. this.bumpMap = null;
  28566. /**
  28567. * How much the bump map affects the material. Typical range is `[0,1]`.
  28568. *
  28569. * @type {number}
  28570. * @default 1
  28571. */
  28572. this.bumpScale = 1;
  28573. /**
  28574. * The texture to create a normal map. The RGB values affect the surface
  28575. * normal for each pixel fragment and change the way the color is lit. Normal
  28576. * maps do not change the actual shape of the surface, only the lighting. In
  28577. * case the material has a normal map authored using the left handed
  28578. * convention, the `y` component of `normalScale` should be negated to compensate
  28579. * for the different handedness.
  28580. *
  28581. * @type {?Texture}
  28582. * @default null
  28583. */
  28584. this.normalMap = null;
  28585. /**
  28586. * The type of normal map.
  28587. *
  28588. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28589. * @default TangentSpaceNormalMap
  28590. */
  28591. this.normalMapType = TangentSpaceNormalMap;
  28592. /**
  28593. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28594. *
  28595. * @type {Vector2}
  28596. * @default (1,1)
  28597. */
  28598. this.normalScale = new Vector2( 1, 1 );
  28599. /**
  28600. * The displacement map affects the position of the mesh's vertices. Unlike
  28601. * other maps which only affect the light and shade of the material the
  28602. * displaced vertices can cast shadows, block other objects, and otherwise
  28603. * act as real geometry. The displacement texture is an image where the value
  28604. * of each pixel (white being the highest) is mapped against, and
  28605. * repositions, the vertices of the mesh.
  28606. *
  28607. * @type {?Texture}
  28608. * @default null
  28609. */
  28610. this.displacementMap = null;
  28611. /**
  28612. * How much the displacement map affects the mesh (where black is no
  28613. * displacement, and white is maximum displacement). Without a displacement
  28614. * map set, this value is not applied.
  28615. *
  28616. * @type {number}
  28617. * @default 0
  28618. */
  28619. this.displacementScale = 1;
  28620. /**
  28621. * The offset of the displacement map's values on the mesh's vertices.
  28622. * The bias is added to the scaled sample of the displacement map.
  28623. * Without a displacement map set, this value is not applied.
  28624. *
  28625. * @type {number}
  28626. * @default 0
  28627. */
  28628. this.displacementBias = 0;
  28629. /**
  28630. * The specular map value affects both how much the specular surface
  28631. * highlight contributes and how much of the environment map affects the
  28632. * surface.
  28633. *
  28634. * @type {?Texture}
  28635. * @default null
  28636. */
  28637. this.specularMap = null;
  28638. /**
  28639. * The alpha map is a grayscale texture that controls the opacity across the
  28640. * surface (black: fully transparent; white: fully opaque).
  28641. *
  28642. * Only the color of the texture is used, ignoring the alpha channel if one
  28643. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28644. * when sampling this texture due to the extra bit of precision provided for
  28645. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28646. * luminance/alpha textures will also still work as expected.
  28647. *
  28648. * @type {?Texture}
  28649. * @default null
  28650. */
  28651. this.alphaMap = null;
  28652. /**
  28653. * The environment map.
  28654. *
  28655. * @type {?Texture}
  28656. * @default null
  28657. */
  28658. this.envMap = null;
  28659. /**
  28660. * The rotation of the environment map in radians.
  28661. *
  28662. * @type {Euler}
  28663. * @default (0,0,0)
  28664. */
  28665. this.envMapRotation = new Euler();
  28666. /**
  28667. * How to combine the result of the surface's color with the environment map, if any.
  28668. *
  28669. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  28670. * blend between the two colors.
  28671. *
  28672. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  28673. * @default MultiplyOperation
  28674. */
  28675. this.combine = MultiplyOperation;
  28676. /**
  28677. * How much the environment map affects the surface.
  28678. * The valid range is between `0` (no reflections) and `1` (full reflections).
  28679. *
  28680. * @type {number}
  28681. * @default 1
  28682. */
  28683. this.reflectivity = 1;
  28684. /**
  28685. * The index of refraction (IOR) of air (approximately 1) divided by the
  28686. * index of refraction of the material. It is used with environment mapping
  28687. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  28688. * The refraction ratio should not exceed `1`.
  28689. *
  28690. * @type {number}
  28691. * @default 0.98
  28692. */
  28693. this.refractionRatio = 0.98;
  28694. /**
  28695. * Renders the geometry as a wireframe.
  28696. *
  28697. * @type {boolean}
  28698. * @default false
  28699. */
  28700. this.wireframe = false;
  28701. /**
  28702. * Controls the thickness of the wireframe.
  28703. *
  28704. * Can only be used with {@link SVGRenderer}.
  28705. *
  28706. * @type {number}
  28707. * @default 1
  28708. */
  28709. this.wireframeLinewidth = 1;
  28710. /**
  28711. * Defines appearance of wireframe ends.
  28712. *
  28713. * Can only be used with {@link SVGRenderer}.
  28714. *
  28715. * @type {('round'|'bevel'|'miter')}
  28716. * @default 'round'
  28717. */
  28718. this.wireframeLinecap = 'round';
  28719. /**
  28720. * Defines appearance of wireframe joints.
  28721. *
  28722. * Can only be used with {@link SVGRenderer}.
  28723. *
  28724. * @type {('round'|'bevel'|'miter')}
  28725. * @default 'round'
  28726. */
  28727. this.wireframeLinejoin = 'round';
  28728. /**
  28729. * Whether the material is rendered with flat shading or not.
  28730. *
  28731. * @type {boolean}
  28732. * @default false
  28733. */
  28734. this.flatShading = false;
  28735. /**
  28736. * Whether the material is affected by fog or not.
  28737. *
  28738. * @type {boolean}
  28739. * @default true
  28740. */
  28741. this.fog = true;
  28742. this.setValues( parameters );
  28743. }
  28744. copy( source ) {
  28745. super.copy( source );
  28746. this.color.copy( source.color );
  28747. this.specular.copy( source.specular );
  28748. this.shininess = source.shininess;
  28749. this.map = source.map;
  28750. this.lightMap = source.lightMap;
  28751. this.lightMapIntensity = source.lightMapIntensity;
  28752. this.aoMap = source.aoMap;
  28753. this.aoMapIntensity = source.aoMapIntensity;
  28754. this.emissive.copy( source.emissive );
  28755. this.emissiveMap = source.emissiveMap;
  28756. this.emissiveIntensity = source.emissiveIntensity;
  28757. this.bumpMap = source.bumpMap;
  28758. this.bumpScale = source.bumpScale;
  28759. this.normalMap = source.normalMap;
  28760. this.normalMapType = source.normalMapType;
  28761. this.normalScale.copy( source.normalScale );
  28762. this.displacementMap = source.displacementMap;
  28763. this.displacementScale = source.displacementScale;
  28764. this.displacementBias = source.displacementBias;
  28765. this.specularMap = source.specularMap;
  28766. this.alphaMap = source.alphaMap;
  28767. this.envMap = source.envMap;
  28768. this.envMapRotation.copy( source.envMapRotation );
  28769. this.combine = source.combine;
  28770. this.reflectivity = source.reflectivity;
  28771. this.refractionRatio = source.refractionRatio;
  28772. this.wireframe = source.wireframe;
  28773. this.wireframeLinewidth = source.wireframeLinewidth;
  28774. this.wireframeLinecap = source.wireframeLinecap;
  28775. this.wireframeLinejoin = source.wireframeLinejoin;
  28776. this.flatShading = source.flatShading;
  28777. this.fog = source.fog;
  28778. return this;
  28779. }
  28780. }
  28781. /**
  28782. * A material implementing toon shading.
  28783. *
  28784. * @augments Material
  28785. */
  28786. class MeshToonMaterial extends Material {
  28787. /**
  28788. * Constructs a new mesh toon material.
  28789. *
  28790. * @param {Object} [parameters] - An object with one or more properties
  28791. * defining the material's appearance. Any property of the material
  28792. * (including any property from inherited materials) can be passed
  28793. * in here. Color values can be passed any type of value accepted
  28794. * by {@link Color#set}.
  28795. */
  28796. constructor( parameters ) {
  28797. super();
  28798. /**
  28799. * This flag can be used for type testing.
  28800. *
  28801. * @type {boolean}
  28802. * @readonly
  28803. * @default true
  28804. */
  28805. this.isMeshToonMaterial = true;
  28806. this.defines = { 'TOON': '' };
  28807. this.type = 'MeshToonMaterial';
  28808. /**
  28809. * Color of the material.
  28810. *
  28811. * @type {Color}
  28812. * @default (1,1,1)
  28813. */
  28814. this.color = new Color( 0xffffff );
  28815. /**
  28816. * The color map. May optionally include an alpha channel, typically combined
  28817. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28818. * color is modulated by the diffuse `color`.
  28819. *
  28820. * @type {?Texture}
  28821. * @default null
  28822. */
  28823. this.map = null;
  28824. /**
  28825. * Gradient map for toon shading. It's required to set
  28826. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@linkNearestFilter}
  28827. * when using this type of texture.
  28828. *
  28829. * @type {?Texture}
  28830. * @default null
  28831. */
  28832. this.gradientMap = null;
  28833. /**
  28834. * The light map. Requires a second set of UVs.
  28835. *
  28836. * @type {?Texture}
  28837. * @default null
  28838. */
  28839. this.lightMap = null;
  28840. /**
  28841. * Intensity of the baked light.
  28842. *
  28843. * @type {number}
  28844. * @default 1
  28845. */
  28846. this.lightMapIntensity = 1.0;
  28847. /**
  28848. * The red channel of this texture is used as the ambient occlusion map.
  28849. * Requires a second set of UVs.
  28850. *
  28851. * @type {?Texture}
  28852. * @default null
  28853. */
  28854. this.aoMap = null;
  28855. /**
  28856. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28857. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28858. * red channel is also `1`, ambient light is fully occluded on a surface.
  28859. *
  28860. * @type {number}
  28861. * @default 1
  28862. */
  28863. this.aoMapIntensity = 1.0;
  28864. /**
  28865. * Emissive (light) color of the material, essentially a solid color
  28866. * unaffected by other lighting.
  28867. *
  28868. * @type {Color}
  28869. * @default (0,0,0)
  28870. */
  28871. this.emissive = new Color( 0x000000 );
  28872. /**
  28873. * Intensity of the emissive light. Modulates the emissive color.
  28874. *
  28875. * @type {number}
  28876. * @default 1
  28877. */
  28878. this.emissiveIntensity = 1.0;
  28879. /**
  28880. * Set emissive (glow) map. The emissive map color is modulated by the
  28881. * emissive color and the emissive intensity. If you have an emissive map,
  28882. * be sure to set the emissive color to something other than black.
  28883. *
  28884. * @type {?Texture}
  28885. * @default null
  28886. */
  28887. this.emissiveMap = null;
  28888. /**
  28889. * The texture to create a bump map. The black and white values map to the
  28890. * perceived depth in relation to the lights. Bump doesn't actually affect
  28891. * the geometry of the object, only the lighting. If a normal map is defined
  28892. * this will be ignored.
  28893. *
  28894. * @type {?Texture}
  28895. * @default null
  28896. */
  28897. this.bumpMap = null;
  28898. /**
  28899. * How much the bump map affects the material. Typical range is `[0,1]`.
  28900. *
  28901. * @type {number}
  28902. * @default 1
  28903. */
  28904. this.bumpScale = 1;
  28905. /**
  28906. * The texture to create a normal map. The RGB values affect the surface
  28907. * normal for each pixel fragment and change the way the color is lit. Normal
  28908. * maps do not change the actual shape of the surface, only the lighting. In
  28909. * case the material has a normal map authored using the left handed
  28910. * convention, the `y` component of `normalScale` should be negated to compensate
  28911. * for the different handedness.
  28912. *
  28913. * @type {?Texture}
  28914. * @default null
  28915. */
  28916. this.normalMap = null;
  28917. /**
  28918. * The type of normal map.
  28919. *
  28920. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28921. * @default TangentSpaceNormalMap
  28922. */
  28923. this.normalMapType = TangentSpaceNormalMap;
  28924. /**
  28925. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28926. *
  28927. * @type {Vector2}
  28928. * @default (1,1)
  28929. */
  28930. this.normalScale = new Vector2( 1, 1 );
  28931. /**
  28932. * The displacement map affects the position of the mesh's vertices. Unlike
  28933. * other maps which only affect the light and shade of the material the
  28934. * displaced vertices can cast shadows, block other objects, and otherwise
  28935. * act as real geometry. The displacement texture is an image where the value
  28936. * of each pixel (white being the highest) is mapped against, and
  28937. * repositions, the vertices of the mesh.
  28938. *
  28939. * @type {?Texture}
  28940. * @default null
  28941. */
  28942. this.displacementMap = null;
  28943. /**
  28944. * How much the displacement map affects the mesh (where black is no
  28945. * displacement, and white is maximum displacement). Without a displacement
  28946. * map set, this value is not applied.
  28947. *
  28948. * @type {number}
  28949. * @default 0
  28950. */
  28951. this.displacementScale = 1;
  28952. /**
  28953. * The offset of the displacement map's values on the mesh's vertices.
  28954. * The bias is added to the scaled sample of the displacement map.
  28955. * Without a displacement map set, this value is not applied.
  28956. *
  28957. * @type {number}
  28958. * @default 0
  28959. */
  28960. this.displacementBias = 0;
  28961. /**
  28962. * The alpha map is a grayscale texture that controls the opacity across the
  28963. * surface (black: fully transparent; white: fully opaque).
  28964. *
  28965. * Only the color of the texture is used, ignoring the alpha channel if one
  28966. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28967. * when sampling this texture due to the extra bit of precision provided for
  28968. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28969. * luminance/alpha textures will also still work as expected.
  28970. *
  28971. * @type {?Texture}
  28972. * @default null
  28973. */
  28974. this.alphaMap = null;
  28975. /**
  28976. * Renders the geometry as a wireframe.
  28977. *
  28978. * @type {boolean}
  28979. * @default false
  28980. */
  28981. this.wireframe = false;
  28982. /**
  28983. * Controls the thickness of the wireframe.
  28984. *
  28985. * Can only be used with {@link SVGRenderer}.
  28986. *
  28987. * @type {number}
  28988. * @default 1
  28989. */
  28990. this.wireframeLinewidth = 1;
  28991. /**
  28992. * Defines appearance of wireframe ends.
  28993. *
  28994. * Can only be used with {@link SVGRenderer}.
  28995. *
  28996. * @type {('round'|'bevel'|'miter')}
  28997. * @default 'round'
  28998. */
  28999. this.wireframeLinecap = 'round';
  29000. /**
  29001. * Defines appearance of wireframe joints.
  29002. *
  29003. * Can only be used with {@link SVGRenderer}.
  29004. *
  29005. * @type {('round'|'bevel'|'miter')}
  29006. * @default 'round'
  29007. */
  29008. this.wireframeLinejoin = 'round';
  29009. /**
  29010. * Whether the material is affected by fog or not.
  29011. *
  29012. * @type {boolean}
  29013. * @default true
  29014. */
  29015. this.fog = true;
  29016. this.setValues( parameters );
  29017. }
  29018. copy( source ) {
  29019. super.copy( source );
  29020. this.color.copy( source.color );
  29021. this.map = source.map;
  29022. this.gradientMap = source.gradientMap;
  29023. this.lightMap = source.lightMap;
  29024. this.lightMapIntensity = source.lightMapIntensity;
  29025. this.aoMap = source.aoMap;
  29026. this.aoMapIntensity = source.aoMapIntensity;
  29027. this.emissive.copy( source.emissive );
  29028. this.emissiveMap = source.emissiveMap;
  29029. this.emissiveIntensity = source.emissiveIntensity;
  29030. this.bumpMap = source.bumpMap;
  29031. this.bumpScale = source.bumpScale;
  29032. this.normalMap = source.normalMap;
  29033. this.normalMapType = source.normalMapType;
  29034. this.normalScale.copy( source.normalScale );
  29035. this.displacementMap = source.displacementMap;
  29036. this.displacementScale = source.displacementScale;
  29037. this.displacementBias = source.displacementBias;
  29038. this.alphaMap = source.alphaMap;
  29039. this.wireframe = source.wireframe;
  29040. this.wireframeLinewidth = source.wireframeLinewidth;
  29041. this.wireframeLinecap = source.wireframeLinecap;
  29042. this.wireframeLinejoin = source.wireframeLinejoin;
  29043. this.fog = source.fog;
  29044. return this;
  29045. }
  29046. }
  29047. /**
  29048. * A material that maps the normal vectors to RGB colors.
  29049. *
  29050. * @augments Material
  29051. */
  29052. class MeshNormalMaterial extends Material {
  29053. /**
  29054. * Constructs a new mesh normal material.
  29055. *
  29056. * @param {Object} [parameters] - An object with one or more properties
  29057. * defining the material's appearance. Any property of the material
  29058. * (including any property from inherited materials) can be passed
  29059. * in here. Color values can be passed any type of value accepted
  29060. * by {@link Color#set}.
  29061. */
  29062. constructor( parameters ) {
  29063. super();
  29064. /**
  29065. * This flag can be used for type testing.
  29066. *
  29067. * @type {boolean}
  29068. * @readonly
  29069. * @default true
  29070. */
  29071. this.isMeshNormalMaterial = true;
  29072. this.type = 'MeshNormalMaterial';
  29073. /**
  29074. * The texture to create a bump map. The black and white values map to the
  29075. * perceived depth in relation to the lights. Bump doesn't actually affect
  29076. * the geometry of the object, only the lighting. If a normal map is defined
  29077. * this will be ignored.
  29078. *
  29079. * @type {?Texture}
  29080. * @default null
  29081. */
  29082. this.bumpMap = null;
  29083. /**
  29084. * How much the bump map affects the material. Typical range is `[0,1]`.
  29085. *
  29086. * @type {number}
  29087. * @default 1
  29088. */
  29089. this.bumpScale = 1;
  29090. /**
  29091. * The texture to create a normal map. The RGB values affect the surface
  29092. * normal for each pixel fragment and change the way the color is lit. Normal
  29093. * maps do not change the actual shape of the surface, only the lighting. In
  29094. * case the material has a normal map authored using the left handed
  29095. * convention, the `y` component of `normalScale` should be negated to compensate
  29096. * for the different handedness.
  29097. *
  29098. * @type {?Texture}
  29099. * @default null
  29100. */
  29101. this.normalMap = null;
  29102. /**
  29103. * The type of normal map.
  29104. *
  29105. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29106. * @default TangentSpaceNormalMap
  29107. */
  29108. this.normalMapType = TangentSpaceNormalMap;
  29109. /**
  29110. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29111. *
  29112. * @type {Vector2}
  29113. * @default (1,1)
  29114. */
  29115. this.normalScale = new Vector2( 1, 1 );
  29116. /**
  29117. * The displacement map affects the position of the mesh's vertices. Unlike
  29118. * other maps which only affect the light and shade of the material the
  29119. * displaced vertices can cast shadows, block other objects, and otherwise
  29120. * act as real geometry. The displacement texture is an image where the value
  29121. * of each pixel (white being the highest) is mapped against, and
  29122. * repositions, the vertices of the mesh.
  29123. *
  29124. * @type {?Texture}
  29125. * @default null
  29126. */
  29127. this.displacementMap = null;
  29128. /**
  29129. * How much the displacement map affects the mesh (where black is no
  29130. * displacement, and white is maximum displacement). Without a displacement
  29131. * map set, this value is not applied.
  29132. *
  29133. * @type {number}
  29134. * @default 0
  29135. */
  29136. this.displacementScale = 1;
  29137. /**
  29138. * The offset of the displacement map's values on the mesh's vertices.
  29139. * The bias is added to the scaled sample of the displacement map.
  29140. * Without a displacement map set, this value is not applied.
  29141. *
  29142. * @type {number}
  29143. * @default 0
  29144. */
  29145. this.displacementBias = 0;
  29146. /**
  29147. * Renders the geometry as a wireframe.
  29148. *
  29149. * @type {boolean}
  29150. * @default false
  29151. */
  29152. this.wireframe = false;
  29153. /**
  29154. * Controls the thickness of the wireframe.
  29155. *
  29156. * WebGL and WebGPU ignore this property and always render
  29157. * 1 pixel wide lines.
  29158. *
  29159. * @type {number}
  29160. * @default 1
  29161. */
  29162. this.wireframeLinewidth = 1;
  29163. /**
  29164. * Whether the material is rendered with flat shading or not.
  29165. *
  29166. * @type {boolean}
  29167. * @default false
  29168. */
  29169. this.flatShading = false;
  29170. this.setValues( parameters );
  29171. }
  29172. copy( source ) {
  29173. super.copy( source );
  29174. this.bumpMap = source.bumpMap;
  29175. this.bumpScale = source.bumpScale;
  29176. this.normalMap = source.normalMap;
  29177. this.normalMapType = source.normalMapType;
  29178. this.normalScale.copy( source.normalScale );
  29179. this.displacementMap = source.displacementMap;
  29180. this.displacementScale = source.displacementScale;
  29181. this.displacementBias = source.displacementBias;
  29182. this.wireframe = source.wireframe;
  29183. this.wireframeLinewidth = source.wireframeLinewidth;
  29184. this.flatShading = source.flatShading;
  29185. return this;
  29186. }
  29187. }
  29188. /**
  29189. * A material for non-shiny surfaces, without specular highlights.
  29190. *
  29191. * The material uses a non-physically based [Lambertian]{@link https://en.wikipedia.org/wiki/Lambertian_reflectance}
  29192. * model for calculating reflectance. This can simulate some surfaces (such
  29193. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29194. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29195. * shading.
  29196. *
  29197. * Due to the simplicity of the reflectance and illumination models,
  29198. * performance will be greater when using this material over the
  29199. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29200. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29201. *
  29202. * @augments Material
  29203. */
  29204. class MeshLambertMaterial extends Material {
  29205. /**
  29206. * Constructs a new mesh lambert material.
  29207. *
  29208. * @param {Object} [parameters] - An object with one or more properties
  29209. * defining the material's appearance. Any property of the material
  29210. * (including any property from inherited materials) can be passed
  29211. * in here. Color values can be passed any type of value accepted
  29212. * by {@link Color#set}.
  29213. */
  29214. constructor( parameters ) {
  29215. super();
  29216. /**
  29217. * This flag can be used for type testing.
  29218. *
  29219. * @type {boolean}
  29220. * @readonly
  29221. * @default true
  29222. */
  29223. this.isMeshLambertMaterial = true;
  29224. this.type = 'MeshLambertMaterial';
  29225. /**
  29226. * Color of the material.
  29227. *
  29228. * @type {Color}
  29229. * @default (1,1,1)
  29230. */
  29231. this.color = new Color( 0xffffff ); // diffuse
  29232. /**
  29233. * The color map. May optionally include an alpha channel, typically combined
  29234. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29235. * color is modulated by the diffuse `color`.
  29236. *
  29237. * @type {?Texture}
  29238. * @default null
  29239. */
  29240. this.map = null;
  29241. /**
  29242. * The light map. Requires a second set of UVs.
  29243. *
  29244. * @type {?Texture}
  29245. * @default null
  29246. */
  29247. this.lightMap = null;
  29248. /**
  29249. * Intensity of the baked light.
  29250. *
  29251. * @type {number}
  29252. * @default 1
  29253. */
  29254. this.lightMapIntensity = 1.0;
  29255. /**
  29256. * The red channel of this texture is used as the ambient occlusion map.
  29257. * Requires a second set of UVs.
  29258. *
  29259. * @type {?Texture}
  29260. * @default null
  29261. */
  29262. this.aoMap = null;
  29263. /**
  29264. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29265. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29266. * red channel is also `1`, ambient light is fully occluded on a surface.
  29267. *
  29268. * @type {number}
  29269. * @default 1
  29270. */
  29271. this.aoMapIntensity = 1.0;
  29272. /**
  29273. * Emissive (light) color of the material, essentially a solid color
  29274. * unaffected by other lighting.
  29275. *
  29276. * @type {Color}
  29277. * @default (0,0,0)
  29278. */
  29279. this.emissive = new Color( 0x000000 );
  29280. /**
  29281. * Intensity of the emissive light. Modulates the emissive color.
  29282. *
  29283. * @type {number}
  29284. * @default 1
  29285. */
  29286. this.emissiveIntensity = 1.0;
  29287. /**
  29288. * Set emissive (glow) map. The emissive map color is modulated by the
  29289. * emissive color and the emissive intensity. If you have an emissive map,
  29290. * be sure to set the emissive color to something other than black.
  29291. *
  29292. * @type {?Texture}
  29293. * @default null
  29294. */
  29295. this.emissiveMap = null;
  29296. /**
  29297. * The texture to create a bump map. The black and white values map to the
  29298. * perceived depth in relation to the lights. Bump doesn't actually affect
  29299. * the geometry of the object, only the lighting. If a normal map is defined
  29300. * this will be ignored.
  29301. *
  29302. * @type {?Texture}
  29303. * @default null
  29304. */
  29305. this.bumpMap = null;
  29306. /**
  29307. * How much the bump map affects the material. Typical range is `[0,1]`.
  29308. *
  29309. * @type {number}
  29310. * @default 1
  29311. */
  29312. this.bumpScale = 1;
  29313. /**
  29314. * The texture to create a normal map. The RGB values affect the surface
  29315. * normal for each pixel fragment and change the way the color is lit. Normal
  29316. * maps do not change the actual shape of the surface, only the lighting. In
  29317. * case the material has a normal map authored using the left handed
  29318. * convention, the `y` component of `normalScale` should be negated to compensate
  29319. * for the different handedness.
  29320. *
  29321. * @type {?Texture}
  29322. * @default null
  29323. */
  29324. this.normalMap = null;
  29325. /**
  29326. * The type of normal map.
  29327. *
  29328. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29329. * @default TangentSpaceNormalMap
  29330. */
  29331. this.normalMapType = TangentSpaceNormalMap;
  29332. /**
  29333. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29334. *
  29335. * @type {Vector2}
  29336. * @default (1,1)
  29337. */
  29338. this.normalScale = new Vector2( 1, 1 );
  29339. /**
  29340. * The displacement map affects the position of the mesh's vertices. Unlike
  29341. * other maps which only affect the light and shade of the material the
  29342. * displaced vertices can cast shadows, block other objects, and otherwise
  29343. * act as real geometry. The displacement texture is an image where the value
  29344. * of each pixel (white being the highest) is mapped against, and
  29345. * repositions, the vertices of the mesh.
  29346. *
  29347. * @type {?Texture}
  29348. * @default null
  29349. */
  29350. this.displacementMap = null;
  29351. /**
  29352. * How much the displacement map affects the mesh (where black is no
  29353. * displacement, and white is maximum displacement). Without a displacement
  29354. * map set, this value is not applied.
  29355. *
  29356. * @type {number}
  29357. * @default 0
  29358. */
  29359. this.displacementScale = 1;
  29360. /**
  29361. * The offset of the displacement map's values on the mesh's vertices.
  29362. * The bias is added to the scaled sample of the displacement map.
  29363. * Without a displacement map set, this value is not applied.
  29364. *
  29365. * @type {number}
  29366. * @default 0
  29367. */
  29368. this.displacementBias = 0;
  29369. /**
  29370. * Specular map used by the material.
  29371. *
  29372. * @type {?Texture}
  29373. * @default null
  29374. */
  29375. this.specularMap = null;
  29376. /**
  29377. * The alpha map is a grayscale texture that controls the opacity across the
  29378. * surface (black: fully transparent; white: fully opaque).
  29379. *
  29380. * Only the color of the texture is used, ignoring the alpha channel if one
  29381. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29382. * when sampling this texture due to the extra bit of precision provided for
  29383. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29384. * luminance/alpha textures will also still work as expected.
  29385. *
  29386. * @type {?Texture}
  29387. * @default null
  29388. */
  29389. this.alphaMap = null;
  29390. /**
  29391. * The environment map.
  29392. *
  29393. * @type {?Texture}
  29394. * @default null
  29395. */
  29396. this.envMap = null;
  29397. /**
  29398. * The rotation of the environment map in radians.
  29399. *
  29400. * @type {Euler}
  29401. * @default (0,0,0)
  29402. */
  29403. this.envMapRotation = new Euler();
  29404. /**
  29405. * How to combine the result of the surface's color with the environment map, if any.
  29406. *
  29407. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29408. * blend between the two colors.
  29409. *
  29410. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29411. * @default MultiplyOperation
  29412. */
  29413. this.combine = MultiplyOperation;
  29414. /**
  29415. * How much the environment map affects the surface.
  29416. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29417. *
  29418. * @type {number}
  29419. * @default 1
  29420. */
  29421. this.reflectivity = 1;
  29422. /**
  29423. * The index of refraction (IOR) of air (approximately 1) divided by the
  29424. * index of refraction of the material. It is used with environment mapping
  29425. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29426. * The refraction ratio should not exceed `1`.
  29427. *
  29428. * @type {number}
  29429. * @default 0.98
  29430. */
  29431. this.refractionRatio = 0.98;
  29432. /**
  29433. * Renders the geometry as a wireframe.
  29434. *
  29435. * @type {boolean}
  29436. * @default false
  29437. */
  29438. this.wireframe = false;
  29439. /**
  29440. * Controls the thickness of the wireframe.
  29441. *
  29442. * Can only be used with {@link SVGRenderer}.
  29443. *
  29444. * @type {number}
  29445. * @default 1
  29446. */
  29447. this.wireframeLinewidth = 1;
  29448. /**
  29449. * Defines appearance of wireframe ends.
  29450. *
  29451. * Can only be used with {@link SVGRenderer}.
  29452. *
  29453. * @type {('round'|'bevel'|'miter')}
  29454. * @default 'round'
  29455. */
  29456. this.wireframeLinecap = 'round';
  29457. /**
  29458. * Defines appearance of wireframe joints.
  29459. *
  29460. * Can only be used with {@link SVGRenderer}.
  29461. *
  29462. * @type {('round'|'bevel'|'miter')}
  29463. * @default 'round'
  29464. */
  29465. this.wireframeLinejoin = 'round';
  29466. /**
  29467. * Whether the material is rendered with flat shading or not.
  29468. *
  29469. * @type {boolean}
  29470. * @default false
  29471. */
  29472. this.flatShading = false;
  29473. /**
  29474. * Whether the material is affected by fog or not.
  29475. *
  29476. * @type {boolean}
  29477. * @default true
  29478. */
  29479. this.fog = true;
  29480. this.setValues( parameters );
  29481. }
  29482. copy( source ) {
  29483. super.copy( source );
  29484. this.color.copy( source.color );
  29485. this.map = source.map;
  29486. this.lightMap = source.lightMap;
  29487. this.lightMapIntensity = source.lightMapIntensity;
  29488. this.aoMap = source.aoMap;
  29489. this.aoMapIntensity = source.aoMapIntensity;
  29490. this.emissive.copy( source.emissive );
  29491. this.emissiveMap = source.emissiveMap;
  29492. this.emissiveIntensity = source.emissiveIntensity;
  29493. this.bumpMap = source.bumpMap;
  29494. this.bumpScale = source.bumpScale;
  29495. this.normalMap = source.normalMap;
  29496. this.normalMapType = source.normalMapType;
  29497. this.normalScale.copy( source.normalScale );
  29498. this.displacementMap = source.displacementMap;
  29499. this.displacementScale = source.displacementScale;
  29500. this.displacementBias = source.displacementBias;
  29501. this.specularMap = source.specularMap;
  29502. this.alphaMap = source.alphaMap;
  29503. this.envMap = source.envMap;
  29504. this.envMapRotation.copy( source.envMapRotation );
  29505. this.combine = source.combine;
  29506. this.reflectivity = source.reflectivity;
  29507. this.refractionRatio = source.refractionRatio;
  29508. this.wireframe = source.wireframe;
  29509. this.wireframeLinewidth = source.wireframeLinewidth;
  29510. this.wireframeLinecap = source.wireframeLinecap;
  29511. this.wireframeLinejoin = source.wireframeLinejoin;
  29512. this.flatShading = source.flatShading;
  29513. this.fog = source.fog;
  29514. return this;
  29515. }
  29516. }
  29517. /**
  29518. * A material for drawing geometry by depth. Depth is based off of the camera
  29519. * near and far plane. White is nearest, black is farthest.
  29520. *
  29521. * @augments Material
  29522. */
  29523. class MeshDepthMaterial extends Material {
  29524. /**
  29525. * Constructs a new mesh depth material.
  29526. *
  29527. * @param {Object} [parameters] - An object with one or more properties
  29528. * defining the material's appearance. Any property of the material
  29529. * (including any property from inherited materials) can be passed
  29530. * in here. Color values can be passed any type of value accepted
  29531. * by {@link Color#set}.
  29532. */
  29533. constructor( parameters ) {
  29534. super();
  29535. /**
  29536. * This flag can be used for type testing.
  29537. *
  29538. * @type {boolean}
  29539. * @readonly
  29540. * @default true
  29541. */
  29542. this.isMeshDepthMaterial = true;
  29543. this.type = 'MeshDepthMaterial';
  29544. /**
  29545. * Type for depth packing.
  29546. *
  29547. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  29548. * @default BasicDepthPacking
  29549. */
  29550. this.depthPacking = BasicDepthPacking;
  29551. /**
  29552. * The color map. May optionally include an alpha channel, typically combined
  29553. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29554. *
  29555. * @type {?Texture}
  29556. * @default null
  29557. */
  29558. this.map = null;
  29559. /**
  29560. * The alpha map is a grayscale texture that controls the opacity across the
  29561. * surface (black: fully transparent; white: fully opaque).
  29562. *
  29563. * Only the color of the texture is used, ignoring the alpha channel if one
  29564. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29565. * when sampling this texture due to the extra bit of precision provided for
  29566. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29567. * luminance/alpha textures will also still work as expected.
  29568. *
  29569. * @type {?Texture}
  29570. * @default null
  29571. */
  29572. this.alphaMap = null;
  29573. /**
  29574. * The displacement map affects the position of the mesh's vertices. Unlike
  29575. * other maps which only affect the light and shade of the material the
  29576. * displaced vertices can cast shadows, block other objects, and otherwise
  29577. * act as real geometry. The displacement texture is an image where the value
  29578. * of each pixel (white being the highest) is mapped against, and
  29579. * repositions, the vertices of the mesh.
  29580. *
  29581. * @type {?Texture}
  29582. * @default null
  29583. */
  29584. this.displacementMap = null;
  29585. /**
  29586. * How much the displacement map affects the mesh (where black is no
  29587. * displacement, and white is maximum displacement). Without a displacement
  29588. * map set, this value is not applied.
  29589. *
  29590. * @type {number}
  29591. * @default 0
  29592. */
  29593. this.displacementScale = 1;
  29594. /**
  29595. * The offset of the displacement map's values on the mesh's vertices.
  29596. * The bias is added to the scaled sample of the displacement map.
  29597. * Without a displacement map set, this value is not applied.
  29598. *
  29599. * @type {number}
  29600. * @default 0
  29601. */
  29602. this.displacementBias = 0;
  29603. /**
  29604. * Renders the geometry as a wireframe.
  29605. *
  29606. * @type {boolean}
  29607. * @default false
  29608. */
  29609. this.wireframe = false;
  29610. /**
  29611. * Controls the thickness of the wireframe.
  29612. *
  29613. * WebGL and WebGPU ignore this property and always render
  29614. * 1 pixel wide lines.
  29615. *
  29616. * @type {number}
  29617. * @default 1
  29618. */
  29619. this.wireframeLinewidth = 1;
  29620. this.setValues( parameters );
  29621. }
  29622. copy( source ) {
  29623. super.copy( source );
  29624. this.depthPacking = source.depthPacking;
  29625. this.map = source.map;
  29626. this.alphaMap = source.alphaMap;
  29627. this.displacementMap = source.displacementMap;
  29628. this.displacementScale = source.displacementScale;
  29629. this.displacementBias = source.displacementBias;
  29630. this.wireframe = source.wireframe;
  29631. this.wireframeLinewidth = source.wireframeLinewidth;
  29632. return this;
  29633. }
  29634. }
  29635. /**
  29636. * A material used internally for implementing shadow mapping with
  29637. * point lights.
  29638. *
  29639. * Can also be used to customize the shadow casting of an object by assigning
  29640. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  29641. * The following examples demonstrates this approach in order to ensure
  29642. * transparent parts of objects do no cast shadows.
  29643. *
  29644. * @augments Material
  29645. */
  29646. class MeshDistanceMaterial extends Material {
  29647. /**
  29648. * Constructs a new mesh distance material.
  29649. *
  29650. * @param {Object} [parameters] - An object with one or more properties
  29651. * defining the material's appearance. Any property of the material
  29652. * (including any property from inherited materials) can be passed
  29653. * in here. Color values can be passed any type of value accepted
  29654. * by {@link Color#set}.
  29655. */
  29656. constructor( parameters ) {
  29657. super();
  29658. /**
  29659. * This flag can be used for type testing.
  29660. *
  29661. * @type {boolean}
  29662. * @readonly
  29663. * @default true
  29664. */
  29665. this.isMeshDistanceMaterial = true;
  29666. this.type = 'MeshDistanceMaterial';
  29667. /**
  29668. * The color map. May optionally include an alpha channel, typically combined
  29669. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29670. *
  29671. * @type {?Texture}
  29672. * @default null
  29673. */
  29674. this.map = null;
  29675. /**
  29676. * The alpha map is a grayscale texture that controls the opacity across the
  29677. * surface (black: fully transparent; white: fully opaque).
  29678. *
  29679. * Only the color of the texture is used, ignoring the alpha channel if one
  29680. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29681. * when sampling this texture due to the extra bit of precision provided for
  29682. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29683. * luminance/alpha textures will also still work as expected.
  29684. *
  29685. * @type {?Texture}
  29686. * @default null
  29687. */
  29688. this.alphaMap = null;
  29689. /**
  29690. * The displacement map affects the position of the mesh's vertices. Unlike
  29691. * other maps which only affect the light and shade of the material the
  29692. * displaced vertices can cast shadows, block other objects, and otherwise
  29693. * act as real geometry. The displacement texture is an image where the value
  29694. * of each pixel (white being the highest) is mapped against, and
  29695. * repositions, the vertices of the mesh.
  29696. *
  29697. * @type {?Texture}
  29698. * @default null
  29699. */
  29700. this.displacementMap = null;
  29701. /**
  29702. * How much the displacement map affects the mesh (where black is no
  29703. * displacement, and white is maximum displacement). Without a displacement
  29704. * map set, this value is not applied.
  29705. *
  29706. * @type {number}
  29707. * @default 0
  29708. */
  29709. this.displacementScale = 1;
  29710. /**
  29711. * The offset of the displacement map's values on the mesh's vertices.
  29712. * The bias is added to the scaled sample of the displacement map.
  29713. * Without a displacement map set, this value is not applied.
  29714. *
  29715. * @type {number}
  29716. * @default 0
  29717. */
  29718. this.displacementBias = 0;
  29719. this.setValues( parameters );
  29720. }
  29721. copy( source ) {
  29722. super.copy( source );
  29723. this.map = source.map;
  29724. this.alphaMap = source.alphaMap;
  29725. this.displacementMap = source.displacementMap;
  29726. this.displacementScale = source.displacementScale;
  29727. this.displacementBias = source.displacementBias;
  29728. return this;
  29729. }
  29730. }
  29731. /**
  29732. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  29733. * material color and shading.
  29734. *
  29735. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  29736. * baked lighting. It will cast a shadow onto an object that receives shadows
  29737. * (and shadow clipping works), but it will not self-shadow or receive
  29738. * shadows.
  29739. *
  29740. * @augments Material
  29741. */
  29742. class MeshMatcapMaterial extends Material {
  29743. /**
  29744. * Constructs a new mesh matcap material.
  29745. *
  29746. * @param {Object} [parameters] - An object with one or more properties
  29747. * defining the material's appearance. Any property of the material
  29748. * (including any property from inherited materials) can be passed
  29749. * in here. Color values can be passed any type of value accepted
  29750. * by {@link Color#set}.
  29751. */
  29752. constructor( parameters ) {
  29753. super();
  29754. /**
  29755. * This flag can be used for type testing.
  29756. *
  29757. * @type {boolean}
  29758. * @readonly
  29759. * @default true
  29760. */
  29761. this.isMeshMatcapMaterial = true;
  29762. this.defines = { 'MATCAP': '' };
  29763. this.type = 'MeshMatcapMaterial';
  29764. /**
  29765. * Color of the material.
  29766. *
  29767. * @type {Color}
  29768. * @default (1,1,1)
  29769. */
  29770. this.color = new Color( 0xffffff ); // diffuse
  29771. /**
  29772. * The matcap map.
  29773. *
  29774. * @type {?Texture}
  29775. * @default null
  29776. */
  29777. this.matcap = null;
  29778. /**
  29779. * The color map. May optionally include an alpha channel, typically combined
  29780. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29781. * color is modulated by the diffuse `color`.
  29782. *
  29783. * @type {?Texture}
  29784. * @default null
  29785. */
  29786. this.map = null;
  29787. /**
  29788. * The texture to create a bump map. The black and white values map to the
  29789. * perceived depth in relation to the lights. Bump doesn't actually affect
  29790. * the geometry of the object, only the lighting. If a normal map is defined
  29791. * this will be ignored.
  29792. *
  29793. * @type {?Texture}
  29794. * @default null
  29795. */
  29796. this.bumpMap = null;
  29797. /**
  29798. * How much the bump map affects the material. Typical range is `[0,1]`.
  29799. *
  29800. * @type {number}
  29801. * @default 1
  29802. */
  29803. this.bumpScale = 1;
  29804. /**
  29805. * The texture to create a normal map. The RGB values affect the surface
  29806. * normal for each pixel fragment and change the way the color is lit. Normal
  29807. * maps do not change the actual shape of the surface, only the lighting. In
  29808. * case the material has a normal map authored using the left handed
  29809. * convention, the `y` component of `normalScale` should be negated to compensate
  29810. * for the different handedness.
  29811. *
  29812. * @type {?Texture}
  29813. * @default null
  29814. */
  29815. this.normalMap = null;
  29816. /**
  29817. * The type of normal map.
  29818. *
  29819. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29820. * @default TangentSpaceNormalMap
  29821. */
  29822. this.normalMapType = TangentSpaceNormalMap;
  29823. /**
  29824. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29825. *
  29826. * @type {Vector2}
  29827. * @default (1,1)
  29828. */
  29829. this.normalScale = new Vector2( 1, 1 );
  29830. /**
  29831. * The displacement map affects the position of the mesh's vertices. Unlike
  29832. * other maps which only affect the light and shade of the material the
  29833. * displaced vertices can cast shadows, block other objects, and otherwise
  29834. * act as real geometry. The displacement texture is an image where the value
  29835. * of each pixel (white being the highest) is mapped against, and
  29836. * repositions, the vertices of the mesh.
  29837. *
  29838. * @type {?Texture}
  29839. * @default null
  29840. */
  29841. this.displacementMap = null;
  29842. /**
  29843. * How much the displacement map affects the mesh (where black is no
  29844. * displacement, and white is maximum displacement). Without a displacement
  29845. * map set, this value is not applied.
  29846. *
  29847. * @type {number}
  29848. * @default 0
  29849. */
  29850. this.displacementScale = 1;
  29851. /**
  29852. * The offset of the displacement map's values on the mesh's vertices.
  29853. * The bias is added to the scaled sample of the displacement map.
  29854. * Without a displacement map set, this value is not applied.
  29855. *
  29856. * @type {number}
  29857. * @default 0
  29858. */
  29859. this.displacementBias = 0;
  29860. /**
  29861. * The alpha map is a grayscale texture that controls the opacity across the
  29862. * surface (black: fully transparent; white: fully opaque).
  29863. *
  29864. * Only the color of the texture is used, ignoring the alpha channel if one
  29865. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29866. * when sampling this texture due to the extra bit of precision provided for
  29867. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29868. * luminance/alpha textures will also still work as expected.
  29869. *
  29870. * @type {?Texture}
  29871. * @default null
  29872. */
  29873. this.alphaMap = null;
  29874. /**
  29875. * Whether the material is rendered with flat shading or not.
  29876. *
  29877. * @type {boolean}
  29878. * @default false
  29879. */
  29880. this.flatShading = false;
  29881. /**
  29882. * Whether the material is affected by fog or not.
  29883. *
  29884. * @type {boolean}
  29885. * @default true
  29886. */
  29887. this.fog = true;
  29888. this.setValues( parameters );
  29889. }
  29890. copy( source ) {
  29891. super.copy( source );
  29892. this.defines = { 'MATCAP': '' };
  29893. this.color.copy( source.color );
  29894. this.matcap = source.matcap;
  29895. this.map = source.map;
  29896. this.bumpMap = source.bumpMap;
  29897. this.bumpScale = source.bumpScale;
  29898. this.normalMap = source.normalMap;
  29899. this.normalMapType = source.normalMapType;
  29900. this.normalScale.copy( source.normalScale );
  29901. this.displacementMap = source.displacementMap;
  29902. this.displacementScale = source.displacementScale;
  29903. this.displacementBias = source.displacementBias;
  29904. this.alphaMap = source.alphaMap;
  29905. this.flatShading = source.flatShading;
  29906. this.fog = source.fog;
  29907. return this;
  29908. }
  29909. }
  29910. /**
  29911. * A material for rendering line primitives.
  29912. *
  29913. * Materials define the appearance of renderable 3D objects.
  29914. *
  29915. * ```js
  29916. * const material = new THREE.LineDashedMaterial( {
  29917. * color: 0xffffff,
  29918. * scale: 1,
  29919. * dashSize: 3,
  29920. * gapSize: 1,
  29921. * } );
  29922. * ```
  29923. *
  29924. * @augments LineBasicMaterial
  29925. */
  29926. class LineDashedMaterial extends LineBasicMaterial {
  29927. /**
  29928. * Constructs a new line dashed material.
  29929. *
  29930. * @param {Object} [parameters] - An object with one or more properties
  29931. * defining the material's appearance. Any property of the material
  29932. * (including any property from inherited materials) can be passed
  29933. * in here. Color values can be passed any type of value accepted
  29934. * by {@link Color#set}.
  29935. */
  29936. constructor( parameters ) {
  29937. super();
  29938. /**
  29939. * This flag can be used for type testing.
  29940. *
  29941. * @type {boolean}
  29942. * @readonly
  29943. * @default true
  29944. */
  29945. this.isLineDashedMaterial = true;
  29946. this.type = 'LineDashedMaterial';
  29947. /**
  29948. * The scale of the dashed part of a line.
  29949. *
  29950. * @type {number}
  29951. * @default 1
  29952. */
  29953. this.scale = 1;
  29954. /**
  29955. * The size of the dash. This is both the gap with the stroke.
  29956. *
  29957. * @type {number}
  29958. * @default 3
  29959. */
  29960. this.dashSize = 3;
  29961. /**
  29962. * The size of the gap.
  29963. *
  29964. * @type {number}
  29965. * @default 1
  29966. */
  29967. this.gapSize = 1;
  29968. this.setValues( parameters );
  29969. }
  29970. copy( source ) {
  29971. super.copy( source );
  29972. this.scale = source.scale;
  29973. this.dashSize = source.dashSize;
  29974. this.gapSize = source.gapSize;
  29975. return this;
  29976. }
  29977. }
  29978. /**
  29979. * Converts an array to a specific type.
  29980. *
  29981. * @param {TypedArray|Array} array - The array to convert.
  29982. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  29983. * @return {TypedArray} The converted array.
  29984. */
  29985. function convertArray( array, type ) {
  29986. if ( ! array || array.constructor === type ) return array;
  29987. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  29988. return new type( array ); // create typed array
  29989. }
  29990. return Array.prototype.slice.call( array ); // create Array
  29991. }
  29992. /**
  29993. * Returns `true` if the given object is a typed array.
  29994. *
  29995. * @param {any} object - The object to check.
  29996. * @return {boolean} Whether the given object is a typed array.
  29997. */
  29998. function isTypedArray( object ) {
  29999. return ArrayBuffer.isView( object ) && ! ( object instanceof DataView );
  30000. }
  30001. /**
  30002. * Returns an array by which times and values can be sorted.
  30003. *
  30004. * @param {Array<number>} times - The keyframe time values.
  30005. * @return {Array<number>} The array.
  30006. */
  30007. function getKeyframeOrder( times ) {
  30008. function compareTime( i, j ) {
  30009. return times[ i ] - times[ j ];
  30010. }
  30011. const n = times.length;
  30012. const result = new Array( n );
  30013. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  30014. result.sort( compareTime );
  30015. return result;
  30016. }
  30017. /**
  30018. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30019. *
  30020. * @param {Array<number>} values - The values to sort.
  30021. * @param {number} stride - The stride.
  30022. * @param {Array<number>} order - The sort order.
  30023. * @return {Array<number>} The sorted values.
  30024. */
  30025. function sortedArray( values, stride, order ) {
  30026. const nValues = values.length;
  30027. const result = new values.constructor( nValues );
  30028. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  30029. const srcOffset = order[ i ] * stride;
  30030. for ( let j = 0; j !== stride; ++ j ) {
  30031. result[ dstOffset ++ ] = values[ srcOffset + j ];
  30032. }
  30033. }
  30034. return result;
  30035. }
  30036. /**
  30037. * Used for parsing AOS keyframe formats.
  30038. *
  30039. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30040. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  30041. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  30042. * @param {string} valuePropertyName - The name of the property to use.
  30043. */
  30044. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30045. let i = 1, key = jsonKeys[ 0 ];
  30046. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  30047. key = jsonKeys[ i ++ ];
  30048. }
  30049. if ( key === undefined ) return; // no data
  30050. let value = key[ valuePropertyName ];
  30051. if ( value === undefined ) return; // no data
  30052. if ( Array.isArray( value ) ) {
  30053. do {
  30054. value = key[ valuePropertyName ];
  30055. if ( value !== undefined ) {
  30056. times.push( key.time );
  30057. values.push( ...value ); // push all elements
  30058. }
  30059. key = jsonKeys[ i ++ ];
  30060. } while ( key !== undefined );
  30061. } else if ( value.toArray !== undefined ) {
  30062. // ...assume THREE.Math-ish
  30063. do {
  30064. value = key[ valuePropertyName ];
  30065. if ( value !== undefined ) {
  30066. times.push( key.time );
  30067. value.toArray( values, values.length );
  30068. }
  30069. key = jsonKeys[ i ++ ];
  30070. } while ( key !== undefined );
  30071. } else {
  30072. // otherwise push as-is
  30073. do {
  30074. value = key[ valuePropertyName ];
  30075. if ( value !== undefined ) {
  30076. times.push( key.time );
  30077. values.push( value );
  30078. }
  30079. key = jsonKeys[ i ++ ];
  30080. } while ( key !== undefined );
  30081. }
  30082. }
  30083. /**
  30084. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30085. *
  30086. * @param {AnimationClip} sourceClip - The values to sort.
  30087. * @param {string} name - The name of the clip.
  30088. * @param {number} startFrame - The start frame.
  30089. * @param {number} endFrame - The end frame.
  30090. * @param {number} [fps=30] - The FPS.
  30091. * @return {AnimationClip} The new sub clip.
  30092. */
  30093. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30094. const clip = sourceClip.clone();
  30095. clip.name = name;
  30096. const tracks = [];
  30097. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30098. const track = clip.tracks[ i ];
  30099. const valueSize = track.getValueSize();
  30100. const times = [];
  30101. const values = [];
  30102. for ( let j = 0; j < track.times.length; ++ j ) {
  30103. const frame = track.times[ j ] * fps;
  30104. if ( frame < startFrame || frame >= endFrame ) continue;
  30105. times.push( track.times[ j ] );
  30106. for ( let k = 0; k < valueSize; ++ k ) {
  30107. values.push( track.values[ j * valueSize + k ] );
  30108. }
  30109. }
  30110. if ( times.length === 0 ) continue;
  30111. track.times = convertArray( times, track.times.constructor );
  30112. track.values = convertArray( values, track.values.constructor );
  30113. tracks.push( track );
  30114. }
  30115. clip.tracks = tracks;
  30116. // find minimum .times value across all tracks in the trimmed clip
  30117. let minStartTime = Infinity;
  30118. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30119. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  30120. minStartTime = clip.tracks[ i ].times[ 0 ];
  30121. }
  30122. }
  30123. // shift all tracks such that clip begins at t=0
  30124. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30125. clip.tracks[ i ].shift( -1 * minStartTime );
  30126. }
  30127. clip.resetDuration();
  30128. return clip;
  30129. }
  30130. /**
  30131. * Converts the keyframes of the given animation clip to an additive format.
  30132. *
  30133. * @param {AnimationClip} targetClip - The clip to make additive.
  30134. * @param {number} [referenceFrame=0] - The reference frame.
  30135. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30136. * @param {number} [fps=30] - The FPS.
  30137. * @return {AnimationClip} The updated clip which is now additive.
  30138. */
  30139. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30140. if ( fps <= 0 ) fps = 30;
  30141. const numTracks = referenceClip.tracks.length;
  30142. const referenceTime = referenceFrame / fps;
  30143. // Make each track's values relative to the values at the reference frame
  30144. for ( let i = 0; i < numTracks; ++ i ) {
  30145. const referenceTrack = referenceClip.tracks[ i ];
  30146. const referenceTrackType = referenceTrack.ValueTypeName;
  30147. // Skip this track if it's non-numeric
  30148. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  30149. // Find the track in the target clip whose name and type matches the reference track
  30150. const targetTrack = targetClip.tracks.find( function ( track ) {
  30151. return track.name === referenceTrack.name
  30152. && track.ValueTypeName === referenceTrackType;
  30153. } );
  30154. if ( targetTrack === undefined ) continue;
  30155. let referenceOffset = 0;
  30156. const referenceValueSize = referenceTrack.getValueSize();
  30157. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30158. referenceOffset = referenceValueSize / 3;
  30159. }
  30160. let targetOffset = 0;
  30161. const targetValueSize = targetTrack.getValueSize();
  30162. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30163. targetOffset = targetValueSize / 3;
  30164. }
  30165. const lastIndex = referenceTrack.times.length - 1;
  30166. let referenceValue;
  30167. // Find the value to subtract out of the track
  30168. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  30169. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  30170. const startIndex = referenceOffset;
  30171. const endIndex = referenceValueSize - referenceOffset;
  30172. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30173. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30174. // Reference frame is after the last keyframe, so just use the last keyframe
  30175. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30176. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30177. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30178. } else {
  30179. // Interpolate to the reference value
  30180. const interpolant = referenceTrack.createInterpolant();
  30181. const startIndex = referenceOffset;
  30182. const endIndex = referenceValueSize - referenceOffset;
  30183. interpolant.evaluate( referenceTime );
  30184. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30185. }
  30186. // Conjugate the quaternion
  30187. if ( referenceTrackType === 'quaternion' ) {
  30188. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30189. referenceQuat.toArray( referenceValue );
  30190. }
  30191. // Subtract the reference value from all of the track values
  30192. const numTimes = targetTrack.times.length;
  30193. for ( let j = 0; j < numTimes; ++ j ) {
  30194. const valueStart = j * targetValueSize + targetOffset;
  30195. if ( referenceTrackType === 'quaternion' ) {
  30196. // Multiply the conjugate for quaternion track types
  30197. Quaternion.multiplyQuaternionsFlat(
  30198. targetTrack.values,
  30199. valueStart,
  30200. referenceValue,
  30201. 0,
  30202. targetTrack.values,
  30203. valueStart
  30204. );
  30205. } else {
  30206. const valueEnd = targetValueSize - targetOffset * 2;
  30207. // Subtract each value for all other numeric track types
  30208. for ( let k = 0; k < valueEnd; ++ k ) {
  30209. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30210. }
  30211. }
  30212. }
  30213. }
  30214. targetClip.blendMode = AdditiveAnimationBlendMode;
  30215. return targetClip;
  30216. }
  30217. /**
  30218. * A class with various methods to assist with animations.
  30219. *
  30220. * @hideconstructor
  30221. */
  30222. class AnimationUtils {
  30223. /**
  30224. * Converts an array to a specific type
  30225. *
  30226. * @static
  30227. * @param {TypedArray|Array} array - The array to convert.
  30228. * @param {TypedArray.constructor} type - The constructor of a type array.
  30229. * @return {TypedArray} The converted array
  30230. */
  30231. static convertArray( array, type ) {
  30232. return convertArray( array, type );
  30233. }
  30234. /**
  30235. * Returns `true` if the given object is a typed array.
  30236. *
  30237. * @static
  30238. * @param {any} object - The object to check.
  30239. * @return {boolean} Whether the given object is a typed array.
  30240. */
  30241. static isTypedArray( object ) {
  30242. return isTypedArray( object );
  30243. }
  30244. /**
  30245. * Returns an array by which times and values can be sorted.
  30246. *
  30247. * @static
  30248. * @param {Array<number>} times - The keyframe time values.
  30249. * @return {Array<number>} The array.
  30250. */
  30251. static getKeyframeOrder( times ) {
  30252. return getKeyframeOrder( times );
  30253. }
  30254. /**
  30255. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30256. *
  30257. * @static
  30258. * @param {Array<number>} values - The values to sort.
  30259. * @param {number} stride - The stride.
  30260. * @param {Array<number>} order - The sort order.
  30261. * @return {Array<number>} The sorted values.
  30262. */
  30263. static sortedArray( values, stride, order ) {
  30264. return sortedArray( values, stride, order );
  30265. }
  30266. /**
  30267. * Used for parsing AOS keyframe formats.
  30268. *
  30269. * @static
  30270. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30271. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30272. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30273. * @param {string} valuePropertyName - The name of the property to use.
  30274. */
  30275. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30276. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30277. }
  30278. /**
  30279. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30280. *
  30281. * @static
  30282. * @param {AnimationClip} sourceClip - The values to sort.
  30283. * @param {string} name - The name of the clip.
  30284. * @param {number} startFrame - The start frame.
  30285. * @param {number} endFrame - The end frame.
  30286. * @param {number} [fps=30] - The FPS.
  30287. * @return {AnimationClip} The new sub clip.
  30288. */
  30289. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30290. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30291. }
  30292. /**
  30293. * Converts the keyframes of the given animation clip to an additive format.
  30294. *
  30295. * @static
  30296. * @param {AnimationClip} targetClip - The clip to make additive.
  30297. * @param {number} [referenceFrame=0] - The reference frame.
  30298. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30299. * @param {number} [fps=30] - The FPS.
  30300. * @return {AnimationClip} The updated clip which is now additive.
  30301. */
  30302. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30303. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30304. }
  30305. }
  30306. /**
  30307. * Abstract base class of interpolants over parametric samples.
  30308. *
  30309. * The parameter domain is one dimensional, typically the time or a path
  30310. * along a curve defined by the data.
  30311. *
  30312. * The sample values can have any dimensionality and derived classes may
  30313. * apply special interpretations to the data.
  30314. *
  30315. * This class provides the interval seek in a Template Method, deferring
  30316. * the actual interpolation to derived classes.
  30317. *
  30318. * Time complexity is O(1) for linear access crossing at most two points
  30319. * and O(log N) for random access, where N is the number of positions.
  30320. *
  30321. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30322. *
  30323. * @abstract
  30324. */
  30325. class Interpolant {
  30326. /**
  30327. * Constructs a new interpolant.
  30328. *
  30329. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30330. * @param {TypedArray} sampleValues - The sample values.
  30331. * @param {number} sampleSize - The sample size
  30332. * @param {TypedArray} [resultBuffer] - The result buffer.
  30333. */
  30334. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30335. /**
  30336. * The parameter positions.
  30337. *
  30338. * @type {TypedArray}
  30339. */
  30340. this.parameterPositions = parameterPositions;
  30341. /**
  30342. * A cache index.
  30343. *
  30344. * @private
  30345. * @type {number}
  30346. * @default 0
  30347. */
  30348. this._cachedIndex = 0;
  30349. /**
  30350. * The result buffer.
  30351. *
  30352. * @type {TypedArray}
  30353. */
  30354. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30355. /**
  30356. * The sample values.
  30357. *
  30358. * @type {TypedArray}
  30359. */
  30360. this.sampleValues = sampleValues;
  30361. /**
  30362. * The value size.
  30363. *
  30364. * @type {TypedArray}
  30365. */
  30366. this.valueSize = sampleSize;
  30367. /**
  30368. * The interpolation settings.
  30369. *
  30370. * @type {?Object}
  30371. * @default null
  30372. */
  30373. this.settings = null;
  30374. /**
  30375. * The default settings object.
  30376. *
  30377. * @type {Object}
  30378. */
  30379. this.DefaultSettings_ = {};
  30380. }
  30381. /**
  30382. * Evaluate the interpolant at position `t`.
  30383. *
  30384. * @param {number} t - The interpolation factor.
  30385. * @return {TypedArray} The result buffer.
  30386. */
  30387. evaluate( t ) {
  30388. const pp = this.parameterPositions;
  30389. let i1 = this._cachedIndex,
  30390. t1 = pp[ i1 ],
  30391. t0 = pp[ i1 - 1 ];
  30392. validate_interval: {
  30393. seek: {
  30394. let right;
  30395. linear_scan: {
  30396. //- See http://jsperf.com/comparison-to-undefined/3
  30397. //- slower code:
  30398. //-
  30399. //- if ( t >= t1 || t1 === undefined ) {
  30400. forward_scan: if ( ! ( t < t1 ) ) {
  30401. for ( let giveUpAt = i1 + 2; ; ) {
  30402. if ( t1 === undefined ) {
  30403. if ( t < t0 ) break forward_scan;
  30404. // after end
  30405. i1 = pp.length;
  30406. this._cachedIndex = i1;
  30407. return this.copySampleValue_( i1 - 1 );
  30408. }
  30409. if ( i1 === giveUpAt ) break; // this loop
  30410. t0 = t1;
  30411. t1 = pp[ ++ i1 ];
  30412. if ( t < t1 ) {
  30413. // we have arrived at the sought interval
  30414. break seek;
  30415. }
  30416. }
  30417. // prepare binary search on the right side of the index
  30418. right = pp.length;
  30419. break linear_scan;
  30420. }
  30421. //- slower code:
  30422. //- if ( t < t0 || t0 === undefined ) {
  30423. if ( ! ( t >= t0 ) ) {
  30424. // looping?
  30425. const t1global = pp[ 1 ];
  30426. if ( t < t1global ) {
  30427. i1 = 2; // + 1, using the scan for the details
  30428. t0 = t1global;
  30429. }
  30430. // linear reverse scan
  30431. for ( let giveUpAt = i1 - 2; ; ) {
  30432. if ( t0 === undefined ) {
  30433. // before start
  30434. this._cachedIndex = 0;
  30435. return this.copySampleValue_( 0 );
  30436. }
  30437. if ( i1 === giveUpAt ) break; // this loop
  30438. t1 = t0;
  30439. t0 = pp[ -- i1 - 1 ];
  30440. if ( t >= t0 ) {
  30441. // we have arrived at the sought interval
  30442. break seek;
  30443. }
  30444. }
  30445. // prepare binary search on the left side of the index
  30446. right = i1;
  30447. i1 = 0;
  30448. break linear_scan;
  30449. }
  30450. // the interval is valid
  30451. break validate_interval;
  30452. } // linear scan
  30453. // binary search
  30454. while ( i1 < right ) {
  30455. const mid = ( i1 + right ) >>> 1;
  30456. if ( t < pp[ mid ] ) {
  30457. right = mid;
  30458. } else {
  30459. i1 = mid + 1;
  30460. }
  30461. }
  30462. t1 = pp[ i1 ];
  30463. t0 = pp[ i1 - 1 ];
  30464. // check boundary cases, again
  30465. if ( t0 === undefined ) {
  30466. this._cachedIndex = 0;
  30467. return this.copySampleValue_( 0 );
  30468. }
  30469. if ( t1 === undefined ) {
  30470. i1 = pp.length;
  30471. this._cachedIndex = i1;
  30472. return this.copySampleValue_( i1 - 1 );
  30473. }
  30474. } // seek
  30475. this._cachedIndex = i1;
  30476. this.intervalChanged_( i1, t0, t1 );
  30477. } // validate_interval
  30478. return this.interpolate_( i1, t0, t, t1 );
  30479. }
  30480. /**
  30481. * Returns the interpolation settings.
  30482. *
  30483. * @return {Object} The interpolation settings.
  30484. */
  30485. getSettings_() {
  30486. return this.settings || this.DefaultSettings_;
  30487. }
  30488. /**
  30489. * Copies a sample value to the result buffer.
  30490. *
  30491. * @param {number} index - An index into the sample value buffer.
  30492. * @return {TypedArray} The result buffer.
  30493. */
  30494. copySampleValue_( index ) {
  30495. // copies a sample value to the result buffer
  30496. const result = this.resultBuffer,
  30497. values = this.sampleValues,
  30498. stride = this.valueSize,
  30499. offset = index * stride;
  30500. for ( let i = 0; i !== stride; ++ i ) {
  30501. result[ i ] = values[ offset + i ];
  30502. }
  30503. return result;
  30504. }
  30505. /**
  30506. * Copies a sample value to the result buffer.
  30507. *
  30508. * @abstract
  30509. * @param {number} i1 - An index into the sample value buffer.
  30510. * @param {number} t0 - The previous interpolation factor.
  30511. * @param {number} t - The current interpolation factor.
  30512. * @param {number} t1 - The next interpolation factor.
  30513. * @return {TypedArray} The result buffer.
  30514. */
  30515. interpolate_( /* i1, t0, t, t1 */ ) {
  30516. throw new Error( 'call to abstract method' );
  30517. // implementations shall return this.resultBuffer
  30518. }
  30519. /**
  30520. * Optional method that is executed when the interval has changed.
  30521. *
  30522. * @param {number} i1 - An index into the sample value buffer.
  30523. * @param {number} t0 - The previous interpolation factor.
  30524. * @param {number} t - The current interpolation factor.
  30525. */
  30526. intervalChanged_( /* i1, t0, t1 */ ) {
  30527. // empty
  30528. }
  30529. }
  30530. /**
  30531. * Fast and simple cubic spline interpolant.
  30532. *
  30533. * It was derived from a Hermitian construction setting the first derivative
  30534. * at each sample position to the linear slope between neighboring positions
  30535. * over their parameter interval.
  30536. *
  30537. * @augments Interpolant
  30538. */
  30539. class CubicInterpolant extends Interpolant {
  30540. /**
  30541. * Constructs a new cubic interpolant.
  30542. *
  30543. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30544. * @param {TypedArray} sampleValues - The sample values.
  30545. * @param {number} sampleSize - The sample size
  30546. * @param {TypedArray} [resultBuffer] - The result buffer.
  30547. */
  30548. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30549. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30550. this._weightPrev = -0;
  30551. this._offsetPrev = -0;
  30552. this._weightNext = -0;
  30553. this._offsetNext = -0;
  30554. this.DefaultSettings_ = {
  30555. endingStart: ZeroCurvatureEnding,
  30556. endingEnd: ZeroCurvatureEnding
  30557. };
  30558. }
  30559. intervalChanged_( i1, t0, t1 ) {
  30560. const pp = this.parameterPositions;
  30561. let iPrev = i1 - 2,
  30562. iNext = i1 + 1,
  30563. tPrev = pp[ iPrev ],
  30564. tNext = pp[ iNext ];
  30565. if ( tPrev === undefined ) {
  30566. switch ( this.getSettings_().endingStart ) {
  30567. case ZeroSlopeEnding:
  30568. // f'(t0) = 0
  30569. iPrev = i1;
  30570. tPrev = 2 * t0 - t1;
  30571. break;
  30572. case WrapAroundEnding:
  30573. // use the other end of the curve
  30574. iPrev = pp.length - 2;
  30575. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  30576. break;
  30577. default: // ZeroCurvatureEnding
  30578. // f''(t0) = 0 a.k.a. Natural Spline
  30579. iPrev = i1;
  30580. tPrev = t1;
  30581. }
  30582. }
  30583. if ( tNext === undefined ) {
  30584. switch ( this.getSettings_().endingEnd ) {
  30585. case ZeroSlopeEnding:
  30586. // f'(tN) = 0
  30587. iNext = i1;
  30588. tNext = 2 * t1 - t0;
  30589. break;
  30590. case WrapAroundEnding:
  30591. // use the other end of the curve
  30592. iNext = 1;
  30593. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  30594. break;
  30595. default: // ZeroCurvatureEnding
  30596. // f''(tN) = 0, a.k.a. Natural Spline
  30597. iNext = i1 - 1;
  30598. tNext = t0;
  30599. }
  30600. }
  30601. const halfDt = ( t1 - t0 ) * 0.5,
  30602. stride = this.valueSize;
  30603. this._weightPrev = halfDt / ( t0 - tPrev );
  30604. this._weightNext = halfDt / ( tNext - t1 );
  30605. this._offsetPrev = iPrev * stride;
  30606. this._offsetNext = iNext * stride;
  30607. }
  30608. interpolate_( i1, t0, t, t1 ) {
  30609. const result = this.resultBuffer,
  30610. values = this.sampleValues,
  30611. stride = this.valueSize,
  30612. o1 = i1 * stride, o0 = o1 - stride,
  30613. oP = this._offsetPrev, oN = this._offsetNext,
  30614. wP = this._weightPrev, wN = this._weightNext,
  30615. p = ( t - t0 ) / ( t1 - t0 ),
  30616. pp = p * p,
  30617. ppp = pp * p;
  30618. // evaluate polynomials
  30619. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  30620. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  30621. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  30622. const sN = wN * ppp - wN * pp;
  30623. // combine data linearly
  30624. for ( let i = 0; i !== stride; ++ i ) {
  30625. result[ i ] =
  30626. sP * values[ oP + i ] +
  30627. s0 * values[ o0 + i ] +
  30628. s1 * values[ o1 + i ] +
  30629. sN * values[ oN + i ];
  30630. }
  30631. return result;
  30632. }
  30633. }
  30634. /**
  30635. * A basic linear interpolant.
  30636. *
  30637. * @augments Interpolant
  30638. */
  30639. class LinearInterpolant extends Interpolant {
  30640. /**
  30641. * Constructs a new linear interpolant.
  30642. *
  30643. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30644. * @param {TypedArray} sampleValues - The sample values.
  30645. * @param {number} sampleSize - The sample size
  30646. * @param {TypedArray} [resultBuffer] - The result buffer.
  30647. */
  30648. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30649. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30650. }
  30651. interpolate_( i1, t0, t, t1 ) {
  30652. const result = this.resultBuffer,
  30653. values = this.sampleValues,
  30654. stride = this.valueSize,
  30655. offset1 = i1 * stride,
  30656. offset0 = offset1 - stride,
  30657. weight1 = ( t - t0 ) / ( t1 - t0 ),
  30658. weight0 = 1 - weight1;
  30659. for ( let i = 0; i !== stride; ++ i ) {
  30660. result[ i ] =
  30661. values[ offset0 + i ] * weight0 +
  30662. values[ offset1 + i ] * weight1;
  30663. }
  30664. return result;
  30665. }
  30666. }
  30667. /**
  30668. * Interpolant that evaluates to the sample value at the position preceding
  30669. * the parameter.
  30670. *
  30671. * @augments Interpolant
  30672. */
  30673. class DiscreteInterpolant extends Interpolant {
  30674. /**
  30675. * Constructs a new discrete interpolant.
  30676. *
  30677. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30678. * @param {TypedArray} sampleValues - The sample values.
  30679. * @param {number} sampleSize - The sample size
  30680. * @param {TypedArray} [resultBuffer] - The result buffer.
  30681. */
  30682. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30683. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30684. }
  30685. interpolate_( i1 /*, t0, t, t1 */ ) {
  30686. return this.copySampleValue_( i1 - 1 );
  30687. }
  30688. }
  30689. /**
  30690. * Represents s a timed sequence of keyframes, which are composed of lists of
  30691. * times and related values, and which are used to animate a specific property
  30692. * of an object.
  30693. */
  30694. class KeyframeTrack {
  30695. /**
  30696. * Constructs a new keyframe track.
  30697. *
  30698. * @param {string} name - The keyframe track's name.
  30699. * @param {Array<number>} times - A list of keyframe times.
  30700. * @param {Array<number|string|boolean>} values - A list of keyframe values.
  30701. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30702. */
  30703. constructor( name, times, values, interpolation ) {
  30704. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  30705. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  30706. /**
  30707. * The track's name can refer to morph targets or bones or
  30708. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  30709. * for the forms of strings that can be parsed for property binding.
  30710. *
  30711. * @type {string}
  30712. */
  30713. this.name = name;
  30714. /**
  30715. * The keyframe times.
  30716. *
  30717. * @type {Float32Array}
  30718. */
  30719. this.times = convertArray( times, this.TimeBufferType );
  30720. /**
  30721. * The keyframe values.
  30722. *
  30723. * @type {Float32Array}
  30724. */
  30725. this.values = convertArray( values, this.ValueBufferType );
  30726. this.setInterpolation( interpolation || this.DefaultInterpolation );
  30727. }
  30728. /**
  30729. * Converts the keyframe track to JSON.
  30730. *
  30731. * @static
  30732. * @param {KeyframeTrack} track - The keyframe track to serialize.
  30733. * @return {Object} The serialized keyframe track as JSON.
  30734. */
  30735. static toJSON( track ) {
  30736. const trackType = track.constructor;
  30737. let json;
  30738. // derived classes can define a static toJSON method
  30739. if ( trackType.toJSON !== this.toJSON ) {
  30740. json = trackType.toJSON( track );
  30741. } else {
  30742. // by default, we assume the data can be serialized as-is
  30743. json = {
  30744. 'name': track.name,
  30745. 'times': convertArray( track.times, Array ),
  30746. 'values': convertArray( track.values, Array )
  30747. };
  30748. const interpolation = track.getInterpolation();
  30749. if ( interpolation !== track.DefaultInterpolation ) {
  30750. json.interpolation = interpolation;
  30751. }
  30752. }
  30753. json.type = track.ValueTypeName; // mandatory
  30754. return json;
  30755. }
  30756. /**
  30757. * Factory method for creating a new discrete interpolant.
  30758. *
  30759. * @static
  30760. * @param {TypedArray} [result] - The result buffer.
  30761. * @return {DiscreteInterpolant} The new interpolant.
  30762. */
  30763. InterpolantFactoryMethodDiscrete( result ) {
  30764. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  30765. }
  30766. /**
  30767. * Factory method for creating a new linear interpolant.
  30768. *
  30769. * @static
  30770. * @param {TypedArray} [result] - The result buffer.
  30771. * @return {LinearInterpolant} The new interpolant.
  30772. */
  30773. InterpolantFactoryMethodLinear( result ) {
  30774. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  30775. }
  30776. /**
  30777. * Factory method for creating a new smooth interpolant.
  30778. *
  30779. * @static
  30780. * @param {TypedArray} [result] - The result buffer.
  30781. * @return {CubicInterpolant} The new interpolant.
  30782. */
  30783. InterpolantFactoryMethodSmooth( result ) {
  30784. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  30785. }
  30786. /**
  30787. * Defines the interpolation factor method for this keyframe track.
  30788. *
  30789. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} interpolation - The interpolation type.
  30790. * @return {KeyframeTrack} A reference to this keyframe track.
  30791. */
  30792. setInterpolation( interpolation ) {
  30793. let factoryMethod;
  30794. switch ( interpolation ) {
  30795. case InterpolateDiscrete:
  30796. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  30797. break;
  30798. case InterpolateLinear:
  30799. factoryMethod = this.InterpolantFactoryMethodLinear;
  30800. break;
  30801. case InterpolateSmooth:
  30802. factoryMethod = this.InterpolantFactoryMethodSmooth;
  30803. break;
  30804. }
  30805. if ( factoryMethod === undefined ) {
  30806. const message = 'unsupported interpolation for ' +
  30807. this.ValueTypeName + ' keyframe track named ' + this.name;
  30808. if ( this.createInterpolant === undefined ) {
  30809. // fall back to default, unless the default itself is messed up
  30810. if ( interpolation !== this.DefaultInterpolation ) {
  30811. this.setInterpolation( this.DefaultInterpolation );
  30812. } else {
  30813. throw new Error( message ); // fatal, in this case
  30814. }
  30815. }
  30816. console.warn( 'THREE.KeyframeTrack:', message );
  30817. return this;
  30818. }
  30819. this.createInterpolant = factoryMethod;
  30820. return this;
  30821. }
  30822. /**
  30823. * Returns the current interpolation type.
  30824. *
  30825. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} The interpolation type.
  30826. */
  30827. getInterpolation() {
  30828. switch ( this.createInterpolant ) {
  30829. case this.InterpolantFactoryMethodDiscrete:
  30830. return InterpolateDiscrete;
  30831. case this.InterpolantFactoryMethodLinear:
  30832. return InterpolateLinear;
  30833. case this.InterpolantFactoryMethodSmooth:
  30834. return InterpolateSmooth;
  30835. }
  30836. }
  30837. /**
  30838. * Returns the value size.
  30839. *
  30840. * @return {number} The value size.
  30841. */
  30842. getValueSize() {
  30843. return this.values.length / this.times.length;
  30844. }
  30845. /**
  30846. * Moves all keyframes either forward or backward in time.
  30847. *
  30848. * @param {number} timeOffset - The offset to move the time values.
  30849. * @return {KeyframeTrack} A reference to this keyframe track.
  30850. */
  30851. shift( timeOffset ) {
  30852. if ( timeOffset !== 0.0 ) {
  30853. const times = this.times;
  30854. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30855. times[ i ] += timeOffset;
  30856. }
  30857. }
  30858. return this;
  30859. }
  30860. /**
  30861. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  30862. *
  30863. * @param {number} timeScale - The time scale.
  30864. * @return {KeyframeTrack} A reference to this keyframe track.
  30865. */
  30866. scale( timeScale ) {
  30867. if ( timeScale !== 1.0 ) {
  30868. const times = this.times;
  30869. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30870. times[ i ] *= timeScale;
  30871. }
  30872. }
  30873. return this;
  30874. }
  30875. /**
  30876. * Removes keyframes before and after animation without changing any values within the defined time range.
  30877. *
  30878. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  30879. * keys this will change their values
  30880. *
  30881. * @param {number} startTime - The start time.
  30882. * @param {number} endTime - The end time.
  30883. * @return {KeyframeTrack} A reference to this keyframe track.
  30884. */
  30885. trim( startTime, endTime ) {
  30886. const times = this.times,
  30887. nKeys = times.length;
  30888. let from = 0,
  30889. to = nKeys - 1;
  30890. while ( from !== nKeys && times[ from ] < startTime ) {
  30891. ++ from;
  30892. }
  30893. while ( to !== -1 && times[ to ] > endTime ) {
  30894. -- to;
  30895. }
  30896. ++ to; // inclusive -> exclusive bound
  30897. if ( from !== 0 || to !== nKeys ) {
  30898. // empty tracks are forbidden, so keep at least one keyframe
  30899. if ( from >= to ) {
  30900. to = Math.max( to, 1 );
  30901. from = to - 1;
  30902. }
  30903. const stride = this.getValueSize();
  30904. this.times = times.slice( from, to );
  30905. this.values = this.values.slice( from * stride, to * stride );
  30906. }
  30907. return this;
  30908. }
  30909. /**
  30910. * Performs minimal validation on the keyframe track. Returns `true` if the values
  30911. * are valid.
  30912. *
  30913. * @return {boolean} Whether the keyframes are valid or not.
  30914. */
  30915. validate() {
  30916. let valid = true;
  30917. const valueSize = this.getValueSize();
  30918. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  30919. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  30920. valid = false;
  30921. }
  30922. const times = this.times,
  30923. values = this.values,
  30924. nKeys = times.length;
  30925. if ( nKeys === 0 ) {
  30926. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  30927. valid = false;
  30928. }
  30929. let prevTime = null;
  30930. for ( let i = 0; i !== nKeys; i ++ ) {
  30931. const currTime = times[ i ];
  30932. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  30933. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  30934. valid = false;
  30935. break;
  30936. }
  30937. if ( prevTime !== null && prevTime > currTime ) {
  30938. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  30939. valid = false;
  30940. break;
  30941. }
  30942. prevTime = currTime;
  30943. }
  30944. if ( values !== undefined ) {
  30945. if ( isTypedArray( values ) ) {
  30946. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  30947. const value = values[ i ];
  30948. if ( isNaN( value ) ) {
  30949. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  30950. valid = false;
  30951. break;
  30952. }
  30953. }
  30954. }
  30955. }
  30956. return valid;
  30957. }
  30958. /**
  30959. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  30960. * common in morph target sequences).
  30961. *
  30962. * @return {AnimationClip} A reference to this animation clip.
  30963. */
  30964. optimize() {
  30965. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  30966. // times or values may be shared with other tracks, so overwriting is unsafe
  30967. const times = this.times.slice(),
  30968. values = this.values.slice(),
  30969. stride = this.getValueSize(),
  30970. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  30971. lastIndex = times.length - 1;
  30972. let writeIndex = 1;
  30973. for ( let i = 1; i < lastIndex; ++ i ) {
  30974. let keep = false;
  30975. const time = times[ i ];
  30976. const timeNext = times[ i + 1 ];
  30977. // remove adjacent keyframes scheduled at the same time
  30978. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  30979. if ( ! smoothInterpolation ) {
  30980. // remove unnecessary keyframes same as their neighbors
  30981. const offset = i * stride,
  30982. offsetP = offset - stride,
  30983. offsetN = offset + stride;
  30984. for ( let j = 0; j !== stride; ++ j ) {
  30985. const value = values[ offset + j ];
  30986. if ( value !== values[ offsetP + j ] ||
  30987. value !== values[ offsetN + j ] ) {
  30988. keep = true;
  30989. break;
  30990. }
  30991. }
  30992. } else {
  30993. keep = true;
  30994. }
  30995. }
  30996. // in-place compaction
  30997. if ( keep ) {
  30998. if ( i !== writeIndex ) {
  30999. times[ writeIndex ] = times[ i ];
  31000. const readOffset = i * stride,
  31001. writeOffset = writeIndex * stride;
  31002. for ( let j = 0; j !== stride; ++ j ) {
  31003. values[ writeOffset + j ] = values[ readOffset + j ];
  31004. }
  31005. }
  31006. ++ writeIndex;
  31007. }
  31008. }
  31009. // flush last keyframe (compaction looks ahead)
  31010. if ( lastIndex > 0 ) {
  31011. times[ writeIndex ] = times[ lastIndex ];
  31012. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  31013. values[ writeOffset + j ] = values[ readOffset + j ];
  31014. }
  31015. ++ writeIndex;
  31016. }
  31017. if ( writeIndex !== times.length ) {
  31018. this.times = times.slice( 0, writeIndex );
  31019. this.values = values.slice( 0, writeIndex * stride );
  31020. } else {
  31021. this.times = times;
  31022. this.values = values;
  31023. }
  31024. return this;
  31025. }
  31026. /**
  31027. * Returns a new keyframe track with copied values from this instance.
  31028. *
  31029. * @return {KeyframeTrack} A clone of this instance.
  31030. */
  31031. clone() {
  31032. const times = this.times.slice();
  31033. const values = this.values.slice();
  31034. const TypedKeyframeTrack = this.constructor;
  31035. const track = new TypedKeyframeTrack( this.name, times, values );
  31036. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  31037. track.createInterpolant = this.createInterpolant;
  31038. return track;
  31039. }
  31040. }
  31041. /**
  31042. * The value type name.
  31043. *
  31044. * @type {String}
  31045. * @default ''
  31046. */
  31047. KeyframeTrack.prototype.ValueTypeName = '';
  31048. /**
  31049. * The time buffer type of this keyframe track.
  31050. *
  31051. * @type {TypedArray|Array}
  31052. * @default Float32Array.constructor
  31053. */
  31054. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  31055. /**
  31056. * The value buffer type of this keyframe track.
  31057. *
  31058. * @type {TypedArray|Array}
  31059. * @default Float32Array.constructor
  31060. */
  31061. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  31062. /**
  31063. * The default interpolation type of this keyframe track.
  31064. *
  31065. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31066. * @default InterpolateLinear
  31067. */
  31068. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  31069. /**
  31070. * A track for boolean keyframe values.
  31071. *
  31072. * @augments KeyframeTrack
  31073. */
  31074. class BooleanKeyframeTrack extends KeyframeTrack {
  31075. /**
  31076. * Constructs a new boolean keyframe track.
  31077. *
  31078. * This keyframe track type has no `interpolation` parameter because the
  31079. * interpolation is always discrete.
  31080. *
  31081. * @param {string} name - The keyframe track's name.
  31082. * @param {Array<number>} times - A list of keyframe times.
  31083. * @param {Array<boolean>} values - A list of keyframe values.
  31084. */
  31085. constructor( name, times, values ) {
  31086. super( name, times, values );
  31087. }
  31088. }
  31089. /**
  31090. * The value type name.
  31091. *
  31092. * @type {String}
  31093. * @default 'bool'
  31094. */
  31095. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  31096. /**
  31097. * The value buffer type of this keyframe track.
  31098. *
  31099. * @type {TypedArray|Array}
  31100. * @default Array.constructor
  31101. */
  31102. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  31103. /**
  31104. * The default interpolation type of this keyframe track.
  31105. *
  31106. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31107. * @default InterpolateDiscrete
  31108. */
  31109. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31110. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31111. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31112. /**
  31113. * A track for color keyframe values.
  31114. *
  31115. * @augments KeyframeTrack
  31116. */
  31117. class ColorKeyframeTrack extends KeyframeTrack {
  31118. /**
  31119. * Constructs a new color keyframe track.
  31120. *
  31121. * @param {string} name - The keyframe track's name.
  31122. * @param {Array<number>} times - A list of keyframe times.
  31123. * @param {Array<number>} values - A list of keyframe values.
  31124. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31125. */
  31126. constructor( name, times, values, interpolation ) {
  31127. super( name, times, values, interpolation );
  31128. }
  31129. }
  31130. /**
  31131. * The value type name.
  31132. *
  31133. * @type {String}
  31134. * @default 'color'
  31135. */
  31136. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31137. /**
  31138. * A track for numeric keyframe values.
  31139. *
  31140. * @augments KeyframeTrack
  31141. */
  31142. class NumberKeyframeTrack extends KeyframeTrack {
  31143. /**
  31144. * Constructs a new number keyframe track.
  31145. *
  31146. * @param {string} name - The keyframe track's name.
  31147. * @param {Array<number>} times - A list of keyframe times.
  31148. * @param {Array<number>} values - A list of keyframe values.
  31149. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31150. */
  31151. constructor( name, times, values, interpolation ) {
  31152. super( name, times, values, interpolation );
  31153. }
  31154. }
  31155. /**
  31156. * The value type name.
  31157. *
  31158. * @type {String}
  31159. * @default 'number'
  31160. */
  31161. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31162. /**
  31163. * Spherical linear unit quaternion interpolant.
  31164. *
  31165. * @augments Interpolant
  31166. */
  31167. class QuaternionLinearInterpolant extends Interpolant {
  31168. /**
  31169. * Constructs a new SLERP interpolant.
  31170. *
  31171. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31172. * @param {TypedArray} sampleValues - The sample values.
  31173. * @param {number} sampleSize - The sample size
  31174. * @param {TypedArray} [resultBuffer] - The result buffer.
  31175. */
  31176. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31177. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31178. }
  31179. interpolate_( i1, t0, t, t1 ) {
  31180. const result = this.resultBuffer,
  31181. values = this.sampleValues,
  31182. stride = this.valueSize,
  31183. alpha = ( t - t0 ) / ( t1 - t0 );
  31184. let offset = i1 * stride;
  31185. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31186. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31187. }
  31188. return result;
  31189. }
  31190. }
  31191. /**
  31192. * A track for Quaternion keyframe values.
  31193. *
  31194. * @augments KeyframeTrack
  31195. */
  31196. class QuaternionKeyframeTrack extends KeyframeTrack {
  31197. /**
  31198. * Constructs a new Quaternion keyframe track.
  31199. *
  31200. * @param {string} name - The keyframe track's name.
  31201. * @param {Array<number>} times - A list of keyframe times.
  31202. * @param {Array<number>} values - A list of keyframe values.
  31203. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31204. */
  31205. constructor( name, times, values, interpolation ) {
  31206. super( name, times, values, interpolation );
  31207. }
  31208. /**
  31209. * Overwritten so the method returns Quaternion based interpolant.
  31210. *
  31211. * @static
  31212. * @param {TypedArray} [result] - The result buffer.
  31213. * @return {QuaternionLinearInterpolant} The new interpolant.
  31214. */
  31215. InterpolantFactoryMethodLinear( result ) {
  31216. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31217. }
  31218. }
  31219. /**
  31220. * The value type name.
  31221. *
  31222. * @type {String}
  31223. * @default 'quaternion'
  31224. */
  31225. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31226. // ValueBufferType is inherited
  31227. // DefaultInterpolation is inherited;
  31228. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31229. /**
  31230. * A track for string keyframe values.
  31231. *
  31232. * @augments KeyframeTrack
  31233. */
  31234. class StringKeyframeTrack extends KeyframeTrack {
  31235. /**
  31236. * Constructs a new string keyframe track.
  31237. *
  31238. * This keyframe track type has no `interpolation` parameter because the
  31239. * interpolation is always discrete.
  31240. *
  31241. * @param {string} name - The keyframe track's name.
  31242. * @param {Array<number>} times - A list of keyframe times.
  31243. * @param {Array<string>} values - A list of keyframe values.
  31244. */
  31245. constructor( name, times, values ) {
  31246. super( name, times, values );
  31247. }
  31248. }
  31249. /**
  31250. * The value type name.
  31251. *
  31252. * @type {String}
  31253. * @default 'string'
  31254. */
  31255. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31256. /**
  31257. * The value buffer type of this keyframe track.
  31258. *
  31259. * @type {TypedArray|Array}
  31260. * @default Array.constructor
  31261. */
  31262. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31263. /**
  31264. * The default interpolation type of this keyframe track.
  31265. *
  31266. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31267. * @default InterpolateDiscrete
  31268. */
  31269. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31270. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31271. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31272. /**
  31273. * A track for vector keyframe values.
  31274. *
  31275. * @augments KeyframeTrack
  31276. */
  31277. class VectorKeyframeTrack extends KeyframeTrack {
  31278. /**
  31279. * Constructs a new vector keyframe track.
  31280. *
  31281. * @param {string} name - The keyframe track's name.
  31282. * @param {Array<number>} times - A list of keyframe times.
  31283. * @param {Array<number>} values - A list of keyframe values.
  31284. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31285. */
  31286. constructor( name, times, values, interpolation ) {
  31287. super( name, times, values, interpolation );
  31288. }
  31289. }
  31290. /**
  31291. * The value type name.
  31292. *
  31293. * @type {String}
  31294. * @default 'vector'
  31295. */
  31296. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31297. /**
  31298. * A reusable set of keyframe tracks which represent an animation.
  31299. */
  31300. class AnimationClip {
  31301. /**
  31302. * Constructs a new animation clip.
  31303. *
  31304. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31305. * use the static interface of this class for creating clips. In most cases though, animation clips
  31306. * will automatically be created by loaders when importing animated 3D assets.
  31307. *
  31308. * @param {string} [name=''] - The clip's name.
  31309. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31310. * the duration will be calculated from the passed keyframes.
  31311. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31312. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31313. * is blended/combined when two or more animations are simultaneously played.
  31314. */
  31315. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31316. /**
  31317. * The clip's name.
  31318. *
  31319. * @type {string}
  31320. */
  31321. this.name = name;
  31322. /**
  31323. * An array of keyframe tracks.
  31324. *
  31325. * @type {Array<KeyframeTrack>}
  31326. */
  31327. this.tracks = tracks;
  31328. /**
  31329. * The clip's duration in seconds.
  31330. *
  31331. * @type {number}
  31332. */
  31333. this.duration = duration;
  31334. /**
  31335. * Defines how the animation is blended/combined when two or more animations
  31336. * are simultaneously played.
  31337. *
  31338. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31339. */
  31340. this.blendMode = blendMode;
  31341. /**
  31342. * The UUID of the animation clip.
  31343. *
  31344. * @type {string}
  31345. * @readonly
  31346. */
  31347. this.uuid = generateUUID();
  31348. /**
  31349. * An object that can be used to store custom data about the animation clip.
  31350. * It should not hold references to functions as these will not be cloned.
  31351. *
  31352. * @type {Object}
  31353. */
  31354. this.userData = {};
  31355. // this means it should figure out its duration by scanning the tracks
  31356. if ( this.duration < 0 ) {
  31357. this.resetDuration();
  31358. }
  31359. }
  31360. /**
  31361. * Factory method for creating an animation clip from the given JSON.
  31362. *
  31363. * @static
  31364. * @param {Object} json - The serialized animation clip.
  31365. * @return {AnimationClip} The new animation clip.
  31366. */
  31367. static parse( json ) {
  31368. const tracks = [],
  31369. jsonTracks = json.tracks,
  31370. frameTime = 1.0 / ( json.fps || 1.0 );
  31371. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31372. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31373. }
  31374. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31375. clip.uuid = json.uuid;
  31376. clip.userData = JSON.parse( json.userData || '{}' );
  31377. return clip;
  31378. }
  31379. /**
  31380. * Serializes the given animation clip into JSON.
  31381. *
  31382. * @static
  31383. * @param {AnimationClip} clip - The animation clip to serialize.
  31384. * @return {Object} The JSON object.
  31385. */
  31386. static toJSON( clip ) {
  31387. const tracks = [],
  31388. clipTracks = clip.tracks;
  31389. const json = {
  31390. 'name': clip.name,
  31391. 'duration': clip.duration,
  31392. 'tracks': tracks,
  31393. 'uuid': clip.uuid,
  31394. 'blendMode': clip.blendMode,
  31395. 'userData': JSON.stringify( clip.userData ),
  31396. };
  31397. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31398. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31399. }
  31400. return json;
  31401. }
  31402. /**
  31403. * Returns a new animation clip from the passed morph targets array of a
  31404. * geometry, taking a name and the number of frames per second.
  31405. *
  31406. * Note: The fps parameter is required, but the animation speed can be
  31407. * overridden via {@link AnimationAction#setDuration}.
  31408. *
  31409. * @static
  31410. * @param {string} name - The name of the animation clip.
  31411. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31412. * @param {number} fps - The Frames-Per-Second value.
  31413. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31414. * @return {AnimationClip} The new animation clip.
  31415. */
  31416. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  31417. const numMorphTargets = morphTargetSequence.length;
  31418. const tracks = [];
  31419. for ( let i = 0; i < numMorphTargets; i ++ ) {
  31420. let times = [];
  31421. let values = [];
  31422. times.push(
  31423. ( i + numMorphTargets - 1 ) % numMorphTargets,
  31424. i,
  31425. ( i + 1 ) % numMorphTargets );
  31426. values.push( 0, 1, 0 );
  31427. const order = getKeyframeOrder( times );
  31428. times = sortedArray( times, 1, order );
  31429. values = sortedArray( values, 1, order );
  31430. // if there is a key at the first frame, duplicate it as the
  31431. // last frame as well for perfect loop.
  31432. if ( ! noLoop && times[ 0 ] === 0 ) {
  31433. times.push( numMorphTargets );
  31434. values.push( values[ 0 ] );
  31435. }
  31436. tracks.push(
  31437. new NumberKeyframeTrack(
  31438. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  31439. times, values
  31440. ).scale( 1.0 / fps ) );
  31441. }
  31442. return new this( name, -1, tracks );
  31443. }
  31444. /**
  31445. * Searches for an animation clip by name, taking as its first parameter
  31446. * either an array of clips, or a mesh or geometry that contains an
  31447. * array named "animations" property.
  31448. *
  31449. * @static
  31450. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  31451. * @param {string} name - The name to search for.
  31452. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  31453. */
  31454. static findByName( objectOrClipArray, name ) {
  31455. let clipArray = objectOrClipArray;
  31456. if ( ! Array.isArray( objectOrClipArray ) ) {
  31457. const o = objectOrClipArray;
  31458. clipArray = o.geometry && o.geometry.animations || o.animations;
  31459. }
  31460. for ( let i = 0; i < clipArray.length; i ++ ) {
  31461. if ( clipArray[ i ].name === name ) {
  31462. return clipArray[ i ];
  31463. }
  31464. }
  31465. return null;
  31466. }
  31467. /**
  31468. * Returns an array of new AnimationClips created from the morph target
  31469. * sequences of a geometry, trying to sort morph target names into
  31470. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  31471. *
  31472. * See {@link MD2Loader#parse} as an example for how the method should be used.
  31473. *
  31474. * @static
  31475. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  31476. * @param {number} fps - The Frames-Per-Second value.
  31477. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31478. * @return {Array<AnimationClip>} An array of new animation clips.
  31479. */
  31480. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  31481. const animationToMorphTargets = {};
  31482. // tested with https://regex101.com/ on trick sequences
  31483. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  31484. const pattern = /^([\w-]*?)([\d]+)$/;
  31485. // sort morph target names into animation groups based
  31486. // patterns like Walk_001, Walk_002, Run_001, Run_002
  31487. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  31488. const morphTarget = morphTargets[ i ];
  31489. const parts = morphTarget.name.match( pattern );
  31490. if ( parts && parts.length > 1 ) {
  31491. const name = parts[ 1 ];
  31492. let animationMorphTargets = animationToMorphTargets[ name ];
  31493. if ( ! animationMorphTargets ) {
  31494. animationToMorphTargets[ name ] = animationMorphTargets = [];
  31495. }
  31496. animationMorphTargets.push( morphTarget );
  31497. }
  31498. }
  31499. const clips = [];
  31500. for ( const name in animationToMorphTargets ) {
  31501. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  31502. }
  31503. return clips;
  31504. }
  31505. /**
  31506. * Parses the `animation.hierarchy` format and returns a new animation clip.
  31507. *
  31508. * @static
  31509. * @deprecated since r175.
  31510. * @param {Object} animation - A serialized animation clip as JSON.
  31511. * @param {Array<Bones>} bones - An array of bones.
  31512. * @return {?AnimationClip} The new animation clip.
  31513. */
  31514. static parseAnimation( animation, bones ) {
  31515. console.warn( 'THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  31516. if ( ! animation ) {
  31517. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  31518. return null;
  31519. }
  31520. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  31521. // only return track if there are actually keys.
  31522. if ( animationKeys.length !== 0 ) {
  31523. const times = [];
  31524. const values = [];
  31525. flattenJSON( animationKeys, times, values, propertyName );
  31526. // empty keys are filtered out, so check again
  31527. if ( times.length !== 0 ) {
  31528. destTracks.push( new trackType( trackName, times, values ) );
  31529. }
  31530. }
  31531. };
  31532. const tracks = [];
  31533. const clipName = animation.name || 'default';
  31534. const fps = animation.fps || 30;
  31535. const blendMode = animation.blendMode;
  31536. // automatic length determination in AnimationClip.
  31537. let duration = animation.length || -1;
  31538. const hierarchyTracks = animation.hierarchy || [];
  31539. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  31540. const animationKeys = hierarchyTracks[ h ].keys;
  31541. // skip empty tracks
  31542. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  31543. // process morph targets
  31544. if ( animationKeys[ 0 ].morphTargets ) {
  31545. // figure out all morph targets used in this track
  31546. const morphTargetNames = {};
  31547. let k;
  31548. for ( k = 0; k < animationKeys.length; k ++ ) {
  31549. if ( animationKeys[ k ].morphTargets ) {
  31550. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  31551. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  31552. }
  31553. }
  31554. }
  31555. // create a track for each morph target with all zero
  31556. // morphTargetInfluences except for the keys in which
  31557. // the morphTarget is named.
  31558. for ( const morphTargetName in morphTargetNames ) {
  31559. const times = [];
  31560. const values = [];
  31561. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  31562. const animationKey = animationKeys[ k ];
  31563. times.push( animationKey.time );
  31564. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  31565. }
  31566. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  31567. }
  31568. duration = morphTargetNames.length * fps;
  31569. } else {
  31570. // ...assume skeletal animation
  31571. const boneName = '.bones[' + bones[ h ].name + ']';
  31572. addNonemptyTrack(
  31573. VectorKeyframeTrack, boneName + '.position',
  31574. animationKeys, 'pos', tracks );
  31575. addNonemptyTrack(
  31576. QuaternionKeyframeTrack, boneName + '.quaternion',
  31577. animationKeys, 'rot', tracks );
  31578. addNonemptyTrack(
  31579. VectorKeyframeTrack, boneName + '.scale',
  31580. animationKeys, 'scl', tracks );
  31581. }
  31582. }
  31583. if ( tracks.length === 0 ) {
  31584. return null;
  31585. }
  31586. const clip = new this( clipName, duration, tracks, blendMode );
  31587. return clip;
  31588. }
  31589. /**
  31590. * Sets the duration of this clip to the duration of its longest keyframe track.
  31591. *
  31592. * @return {AnimationClip} A reference to this animation clip.
  31593. */
  31594. resetDuration() {
  31595. const tracks = this.tracks;
  31596. let duration = 0;
  31597. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  31598. const track = this.tracks[ i ];
  31599. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  31600. }
  31601. this.duration = duration;
  31602. return this;
  31603. }
  31604. /**
  31605. * Trims all tracks to the clip's duration.
  31606. *
  31607. * @return {AnimationClip} A reference to this animation clip.
  31608. */
  31609. trim() {
  31610. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31611. this.tracks[ i ].trim( 0, this.duration );
  31612. }
  31613. return this;
  31614. }
  31615. /**
  31616. * Performs minimal validation on each track in the clip. Returns `true` if all
  31617. * tracks are valid.
  31618. *
  31619. * @return {boolean} Whether the clip's keyframes are valid or not.
  31620. */
  31621. validate() {
  31622. let valid = true;
  31623. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31624. valid = valid && this.tracks[ i ].validate();
  31625. }
  31626. return valid;
  31627. }
  31628. /**
  31629. * Optimizes each track by removing equivalent sequential keys (which are
  31630. * common in morph target sequences).
  31631. *
  31632. * @return {AnimationClip} A reference to this animation clip.
  31633. */
  31634. optimize() {
  31635. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31636. this.tracks[ i ].optimize();
  31637. }
  31638. return this;
  31639. }
  31640. /**
  31641. * Returns a new animation clip with copied values from this instance.
  31642. *
  31643. * @return {AnimationClip} A clone of this instance.
  31644. */
  31645. clone() {
  31646. const tracks = [];
  31647. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31648. tracks.push( this.tracks[ i ].clone() );
  31649. }
  31650. const clip = new this.constructor( this.name, this.duration, tracks, this.blendMode );
  31651. clip.userData = JSON.parse( JSON.stringify( this.userData ) );
  31652. return clip;
  31653. }
  31654. /**
  31655. * Serializes this animation clip into JSON.
  31656. *
  31657. * @return {Object} The JSON object.
  31658. */
  31659. toJSON() {
  31660. return this.constructor.toJSON( this );
  31661. }
  31662. }
  31663. function getTrackTypeForValueTypeName( typeName ) {
  31664. switch ( typeName.toLowerCase() ) {
  31665. case 'scalar':
  31666. case 'double':
  31667. case 'float':
  31668. case 'number':
  31669. case 'integer':
  31670. return NumberKeyframeTrack;
  31671. case 'vector':
  31672. case 'vector2':
  31673. case 'vector3':
  31674. case 'vector4':
  31675. return VectorKeyframeTrack;
  31676. case 'color':
  31677. return ColorKeyframeTrack;
  31678. case 'quaternion':
  31679. return QuaternionKeyframeTrack;
  31680. case 'bool':
  31681. case 'boolean':
  31682. return BooleanKeyframeTrack;
  31683. case 'string':
  31684. return StringKeyframeTrack;
  31685. }
  31686. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  31687. }
  31688. function parseKeyframeTrack( json ) {
  31689. if ( json.type === undefined ) {
  31690. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  31691. }
  31692. const trackType = getTrackTypeForValueTypeName( json.type );
  31693. if ( json.times === undefined ) {
  31694. const times = [], values = [];
  31695. flattenJSON( json.keys, times, values, 'value' );
  31696. json.times = times;
  31697. json.values = values;
  31698. }
  31699. // derived classes can define a static parse method
  31700. if ( trackType.parse !== undefined ) {
  31701. return trackType.parse( json );
  31702. } else {
  31703. // by default, we assume a constructor compatible with the base
  31704. return new trackType( json.name, json.times, json.values, json.interpolation );
  31705. }
  31706. }
  31707. /**
  31708. * @class
  31709. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  31710. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  31711. * @hideconstructor
  31712. */
  31713. const Cache = {
  31714. /**
  31715. * Whether caching is enabled or not.
  31716. *
  31717. * @static
  31718. * @type {boolean}
  31719. * @default false
  31720. */
  31721. enabled: false,
  31722. /**
  31723. * A dictionary that holds cached files.
  31724. *
  31725. * @static
  31726. * @type {Object<string,Object>}
  31727. */
  31728. files: {},
  31729. /**
  31730. * Adds a cache entry with a key to reference the file. If this key already
  31731. * holds a file, it is overwritten.
  31732. *
  31733. * @static
  31734. * @param {string} key - The key to reference the cached file.
  31735. * @param {Object} file - The file to be cached.
  31736. */
  31737. add: function ( key, file ) {
  31738. if ( this.enabled === false ) return;
  31739. // console.log( 'THREE.Cache', 'Adding key:', key );
  31740. this.files[ key ] = file;
  31741. },
  31742. /**
  31743. * Gets the cached value for the given key.
  31744. *
  31745. * @static
  31746. * @param {string} key - The key to reference the cached file.
  31747. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  31748. */
  31749. get: function ( key ) {
  31750. if ( this.enabled === false ) return;
  31751. // console.log( 'THREE.Cache', 'Checking key:', key );
  31752. return this.files[ key ];
  31753. },
  31754. /**
  31755. * Removes the cached file associated with the given key.
  31756. *
  31757. * @static
  31758. * @param {string} key - The key to reference the cached file.
  31759. */
  31760. remove: function ( key ) {
  31761. delete this.files[ key ];
  31762. },
  31763. /**
  31764. * Remove all values from the cache.
  31765. *
  31766. * @static
  31767. */
  31768. clear: function () {
  31769. this.files = {};
  31770. }
  31771. };
  31772. /**
  31773. * Handles and keeps track of loaded and pending data. A default global
  31774. * instance of this class is created and used by loaders if not supplied
  31775. * manually.
  31776. *
  31777. * In general that should be sufficient, however there are times when it can
  31778. * be useful to have separate loaders - for example if you want to show
  31779. * separate loading bars for objects and textures.
  31780. *
  31781. * ```js
  31782. * const manager = new THREE.LoadingManager();
  31783. * manager.onLoad = () => console.log( 'Loading complete!' );
  31784. *
  31785. * const loader1 = new OBJLoader( manager );
  31786. * const loader2 = new ColladaLoader( manager );
  31787. * ```
  31788. */
  31789. class LoadingManager {
  31790. /**
  31791. * Constructs a new loading manager.
  31792. *
  31793. * @param {Function} [onLoad] - Executes when all items have been loaded.
  31794. * @param {Function} [onProgress] - Executes when single items have been loaded.
  31795. * @param {Function} [onError] - Executes when an error occurs.
  31796. */
  31797. constructor( onLoad, onProgress, onError ) {
  31798. const scope = this;
  31799. let isLoading = false;
  31800. let itemsLoaded = 0;
  31801. let itemsTotal = 0;
  31802. let urlModifier = undefined;
  31803. const handlers = [];
  31804. // Refer to #5689 for the reason why we don't set .onStart
  31805. // in the constructor
  31806. /**
  31807. * Executes when an item starts loading.
  31808. *
  31809. * @type {Function|undefined}
  31810. * @default undefined
  31811. */
  31812. this.onStart = undefined;
  31813. /**
  31814. * Executes when all items have been loaded.
  31815. *
  31816. * @type {Function|undefined}
  31817. * @default undefined
  31818. */
  31819. this.onLoad = onLoad;
  31820. /**
  31821. * Executes when single items have been loaded.
  31822. *
  31823. * @type {Function|undefined}
  31824. * @default undefined
  31825. */
  31826. this.onProgress = onProgress;
  31827. /**
  31828. * Executes when an error occurs.
  31829. *
  31830. * @type {Function|undefined}
  31831. * @default undefined
  31832. */
  31833. this.onError = onError;
  31834. /**
  31835. * Used for aborting ongoing requests in loaders using this manager.
  31836. *
  31837. * @type {AbortController}
  31838. */
  31839. this.abortController = new AbortController();
  31840. /**
  31841. * This should be called by any loader using the manager when the loader
  31842. * starts loading an item.
  31843. *
  31844. * @param {string} url - The URL to load.
  31845. */
  31846. this.itemStart = function ( url ) {
  31847. itemsTotal ++;
  31848. if ( isLoading === false ) {
  31849. if ( scope.onStart !== undefined ) {
  31850. scope.onStart( url, itemsLoaded, itemsTotal );
  31851. }
  31852. }
  31853. isLoading = true;
  31854. };
  31855. /**
  31856. * This should be called by any loader using the manager when the loader
  31857. * ended loading an item.
  31858. *
  31859. * @param {string} url - The URL of the loaded item.
  31860. */
  31861. this.itemEnd = function ( url ) {
  31862. itemsLoaded ++;
  31863. if ( scope.onProgress !== undefined ) {
  31864. scope.onProgress( url, itemsLoaded, itemsTotal );
  31865. }
  31866. if ( itemsLoaded === itemsTotal ) {
  31867. isLoading = false;
  31868. if ( scope.onLoad !== undefined ) {
  31869. scope.onLoad();
  31870. }
  31871. }
  31872. };
  31873. /**
  31874. * This should be called by any loader using the manager when the loader
  31875. * encounters an error when loading an item.
  31876. *
  31877. * @param {string} url - The URL of the item that produces an error.
  31878. */
  31879. this.itemError = function ( url ) {
  31880. if ( scope.onError !== undefined ) {
  31881. scope.onError( url );
  31882. }
  31883. };
  31884. /**
  31885. * Given a URL, uses the URL modifier callback (if any) and returns a
  31886. * resolved URL. If no URL modifier is set, returns the original URL.
  31887. *
  31888. * @param {string} url - The URL to load.
  31889. * @return {string} The resolved URL.
  31890. */
  31891. this.resolveURL = function ( url ) {
  31892. if ( urlModifier ) {
  31893. return urlModifier( url );
  31894. }
  31895. return url;
  31896. };
  31897. /**
  31898. * If provided, the callback will be passed each resource URL before a
  31899. * request is sent. The callback may return the original URL, or a new URL to
  31900. * override loading behavior. This behavior can be used to load assets from
  31901. * .ZIP files, drag-and-drop APIs, and Data URIs.
  31902. *
  31903. * ```js
  31904. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  31905. *
  31906. * const manager = new THREE.LoadingManager();
  31907. *
  31908. * // Initialize loading manager with URL callback.
  31909. * const objectURLs = [];
  31910. * manager.setURLModifier( ( url ) => {
  31911. *
  31912. * url = URL.createObjectURL( blobs[ url ] );
  31913. * objectURLs.push( url );
  31914. * return url;
  31915. *
  31916. * } );
  31917. *
  31918. * // Load as usual, then revoke the blob URLs.
  31919. * const loader = new GLTFLoader( manager );
  31920. * loader.load( 'fish.gltf', (gltf) => {
  31921. *
  31922. * scene.add( gltf.scene );
  31923. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  31924. *
  31925. * } );
  31926. * ```
  31927. *
  31928. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  31929. * @return {LoadingManager} A reference to this loading manager.
  31930. */
  31931. this.setURLModifier = function ( transform ) {
  31932. urlModifier = transform;
  31933. return this;
  31934. };
  31935. /**
  31936. * Registers a loader with the given regular expression. Can be used to
  31937. * define what loader should be used in order to load specific files. A
  31938. * typical use case is to overwrite the default loader for textures.
  31939. *
  31940. * ```js
  31941. * // add handler for TGA textures
  31942. * manager.addHandler( /\.tga$/i, new TGALoader() );
  31943. * ```
  31944. *
  31945. * @param {string} regex - A regular expression.
  31946. * @param {Loader} loader - A loader that should handle matched cases.
  31947. * @return {LoadingManager} A reference to this loading manager.
  31948. */
  31949. this.addHandler = function ( regex, loader ) {
  31950. handlers.push( regex, loader );
  31951. return this;
  31952. };
  31953. /**
  31954. * Removes the loader for the given regular expression.
  31955. *
  31956. * @param {string} regex - A regular expression.
  31957. * @return {LoadingManager} A reference to this loading manager.
  31958. */
  31959. this.removeHandler = function ( regex ) {
  31960. const index = handlers.indexOf( regex );
  31961. if ( index !== -1 ) {
  31962. handlers.splice( index, 2 );
  31963. }
  31964. return this;
  31965. };
  31966. /**
  31967. * Can be used to retrieve the registered loader for the given file path.
  31968. *
  31969. * @param {string} file - The file path.
  31970. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  31971. */
  31972. this.getHandler = function ( file ) {
  31973. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  31974. const regex = handlers[ i ];
  31975. const loader = handlers[ i + 1 ];
  31976. if ( regex.global ) regex.lastIndex = 0; // see #17920
  31977. if ( regex.test( file ) ) {
  31978. return loader;
  31979. }
  31980. }
  31981. return null;
  31982. };
  31983. /**
  31984. * Can be used to abort ongoing loading requests in loaders using this manager.
  31985. * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()`
  31986. * is supported in the browser.
  31987. *
  31988. * @return {LoadingManager} A reference to this loading manager.
  31989. */
  31990. this.abort = function () {
  31991. this.abortController.abort();
  31992. this.abortController = new AbortController();
  31993. return this;
  31994. };
  31995. }
  31996. }
  31997. /**
  31998. * The global default loading manager.
  31999. *
  32000. * @constant
  32001. * @type {LoadingManager}
  32002. */
  32003. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  32004. /**
  32005. * Abstract base class for loaders.
  32006. *
  32007. * @abstract
  32008. */
  32009. class Loader {
  32010. /**
  32011. * Constructs a new loader.
  32012. *
  32013. * @param {LoadingManager} [manager] - The loading manager.
  32014. */
  32015. constructor( manager ) {
  32016. /**
  32017. * The loading manager.
  32018. *
  32019. * @type {LoadingManager}
  32020. * @default DefaultLoadingManager
  32021. */
  32022. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  32023. /**
  32024. * The crossOrigin string to implement CORS for loading the url from a
  32025. * different domain that allows CORS.
  32026. *
  32027. * @type {string}
  32028. * @default 'anonymous'
  32029. */
  32030. this.crossOrigin = 'anonymous';
  32031. /**
  32032. * Whether the XMLHttpRequest uses credentials.
  32033. *
  32034. * @type {boolean}
  32035. * @default false
  32036. */
  32037. this.withCredentials = false;
  32038. /**
  32039. * The base path from which the asset will be loaded.
  32040. *
  32041. * @type {string}
  32042. */
  32043. this.path = '';
  32044. /**
  32045. * The base path from which additional resources like textures will be loaded.
  32046. *
  32047. * @type {string}
  32048. */
  32049. this.resourcePath = '';
  32050. /**
  32051. * The [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  32052. * used in HTTP request.
  32053. *
  32054. * @type {Object<string, any>}
  32055. */
  32056. this.requestHeader = {};
  32057. }
  32058. /**
  32059. * This method needs to be implemented by all concrete loaders. It holds the
  32060. * logic for loading assets from the backend.
  32061. *
  32062. * @abstract
  32063. * @param {string} url - The path/URL of the file to be loaded.
  32064. * @param {Function} onLoad - Executed when the loading process has been finished.
  32065. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32066. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32067. */
  32068. load( /* url, onLoad, onProgress, onError */ ) {}
  32069. /**
  32070. * A async version of {@link Loader#load}.
  32071. *
  32072. * @param {string} url - The path/URL of the file to be loaded.
  32073. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32074. * @return {Promise} A Promise that resolves when the asset has been loaded.
  32075. */
  32076. loadAsync( url, onProgress ) {
  32077. const scope = this;
  32078. return new Promise( function ( resolve, reject ) {
  32079. scope.load( url, resolve, onProgress, reject );
  32080. } );
  32081. }
  32082. /**
  32083. * This method needs to be implemented by all concrete loaders. It holds the
  32084. * logic for parsing the asset into three.js entities.
  32085. *
  32086. * @abstract
  32087. * @param {any} data - The data to parse.
  32088. */
  32089. parse( /* data */ ) {}
  32090. /**
  32091. * Sets the `crossOrigin` String to implement CORS for loading the URL
  32092. * from a different domain that allows CORS.
  32093. *
  32094. * @param {string} crossOrigin - The `crossOrigin` value.
  32095. * @return {Loader} A reference to this instance.
  32096. */
  32097. setCrossOrigin( crossOrigin ) {
  32098. this.crossOrigin = crossOrigin;
  32099. return this;
  32100. }
  32101. /**
  32102. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  32103. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials}.
  32104. *
  32105. * Note: This setting has no effect if you are loading files locally or from the same domain.
  32106. *
  32107. * @param {boolean} value - The `withCredentials` value.
  32108. * @return {Loader} A reference to this instance.
  32109. */
  32110. setWithCredentials( value ) {
  32111. this.withCredentials = value;
  32112. return this;
  32113. }
  32114. /**
  32115. * Sets the base path for the asset.
  32116. *
  32117. * @param {string} path - The base path.
  32118. * @return {Loader} A reference to this instance.
  32119. */
  32120. setPath( path ) {
  32121. this.path = path;
  32122. return this;
  32123. }
  32124. /**
  32125. * Sets the base path for dependent resources like textures.
  32126. *
  32127. * @param {string} resourcePath - The resource path.
  32128. * @return {Loader} A reference to this instance.
  32129. */
  32130. setResourcePath( resourcePath ) {
  32131. this.resourcePath = resourcePath;
  32132. return this;
  32133. }
  32134. /**
  32135. * Sets the given request header.
  32136. *
  32137. * @param {Object} requestHeader - A [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  32138. * for configuring the HTTP request.
  32139. * @return {Loader} A reference to this instance.
  32140. */
  32141. setRequestHeader( requestHeader ) {
  32142. this.requestHeader = requestHeader;
  32143. return this;
  32144. }
  32145. /**
  32146. * This method can be implemented in loaders for aborting ongoing requests.
  32147. *
  32148. * @abstract
  32149. * @return {Loader} A reference to this instance.
  32150. */
  32151. abort() {
  32152. return this;
  32153. }
  32154. }
  32155. /**
  32156. * Callback for onProgress in loaders.
  32157. *
  32158. * @callback onProgressCallback
  32159. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32160. */
  32161. /**
  32162. * Callback for onError in loaders.
  32163. *
  32164. * @callback onErrorCallback
  32165. * @param {Error} error - The error which occurred during the loading process.
  32166. */
  32167. /**
  32168. * The default material name that is used by loaders
  32169. * when creating materials for loaded 3D objects.
  32170. *
  32171. * Note: Not all loaders might honor this setting.
  32172. *
  32173. * @static
  32174. * @type {string}
  32175. * @default '__DEFAULT'
  32176. */
  32177. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32178. const loading = {};
  32179. class HttpError extends Error {
  32180. constructor( message, response ) {
  32181. super( message );
  32182. this.response = response;
  32183. }
  32184. }
  32185. /**
  32186. * A low level class for loading resources with the Fetch API, used internally by
  32187. * most loaders. It can also be used directly to load any file type that does
  32188. * not have a loader.
  32189. *
  32190. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32191. * once to your application.
  32192. *
  32193. * ```js
  32194. * const loader = new THREE.FileLoader();
  32195. * const data = await loader.loadAsync( 'example.txt' );
  32196. * ```
  32197. *
  32198. * @augments Loader
  32199. */
  32200. class FileLoader extends Loader {
  32201. /**
  32202. * Constructs a new file loader.
  32203. *
  32204. * @param {LoadingManager} [manager] - The loading manager.
  32205. */
  32206. constructor( manager ) {
  32207. super( manager );
  32208. /**
  32209. * The expected mime type. Valid values can be found
  32210. * [here]{@link hhttps://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype}
  32211. *
  32212. * @type {string}
  32213. */
  32214. this.mimeType = '';
  32215. /**
  32216. * The expected response type.
  32217. *
  32218. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32219. * @default ''
  32220. */
  32221. this.responseType = '';
  32222. /**
  32223. * Used for aborting requests.
  32224. *
  32225. * @private
  32226. * @type {AbortController}
  32227. */
  32228. this._abortController = new AbortController();
  32229. }
  32230. /**
  32231. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32232. *
  32233. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32234. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32235. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32236. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32237. * @return {any|undefined} The cached resource if available.
  32238. */
  32239. load( url, onLoad, onProgress, onError ) {
  32240. if ( url === undefined ) url = '';
  32241. if ( this.path !== undefined ) url = this.path + url;
  32242. url = this.manager.resolveURL( url );
  32243. const cached = Cache.get( `file:${url}` );
  32244. if ( cached !== undefined ) {
  32245. this.manager.itemStart( url );
  32246. setTimeout( () => {
  32247. if ( onLoad ) onLoad( cached );
  32248. this.manager.itemEnd( url );
  32249. }, 0 );
  32250. return cached;
  32251. }
  32252. // Check if request is duplicate
  32253. if ( loading[ url ] !== undefined ) {
  32254. loading[ url ].push( {
  32255. onLoad: onLoad,
  32256. onProgress: onProgress,
  32257. onError: onError
  32258. } );
  32259. return;
  32260. }
  32261. // Initialise array for duplicate requests
  32262. loading[ url ] = [];
  32263. loading[ url ].push( {
  32264. onLoad: onLoad,
  32265. onProgress: onProgress,
  32266. onError: onError,
  32267. } );
  32268. // create request
  32269. const req = new Request( url, {
  32270. headers: new Headers( this.requestHeader ),
  32271. credentials: this.withCredentials ? 'include' : 'same-origin',
  32272. signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal
  32273. } );
  32274. // record states ( avoid data race )
  32275. const mimeType = this.mimeType;
  32276. const responseType = this.responseType;
  32277. // start the fetch
  32278. fetch( req )
  32279. .then( response => {
  32280. if ( response.status === 200 || response.status === 0 ) {
  32281. // Some browsers return HTTP Status 0 when using non-http protocol
  32282. // e.g. 'file://' or 'data://'. Handle as success.
  32283. if ( response.status === 0 ) {
  32284. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  32285. }
  32286. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32287. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32288. return response;
  32289. }
  32290. const callbacks = loading[ url ];
  32291. const reader = response.body.getReader();
  32292. // Nginx needs X-File-Size check
  32293. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32294. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32295. const total = contentLength ? parseInt( contentLength ) : 0;
  32296. const lengthComputable = total !== 0;
  32297. let loaded = 0;
  32298. // periodically read data into the new stream tracking while download progress
  32299. const stream = new ReadableStream( {
  32300. start( controller ) {
  32301. readData();
  32302. function readData() {
  32303. reader.read().then( ( { done, value } ) => {
  32304. if ( done ) {
  32305. controller.close();
  32306. } else {
  32307. loaded += value.byteLength;
  32308. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32309. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32310. const callback = callbacks[ i ];
  32311. if ( callback.onProgress ) callback.onProgress( event );
  32312. }
  32313. controller.enqueue( value );
  32314. readData();
  32315. }
  32316. }, ( e ) => {
  32317. controller.error( e );
  32318. } );
  32319. }
  32320. }
  32321. } );
  32322. return new Response( stream );
  32323. } else {
  32324. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32325. }
  32326. } )
  32327. .then( response => {
  32328. switch ( responseType ) {
  32329. case 'arraybuffer':
  32330. return response.arrayBuffer();
  32331. case 'blob':
  32332. return response.blob();
  32333. case 'document':
  32334. return response.text()
  32335. .then( text => {
  32336. const parser = new DOMParser();
  32337. return parser.parseFromString( text, mimeType );
  32338. } );
  32339. case 'json':
  32340. return response.json();
  32341. default:
  32342. if ( mimeType === '' ) {
  32343. return response.text();
  32344. } else {
  32345. // sniff encoding
  32346. const re = /charset="?([^;"\s]*)"?/i;
  32347. const exec = re.exec( mimeType );
  32348. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32349. const decoder = new TextDecoder( label );
  32350. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32351. }
  32352. }
  32353. } )
  32354. .then( data => {
  32355. // Add to cache only on HTTP success, so that we do not cache
  32356. // error response bodies as proper responses to requests.
  32357. Cache.add( `file:${url}`, data );
  32358. const callbacks = loading[ url ];
  32359. delete loading[ url ];
  32360. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32361. const callback = callbacks[ i ];
  32362. if ( callback.onLoad ) callback.onLoad( data );
  32363. }
  32364. } )
  32365. .catch( err => {
  32366. // Abort errors and other errors are handled the same
  32367. const callbacks = loading[ url ];
  32368. if ( callbacks === undefined ) {
  32369. // When onLoad was called and url was deleted in `loading`
  32370. this.manager.itemError( url );
  32371. throw err;
  32372. }
  32373. delete loading[ url ];
  32374. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32375. const callback = callbacks[ i ];
  32376. if ( callback.onError ) callback.onError( err );
  32377. }
  32378. this.manager.itemError( url );
  32379. } )
  32380. .finally( () => {
  32381. this.manager.itemEnd( url );
  32382. } );
  32383. this.manager.itemStart( url );
  32384. }
  32385. /**
  32386. * Sets the expected response type.
  32387. *
  32388. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32389. * @return {FileLoader} A reference to this file loader.
  32390. */
  32391. setResponseType( value ) {
  32392. this.responseType = value;
  32393. return this;
  32394. }
  32395. /**
  32396. * Sets the expected mime type of the loaded file.
  32397. *
  32398. * @param {string} value - The mime type.
  32399. * @return {FileLoader} A reference to this file loader.
  32400. */
  32401. setMimeType( value ) {
  32402. this.mimeType = value;
  32403. return this;
  32404. }
  32405. /**
  32406. * Aborts ongoing fetch requests.
  32407. *
  32408. * @return {FileLoader} A reference to this instance.
  32409. */
  32410. abort() {
  32411. this._abortController.abort();
  32412. this._abortController = new AbortController();
  32413. return this;
  32414. }
  32415. }
  32416. /**
  32417. * Class for loading animation clips in the JSON format. The files are internally
  32418. * loaded via {@link FileLoader}.
  32419. *
  32420. * ```js
  32421. * const loader = new THREE.AnimationLoader();
  32422. * const animations = await loader.loadAsync( 'animations/animation.js' );
  32423. * ```
  32424. *
  32425. * @augments Loader
  32426. */
  32427. class AnimationLoader extends Loader {
  32428. /**
  32429. * Constructs a new animation loader.
  32430. *
  32431. * @param {LoadingManager} [manager] - The loading manager.
  32432. */
  32433. constructor( manager ) {
  32434. super( manager );
  32435. }
  32436. /**
  32437. * Starts loading from the given URL and pass the loaded animations as an array
  32438. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  32439. *
  32440. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32441. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  32442. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32443. * @param {onErrorCallback} onError - Executed when errors occur.
  32444. */
  32445. load( url, onLoad, onProgress, onError ) {
  32446. const scope = this;
  32447. const loader = new FileLoader( this.manager );
  32448. loader.setPath( this.path );
  32449. loader.setRequestHeader( this.requestHeader );
  32450. loader.setWithCredentials( this.withCredentials );
  32451. loader.load( url, function ( text ) {
  32452. try {
  32453. onLoad( scope.parse( JSON.parse( text ) ) );
  32454. } catch ( e ) {
  32455. if ( onError ) {
  32456. onError( e );
  32457. } else {
  32458. console.error( e );
  32459. }
  32460. scope.manager.itemError( url );
  32461. }
  32462. }, onProgress, onError );
  32463. }
  32464. /**
  32465. * Parses the given JSON object and returns an array of animation clips.
  32466. *
  32467. * @param {Object} json - The serialized animation clips.
  32468. * @return {Array<AnimationClip>} The parsed animation clips.
  32469. */
  32470. parse( json ) {
  32471. const animations = [];
  32472. for ( let i = 0; i < json.length; i ++ ) {
  32473. const clip = AnimationClip.parse( json[ i ] );
  32474. animations.push( clip );
  32475. }
  32476. return animations;
  32477. }
  32478. }
  32479. /**
  32480. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  32481. * Textures are internally loaded via {@link FileLoader}.
  32482. *
  32483. * Derived classes have to implement the `parse()` method which holds the parsing
  32484. * for the respective format.
  32485. *
  32486. * @abstract
  32487. * @augments Loader
  32488. */
  32489. class CompressedTextureLoader extends Loader {
  32490. /**
  32491. * Constructs a new compressed texture loader.
  32492. *
  32493. * @param {LoadingManager} [manager] - The loading manager.
  32494. */
  32495. constructor( manager ) {
  32496. super( manager );
  32497. }
  32498. /**
  32499. * Starts loading from the given URL and passes the loaded compressed texture
  32500. * to the `onLoad()` callback. The method also returns a new texture object which can
  32501. * directly be used for material creation. If you do it this way, the texture
  32502. * may pop up in your scene once the respective loading process is finished.
  32503. *
  32504. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32505. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  32506. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32507. * @param {onErrorCallback} onError - Executed when errors occur.
  32508. * @return {CompressedTexture} The compressed texture.
  32509. */
  32510. load( url, onLoad, onProgress, onError ) {
  32511. const scope = this;
  32512. const images = [];
  32513. const texture = new CompressedTexture();
  32514. const loader = new FileLoader( this.manager );
  32515. loader.setPath( this.path );
  32516. loader.setResponseType( 'arraybuffer' );
  32517. loader.setRequestHeader( this.requestHeader );
  32518. loader.setWithCredentials( scope.withCredentials );
  32519. let loaded = 0;
  32520. function loadTexture( i ) {
  32521. loader.load( url[ i ], function ( buffer ) {
  32522. const texDatas = scope.parse( buffer, true );
  32523. images[ i ] = {
  32524. width: texDatas.width,
  32525. height: texDatas.height,
  32526. format: texDatas.format,
  32527. mipmaps: texDatas.mipmaps
  32528. };
  32529. loaded += 1;
  32530. if ( loaded === 6 ) {
  32531. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  32532. texture.image = images;
  32533. texture.format = texDatas.format;
  32534. texture.needsUpdate = true;
  32535. if ( onLoad ) onLoad( texture );
  32536. }
  32537. }, onProgress, onError );
  32538. }
  32539. if ( Array.isArray( url ) ) {
  32540. for ( let i = 0, il = url.length; i < il; ++ i ) {
  32541. loadTexture( i );
  32542. }
  32543. } else {
  32544. // compressed cubemap texture stored in a single DDS file
  32545. loader.load( url, function ( buffer ) {
  32546. const texDatas = scope.parse( buffer, true );
  32547. if ( texDatas.isCubemap ) {
  32548. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  32549. for ( let f = 0; f < faces; f ++ ) {
  32550. images[ f ] = { mipmaps: [] };
  32551. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  32552. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  32553. images[ f ].format = texDatas.format;
  32554. images[ f ].width = texDatas.width;
  32555. images[ f ].height = texDatas.height;
  32556. }
  32557. }
  32558. texture.image = images;
  32559. } else {
  32560. texture.image.width = texDatas.width;
  32561. texture.image.height = texDatas.height;
  32562. texture.mipmaps = texDatas.mipmaps;
  32563. }
  32564. if ( texDatas.mipmapCount === 1 ) {
  32565. texture.minFilter = LinearFilter;
  32566. }
  32567. texture.format = texDatas.format;
  32568. texture.needsUpdate = true;
  32569. if ( onLoad ) onLoad( texture );
  32570. }, onProgress, onError );
  32571. }
  32572. return texture;
  32573. }
  32574. }
  32575. const _loading = new WeakMap();
  32576. /**
  32577. * A loader for loading images. The class loads images with the HTML `Image` API.
  32578. *
  32579. * ```js
  32580. * const loader = new THREE.ImageLoader();
  32581. * const image = await loader.loadAsync( 'image.png' );
  32582. * ```
  32583. * Please note that `ImageLoader` has dropped support for progress
  32584. * events in `r84`. For an `ImageLoader` that supports progress events, see
  32585. * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639}.
  32586. *
  32587. * @augments Loader
  32588. */
  32589. class ImageLoader extends Loader {
  32590. /**
  32591. * Constructs a new image loader.
  32592. *
  32593. * @param {LoadingManager} [manager] - The loading manager.
  32594. */
  32595. constructor( manager ) {
  32596. super( manager );
  32597. }
  32598. /**
  32599. * Starts loading from the given URL and passes the loaded image
  32600. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  32601. * directly be used for texture creation. If you do it this way, the texture
  32602. * may pop up in your scene once the respective loading process is finished.
  32603. *
  32604. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32605. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  32606. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32607. * @param {onErrorCallback} onError - Executed when errors occur.
  32608. * @return {Image} The image.
  32609. */
  32610. load( url, onLoad, onProgress, onError ) {
  32611. if ( this.path !== undefined ) url = this.path + url;
  32612. url = this.manager.resolveURL( url );
  32613. const scope = this;
  32614. const cached = Cache.get( `image:${url}` );
  32615. if ( cached !== undefined ) {
  32616. if ( cached.complete === true ) {
  32617. scope.manager.itemStart( url );
  32618. setTimeout( function () {
  32619. if ( onLoad ) onLoad( cached );
  32620. scope.manager.itemEnd( url );
  32621. }, 0 );
  32622. } else {
  32623. let arr = _loading.get( cached );
  32624. if ( arr === undefined ) {
  32625. arr = [];
  32626. _loading.set( cached, arr );
  32627. }
  32628. arr.push( { onLoad, onError } );
  32629. }
  32630. return cached;
  32631. }
  32632. const image = createElementNS( 'img' );
  32633. function onImageLoad() {
  32634. removeEventListeners();
  32635. if ( onLoad ) onLoad( this );
  32636. //
  32637. const callbacks = _loading.get( this ) || [];
  32638. for ( let i = 0; i < callbacks.length; i ++ ) {
  32639. const callback = callbacks[ i ];
  32640. if ( callback.onLoad ) callback.onLoad( this );
  32641. }
  32642. _loading.delete( this );
  32643. scope.manager.itemEnd( url );
  32644. }
  32645. function onImageError( event ) {
  32646. removeEventListeners();
  32647. if ( onError ) onError( event );
  32648. Cache.remove( `image:${url}` );
  32649. //
  32650. const callbacks = _loading.get( this ) || [];
  32651. for ( let i = 0; i < callbacks.length; i ++ ) {
  32652. const callback = callbacks[ i ];
  32653. if ( callback.onError ) callback.onError( event );
  32654. }
  32655. _loading.delete( this );
  32656. scope.manager.itemError( url );
  32657. scope.manager.itemEnd( url );
  32658. }
  32659. function removeEventListeners() {
  32660. image.removeEventListener( 'load', onImageLoad, false );
  32661. image.removeEventListener( 'error', onImageError, false );
  32662. }
  32663. image.addEventListener( 'load', onImageLoad, false );
  32664. image.addEventListener( 'error', onImageError, false );
  32665. if ( url.slice( 0, 5 ) !== 'data:' ) {
  32666. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  32667. }
  32668. Cache.add( `image:${url}`, image );
  32669. scope.manager.itemStart( url );
  32670. image.src = url;
  32671. return image;
  32672. }
  32673. }
  32674. /**
  32675. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  32676. *
  32677. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  32678. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  32679. * like vertical and horizontal cross, column and row layouts are not supported.
  32680. *
  32681. * Note that, by convention, cube maps are specified in a coordinate system
  32682. * in which positive-x is to the right when looking up the positive-z axis --
  32683. * in other words, using a left-handed coordinate system. Since three.js uses
  32684. * a right-handed coordinate system, environment maps used in three.js will
  32685. * have pos-x and neg-x swapped.
  32686. *
  32687. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  32688. * is set to `SRGBColorSpace` by default.
  32689. *
  32690. * ```js
  32691. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  32692. * const cubeTexture = await loader.loadAsync( [
  32693. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  32694. * ] );
  32695. * scene.background = cubeTexture;
  32696. * ```
  32697. *
  32698. * @augments Loader
  32699. */
  32700. class CubeTextureLoader extends Loader {
  32701. /**
  32702. * Constructs a new cube texture loader.
  32703. *
  32704. * @param {LoadingManager} [manager] - The loading manager.
  32705. */
  32706. constructor( manager ) {
  32707. super( manager );
  32708. }
  32709. /**
  32710. * Starts loading from the given URL and pass the fully loaded cube texture
  32711. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  32712. * directly be used for material creation. If you do it this way, the cube texture
  32713. * may pop up in your scene once the respective loading process is finished.
  32714. *
  32715. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  32716. * cube texture. The urls should be specified in the following order: pos-x,
  32717. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  32718. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  32719. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32720. * @param {onErrorCallback} onError - Executed when errors occur.
  32721. * @return {CubeTexture} The cube texture.
  32722. */
  32723. load( urls, onLoad, onProgress, onError ) {
  32724. const texture = new CubeTexture();
  32725. texture.colorSpace = SRGBColorSpace;
  32726. const loader = new ImageLoader( this.manager );
  32727. loader.setCrossOrigin( this.crossOrigin );
  32728. loader.setPath( this.path );
  32729. let loaded = 0;
  32730. function loadTexture( i ) {
  32731. loader.load( urls[ i ], function ( image ) {
  32732. texture.images[ i ] = image;
  32733. loaded ++;
  32734. if ( loaded === 6 ) {
  32735. texture.needsUpdate = true;
  32736. if ( onLoad ) onLoad( texture );
  32737. }
  32738. }, undefined, onError );
  32739. }
  32740. for ( let i = 0; i < urls.length; ++ i ) {
  32741. loadTexture( i );
  32742. }
  32743. return texture;
  32744. }
  32745. }
  32746. /**
  32747. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  32748. * Textures are internally loaded via {@link FileLoader}.
  32749. *
  32750. * Derived classes have to implement the `parse()` method which holds the parsing
  32751. * for the respective format.
  32752. *
  32753. * @abstract
  32754. * @augments Loader
  32755. */
  32756. class DataTextureLoader extends Loader {
  32757. /**
  32758. * Constructs a new data texture loader.
  32759. *
  32760. * @param {LoadingManager} [manager] - The loading manager.
  32761. */
  32762. constructor( manager ) {
  32763. super( manager );
  32764. }
  32765. /**
  32766. * Starts loading from the given URL and passes the loaded data texture
  32767. * to the `onLoad()` callback. The method also returns a new texture object which can
  32768. * directly be used for material creation. If you do it this way, the texture
  32769. * may pop up in your scene once the respective loading process is finished.
  32770. *
  32771. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32772. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  32773. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32774. * @param {onErrorCallback} onError - Executed when errors occur.
  32775. * @return {DataTexture} The data texture.
  32776. */
  32777. load( url, onLoad, onProgress, onError ) {
  32778. const scope = this;
  32779. const texture = new DataTexture();
  32780. const loader = new FileLoader( this.manager );
  32781. loader.setResponseType( 'arraybuffer' );
  32782. loader.setRequestHeader( this.requestHeader );
  32783. loader.setPath( this.path );
  32784. loader.setWithCredentials( scope.withCredentials );
  32785. loader.load( url, function ( buffer ) {
  32786. let texData;
  32787. try {
  32788. texData = scope.parse( buffer );
  32789. } catch ( error ) {
  32790. if ( onError !== undefined ) {
  32791. onError( error );
  32792. } else {
  32793. console.error( error );
  32794. return;
  32795. }
  32796. }
  32797. if ( texData.image !== undefined ) {
  32798. texture.image = texData.image;
  32799. } else if ( texData.data !== undefined ) {
  32800. texture.image.width = texData.width;
  32801. texture.image.height = texData.height;
  32802. texture.image.data = texData.data;
  32803. }
  32804. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  32805. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  32806. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  32807. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  32808. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  32809. if ( texData.colorSpace !== undefined ) {
  32810. texture.colorSpace = texData.colorSpace;
  32811. }
  32812. if ( texData.flipY !== undefined ) {
  32813. texture.flipY = texData.flipY;
  32814. }
  32815. if ( texData.format !== undefined ) {
  32816. texture.format = texData.format;
  32817. }
  32818. if ( texData.type !== undefined ) {
  32819. texture.type = texData.type;
  32820. }
  32821. if ( texData.mipmaps !== undefined ) {
  32822. texture.mipmaps = texData.mipmaps;
  32823. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  32824. }
  32825. if ( texData.mipmapCount === 1 ) {
  32826. texture.minFilter = LinearFilter;
  32827. }
  32828. if ( texData.generateMipmaps !== undefined ) {
  32829. texture.generateMipmaps = texData.generateMipmaps;
  32830. }
  32831. texture.needsUpdate = true;
  32832. if ( onLoad ) onLoad( texture, texData );
  32833. }, onProgress, onError );
  32834. return texture;
  32835. }
  32836. }
  32837. /**
  32838. * Class for loading textures. Images are internally
  32839. * loaded via {@link ImageLoader}.
  32840. *
  32841. * ```js
  32842. * const loader = new THREE.TextureLoader();
  32843. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  32844. *
  32845. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  32846. * ```
  32847. * Please note that `TextureLoader` has dropped support for progress
  32848. * events in `r84`. For a `TextureLoader` that supports progress events, see
  32849. * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145}.
  32850. *
  32851. * @augments Loader
  32852. */
  32853. class TextureLoader extends Loader {
  32854. /**
  32855. * Constructs a new texture loader.
  32856. *
  32857. * @param {LoadingManager} [manager] - The loading manager.
  32858. */
  32859. constructor( manager ) {
  32860. super( manager );
  32861. }
  32862. /**
  32863. * Starts loading from the given URL and pass the fully loaded texture
  32864. * to the `onLoad()` callback. The method also returns a new texture object which can
  32865. * directly be used for material creation. If you do it this way, the texture
  32866. * may pop up in your scene once the respective loading process is finished.
  32867. *
  32868. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32869. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  32870. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32871. * @param {onErrorCallback} onError - Executed when errors occur.
  32872. * @return {Texture} The texture.
  32873. */
  32874. load( url, onLoad, onProgress, onError ) {
  32875. const texture = new Texture();
  32876. const loader = new ImageLoader( this.manager );
  32877. loader.setCrossOrigin( this.crossOrigin );
  32878. loader.setPath( this.path );
  32879. loader.load( url, function ( image ) {
  32880. texture.image = image;
  32881. texture.needsUpdate = true;
  32882. if ( onLoad !== undefined ) {
  32883. onLoad( texture );
  32884. }
  32885. }, onProgress, onError );
  32886. return texture;
  32887. }
  32888. }
  32889. /**
  32890. * Abstract base class for lights - all other light types inherit the
  32891. * properties and methods described here.
  32892. *
  32893. * @abstract
  32894. * @augments Object3D
  32895. */
  32896. class Light extends Object3D {
  32897. /**
  32898. * Constructs a new light.
  32899. *
  32900. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  32901. * @param {number} [intensity=1] - The light's strength/intensity.
  32902. */
  32903. constructor( color, intensity = 1 ) {
  32904. super();
  32905. /**
  32906. * This flag can be used for type testing.
  32907. *
  32908. * @type {boolean}
  32909. * @readonly
  32910. * @default true
  32911. */
  32912. this.isLight = true;
  32913. this.type = 'Light';
  32914. /**
  32915. * The light's color.
  32916. *
  32917. * @type {Color}
  32918. */
  32919. this.color = new Color( color );
  32920. /**
  32921. * The light's intensity.
  32922. *
  32923. * @type {number}
  32924. * @default 1
  32925. */
  32926. this.intensity = intensity;
  32927. }
  32928. /**
  32929. * Frees the GPU-related resources allocated by this instance. Call this
  32930. * method whenever this instance is no longer used in your app.
  32931. */
  32932. dispose() {
  32933. // Empty here in base class; some subclasses override.
  32934. }
  32935. copy( source, recursive ) {
  32936. super.copy( source, recursive );
  32937. this.color.copy( source.color );
  32938. this.intensity = source.intensity;
  32939. return this;
  32940. }
  32941. toJSON( meta ) {
  32942. const data = super.toJSON( meta );
  32943. data.object.color = this.color.getHex();
  32944. data.object.intensity = this.intensity;
  32945. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  32946. if ( this.distance !== undefined ) data.object.distance = this.distance;
  32947. if ( this.angle !== undefined ) data.object.angle = this.angle;
  32948. if ( this.decay !== undefined ) data.object.decay = this.decay;
  32949. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  32950. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  32951. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  32952. return data;
  32953. }
  32954. }
  32955. /**
  32956. * A light source positioned directly above the scene, with color fading from
  32957. * the sky color to the ground color.
  32958. *
  32959. * This light cannot be used to cast shadows.
  32960. *
  32961. * ```js
  32962. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  32963. * scene.add( light );
  32964. * ```
  32965. *
  32966. * @augments Light
  32967. */
  32968. class HemisphereLight extends Light {
  32969. /**
  32970. * Constructs a new hemisphere light.
  32971. *
  32972. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  32973. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  32974. * @param {number} [intensity=1] - The light's strength/intensity.
  32975. */
  32976. constructor( skyColor, groundColor, intensity ) {
  32977. super( skyColor, intensity );
  32978. /**
  32979. * This flag can be used for type testing.
  32980. *
  32981. * @type {boolean}
  32982. * @readonly
  32983. * @default true
  32984. */
  32985. this.isHemisphereLight = true;
  32986. this.type = 'HemisphereLight';
  32987. this.position.copy( Object3D.DEFAULT_UP );
  32988. this.updateMatrix();
  32989. /**
  32990. * The light's ground color.
  32991. *
  32992. * @type {Color}
  32993. */
  32994. this.groundColor = new Color( groundColor );
  32995. }
  32996. copy( source, recursive ) {
  32997. super.copy( source, recursive );
  32998. this.groundColor.copy( source.groundColor );
  32999. return this;
  33000. }
  33001. }
  33002. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  33003. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  33004. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  33005. /**
  33006. * Abstract base class for light shadow classes. These classes
  33007. * represent the shadow configuration for different light types.
  33008. *
  33009. * @abstract
  33010. */
  33011. class LightShadow {
  33012. /**
  33013. * Constructs a new light shadow.
  33014. *
  33015. * @param {Camera} camera - The light's view of the world.
  33016. */
  33017. constructor( camera ) {
  33018. /**
  33019. * The light's view of the world.
  33020. *
  33021. * @type {Camera}
  33022. */
  33023. this.camera = camera;
  33024. /**
  33025. * The intensity of the shadow. The default is `1`.
  33026. * Valid values are in the range `[0, 1]`.
  33027. *
  33028. * @type {number}
  33029. * @default 1
  33030. */
  33031. this.intensity = 1;
  33032. /**
  33033. * Shadow map bias, how much to add or subtract from the normalized depth
  33034. * when deciding whether a surface is in shadow.
  33035. *
  33036. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  33037. * may help reduce artifacts in shadows.
  33038. *
  33039. * @type {number}
  33040. * @default 0
  33041. */
  33042. this.bias = 0;
  33043. /**
  33044. * Defines how much the position used to query the shadow map is offset along
  33045. * the object normal. The default is `0`. Increasing this value can be used to
  33046. * reduce shadow acne especially in large scenes where light shines onto
  33047. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  33048. *
  33049. * @type {number}
  33050. * @default 0
  33051. */
  33052. this.normalBias = 0;
  33053. /**
  33054. * Setting this to values greater than 1 will blur the edges of the shadow.
  33055. * High values will cause unwanted banding effects in the shadows - a greater
  33056. * map size will allow for a higher value to be used here before these effects
  33057. * become visible.
  33058. *
  33059. * The property has no effect when the shadow map type is `PCFSoftShadowMap` and
  33060. * and it is recommended to increase softness by decreasing the shadow map size instead.
  33061. *
  33062. * The property has no effect when the shadow map type is `BasicShadowMap`.
  33063. *
  33064. * @type {number}
  33065. * @default 1
  33066. */
  33067. this.radius = 1;
  33068. /**
  33069. * The amount of samples to use when blurring a VSM shadow map.
  33070. *
  33071. * @type {number}
  33072. * @default 8
  33073. */
  33074. this.blurSamples = 8;
  33075. /**
  33076. * Defines the width and height of the shadow map. Higher values give better quality
  33077. * shadows at the cost of computation time. Values must be powers of two.
  33078. *
  33079. * @type {Vector2}
  33080. * @default (512,512)
  33081. */
  33082. this.mapSize = new Vector2( 512, 512 );
  33083. /**
  33084. * The type of shadow texture. The default is `UnsignedByteType`.
  33085. *
  33086. * @type {number}
  33087. * @default UnsignedByteType
  33088. */
  33089. this.mapType = UnsignedByteType;
  33090. /**
  33091. * The depth map generated using the internal camera; a location beyond a
  33092. * pixel's depth is in shadow. Computed internally during rendering.
  33093. *
  33094. * @type {?RenderTarget}
  33095. * @default null
  33096. */
  33097. this.map = null;
  33098. /**
  33099. * The distribution map generated using the internal camera; an occlusion is
  33100. * calculated based on the distribution of depths. Computed internally during
  33101. * rendering.
  33102. *
  33103. * @type {?RenderTarget}
  33104. * @default null
  33105. */
  33106. this.mapPass = null;
  33107. /**
  33108. * Model to shadow camera space, to compute location and depth in shadow map.
  33109. * This is computed internally during rendering.
  33110. *
  33111. * @type {Matrix4}
  33112. */
  33113. this.matrix = new Matrix4();
  33114. /**
  33115. * Enables automatic updates of the light's shadow. If you do not require dynamic
  33116. * lighting / shadows, you may set this to `false`.
  33117. *
  33118. * @type {boolean}
  33119. * @default true
  33120. */
  33121. this.autoUpdate = true;
  33122. /**
  33123. * When set to `true`, shadow maps will be updated in the next `render` call.
  33124. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  33125. * set this property to `true` and then make a render call to update the light's shadow.
  33126. *
  33127. * @type {boolean}
  33128. * @default false
  33129. */
  33130. this.needsUpdate = false;
  33131. this._frustum = new Frustum();
  33132. this._frameExtents = new Vector2( 1, 1 );
  33133. this._viewportCount = 1;
  33134. this._viewports = [
  33135. new Vector4( 0, 0, 1, 1 )
  33136. ];
  33137. }
  33138. /**
  33139. * Used internally by the renderer to get the number of viewports that need
  33140. * to be rendered for this shadow.
  33141. *
  33142. * @return {number} The viewport count.
  33143. */
  33144. getViewportCount() {
  33145. return this._viewportCount;
  33146. }
  33147. /**
  33148. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  33149. *
  33150. * @return {Frustum} The shadow camera frustum.
  33151. */
  33152. getFrustum() {
  33153. return this._frustum;
  33154. }
  33155. /**
  33156. * Update the matrices for the camera and shadow, used internally by the renderer.
  33157. *
  33158. * @param {Light} light - The light for which the shadow is being rendered.
  33159. */
  33160. updateMatrices( light ) {
  33161. const shadowCamera = this.camera;
  33162. const shadowMatrix = this.matrix;
  33163. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  33164. shadowCamera.position.copy( _lightPositionWorld$1 );
  33165. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  33166. shadowCamera.lookAt( _lookTarget$1 );
  33167. shadowCamera.updateMatrixWorld();
  33168. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  33169. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1, shadowCamera.coordinateSystem, shadowCamera.reversedDepth );
  33170. if ( shadowCamera.reversedDepth ) {
  33171. shadowMatrix.set(
  33172. 0.5, 0.0, 0.0, 0.5,
  33173. 0.0, 0.5, 0.0, 0.5,
  33174. 0.0, 0.0, 1.0, 0.0,
  33175. 0.0, 0.0, 0.0, 1.0
  33176. );
  33177. } else {
  33178. shadowMatrix.set(
  33179. 0.5, 0.0, 0.0, 0.5,
  33180. 0.0, 0.5, 0.0, 0.5,
  33181. 0.0, 0.0, 0.5, 0.5,
  33182. 0.0, 0.0, 0.0, 1.0
  33183. );
  33184. }
  33185. shadowMatrix.multiply( _projScreenMatrix$1 );
  33186. }
  33187. /**
  33188. * Returns a viewport definition for the given viewport index.
  33189. *
  33190. * @param {number} viewportIndex - The viewport index.
  33191. * @return {Vector4} The viewport.
  33192. */
  33193. getViewport( viewportIndex ) {
  33194. return this._viewports[ viewportIndex ];
  33195. }
  33196. /**
  33197. * Returns the frame extends.
  33198. *
  33199. * @return {Vector2} The frame extends.
  33200. */
  33201. getFrameExtents() {
  33202. return this._frameExtents;
  33203. }
  33204. /**
  33205. * Frees the GPU-related resources allocated by this instance. Call this
  33206. * method whenever this instance is no longer used in your app.
  33207. */
  33208. dispose() {
  33209. if ( this.map ) {
  33210. this.map.dispose();
  33211. }
  33212. if ( this.mapPass ) {
  33213. this.mapPass.dispose();
  33214. }
  33215. }
  33216. /**
  33217. * Copies the values of the given light shadow instance to this instance.
  33218. *
  33219. * @param {LightShadow} source - The light shadow to copy.
  33220. * @return {LightShadow} A reference to this light shadow instance.
  33221. */
  33222. copy( source ) {
  33223. this.camera = source.camera.clone();
  33224. this.intensity = source.intensity;
  33225. this.bias = source.bias;
  33226. this.radius = source.radius;
  33227. this.autoUpdate = source.autoUpdate;
  33228. this.needsUpdate = source.needsUpdate;
  33229. this.normalBias = source.normalBias;
  33230. this.blurSamples = source.blurSamples;
  33231. this.mapSize.copy( source.mapSize );
  33232. return this;
  33233. }
  33234. /**
  33235. * Returns a new light shadow instance with copied values from this instance.
  33236. *
  33237. * @return {LightShadow} A clone of this instance.
  33238. */
  33239. clone() {
  33240. return new this.constructor().copy( this );
  33241. }
  33242. /**
  33243. * Serializes the light shadow into JSON.
  33244. *
  33245. * @return {Object} A JSON object representing the serialized light shadow.
  33246. * @see {@link ObjectLoader#parse}
  33247. */
  33248. toJSON() {
  33249. const object = {};
  33250. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33251. if ( this.bias !== 0 ) object.bias = this.bias;
  33252. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33253. if ( this.radius !== 1 ) object.radius = this.radius;
  33254. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33255. object.camera = this.camera.toJSON( false ).object;
  33256. delete object.camera.matrix;
  33257. return object;
  33258. }
  33259. }
  33260. /**
  33261. * Represents the shadow configuration of directional lights.
  33262. *
  33263. * @augments LightShadow
  33264. */
  33265. class SpotLightShadow extends LightShadow {
  33266. /**
  33267. * Constructs a new spot light shadow.
  33268. */
  33269. constructor() {
  33270. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  33271. /**
  33272. * This flag can be used for type testing.
  33273. *
  33274. * @type {boolean}
  33275. * @readonly
  33276. * @default true
  33277. */
  33278. this.isSpotLightShadow = true;
  33279. /**
  33280. * Used to focus the shadow camera. The camera's field of view is set as a
  33281. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  33282. *
  33283. * @type {number}
  33284. * @default 1
  33285. */
  33286. this.focus = 1;
  33287. /**
  33288. * Texture aspect ratio.
  33289. *
  33290. * @type {number}
  33291. * @default 1
  33292. */
  33293. this.aspect = 1;
  33294. }
  33295. updateMatrices( light ) {
  33296. const camera = this.camera;
  33297. const fov = RAD2DEG * 2 * light.angle * this.focus;
  33298. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  33299. const far = light.distance || camera.far;
  33300. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  33301. camera.fov = fov;
  33302. camera.aspect = aspect;
  33303. camera.far = far;
  33304. camera.updateProjectionMatrix();
  33305. }
  33306. super.updateMatrices( light );
  33307. }
  33308. copy( source ) {
  33309. super.copy( source );
  33310. this.focus = source.focus;
  33311. return this;
  33312. }
  33313. }
  33314. /**
  33315. * This light gets emitted from a single point in one direction, along a cone
  33316. * that increases in size the further from the light it gets.
  33317. *
  33318. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  33319. *
  33320. * ```js
  33321. * // white spotlight shining from the side, modulated by a texture
  33322. * const spotLight = new THREE.SpotLight( 0xffffff );
  33323. * spotLight.position.set( 100, 1000, 100 );
  33324. * spotLight.map = new THREE.TextureLoader().load( url );
  33325. *
  33326. * spotLight.castShadow = true;
  33327. * spotLight.shadow.mapSize.width = 1024;
  33328. * spotLight.shadow.mapSize.height = 1024;
  33329. * spotLight.shadow.camera.near = 500;
  33330. * spotLight.shadow.camera.far = 4000;
  33331. * spotLight.shadow.camera.fov = 30;s
  33332. * ```
  33333. *
  33334. * @augments Light
  33335. */
  33336. class SpotLight extends Light {
  33337. /**
  33338. * Constructs a new spot light.
  33339. *
  33340. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33341. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33342. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33343. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33344. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  33345. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33346. */
  33347. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  33348. super( color, intensity );
  33349. /**
  33350. * This flag can be used for type testing.
  33351. *
  33352. * @type {boolean}
  33353. * @readonly
  33354. * @default true
  33355. */
  33356. this.isSpotLight = true;
  33357. this.type = 'SpotLight';
  33358. this.position.copy( Object3D.DEFAULT_UP );
  33359. this.updateMatrix();
  33360. /**
  33361. * The spot light points from its position to the
  33362. * target's position.
  33363. *
  33364. * For the target's position to be changed to anything other
  33365. * than the default, it must be added to the scene.
  33366. *
  33367. * It is also possible to set the target to be another 3D object
  33368. * in the scene. The light will now track the target object.
  33369. *
  33370. * @type {Object3D}
  33371. */
  33372. this.target = new Object3D();
  33373. /**
  33374. * Maximum range of the light. `0` means no limit.
  33375. *
  33376. * @type {number}
  33377. * @default 0
  33378. */
  33379. this.distance = distance;
  33380. /**
  33381. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33382. *
  33383. * @type {number}
  33384. * @default Math.PI/3
  33385. */
  33386. this.angle = angle;
  33387. /**
  33388. * Percent of the spotlight cone that is attenuated due to penumbra.
  33389. * Value range is `[0,1]`.
  33390. *
  33391. * @type {number}
  33392. * @default 0
  33393. */
  33394. this.penumbra = penumbra;
  33395. /**
  33396. * The amount the light dims along the distance of the light. In context of
  33397. * physically-correct rendering the default value should not be changed.
  33398. *
  33399. * @type {number}
  33400. * @default 2
  33401. */
  33402. this.decay = decay;
  33403. /**
  33404. * A texture used to modulate the color of the light. The spot light
  33405. * color is mixed with the RGB value of this texture, with a ratio
  33406. * corresponding to its alpha value. The cookie-like masking effect is
  33407. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  33408. *
  33409. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  33410. *
  33411. * @type {?Texture}
  33412. * @default null
  33413. */
  33414. this.map = null;
  33415. /**
  33416. * This property holds the light's shadow configuration.
  33417. *
  33418. * @type {SpotLightShadow}
  33419. */
  33420. this.shadow = new SpotLightShadow();
  33421. }
  33422. /**
  33423. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33424. * Changing the power will also change the light's intensity.
  33425. *
  33426. * @type {number}
  33427. */
  33428. get power() {
  33429. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33430. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  33431. return this.intensity * Math.PI;
  33432. }
  33433. set power( power ) {
  33434. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33435. this.intensity = power / Math.PI;
  33436. }
  33437. dispose() {
  33438. this.shadow.dispose();
  33439. }
  33440. copy( source, recursive ) {
  33441. super.copy( source, recursive );
  33442. this.distance = source.distance;
  33443. this.angle = source.angle;
  33444. this.penumbra = source.penumbra;
  33445. this.decay = source.decay;
  33446. this.target = source.target.clone();
  33447. this.shadow = source.shadow.clone();
  33448. return this;
  33449. }
  33450. }
  33451. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  33452. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  33453. const _lookTarget = /*@__PURE__*/ new Vector3();
  33454. /**
  33455. * Represents the shadow configuration of point lights.
  33456. *
  33457. * @augments LightShadow
  33458. */
  33459. class PointLightShadow extends LightShadow {
  33460. /**
  33461. * Constructs a new point light shadow.
  33462. */
  33463. constructor() {
  33464. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  33465. /**
  33466. * This flag can be used for type testing.
  33467. *
  33468. * @type {boolean}
  33469. * @readonly
  33470. * @default true
  33471. */
  33472. this.isPointLightShadow = true;
  33473. this._frameExtents = new Vector2( 4, 2 );
  33474. this._viewportCount = 6;
  33475. this._viewports = [
  33476. // These viewports map a cube-map onto a 2D texture with the
  33477. // following orientation:
  33478. //
  33479. // xzXZ
  33480. // y Y
  33481. //
  33482. // X - Positive x direction
  33483. // x - Negative x direction
  33484. // Y - Positive y direction
  33485. // y - Negative y direction
  33486. // Z - Positive z direction
  33487. // z - Negative z direction
  33488. // positive X
  33489. new Vector4( 2, 1, 1, 1 ),
  33490. // negative X
  33491. new Vector4( 0, 1, 1, 1 ),
  33492. // positive Z
  33493. new Vector4( 3, 1, 1, 1 ),
  33494. // negative Z
  33495. new Vector4( 1, 1, 1, 1 ),
  33496. // positive Y
  33497. new Vector4( 3, 0, 1, 1 ),
  33498. // negative Y
  33499. new Vector4( 1, 0, 1, 1 )
  33500. ];
  33501. this._cubeDirections = [
  33502. new Vector3( 1, 0, 0 ), new Vector3( -1, 0, 0 ), new Vector3( 0, 0, 1 ),
  33503. new Vector3( 0, 0, -1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, -1, 0 )
  33504. ];
  33505. this._cubeUps = [
  33506. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  33507. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, -1 )
  33508. ];
  33509. }
  33510. /**
  33511. * Update the matrices for the camera and shadow, used internally by the renderer.
  33512. *
  33513. * @param {Light} light - The light for which the shadow is being rendered.
  33514. * @param {number} [viewportIndex=0] - The viewport index.
  33515. */
  33516. updateMatrices( light, viewportIndex = 0 ) {
  33517. const camera = this.camera;
  33518. const shadowMatrix = this.matrix;
  33519. const far = light.distance || camera.far;
  33520. if ( far !== camera.far ) {
  33521. camera.far = far;
  33522. camera.updateProjectionMatrix();
  33523. }
  33524. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  33525. camera.position.copy( _lightPositionWorld );
  33526. _lookTarget.copy( camera.position );
  33527. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  33528. camera.up.copy( this._cubeUps[ viewportIndex ] );
  33529. camera.lookAt( _lookTarget );
  33530. camera.updateMatrixWorld();
  33531. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  33532. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  33533. this._frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  33534. }
  33535. }
  33536. /**
  33537. * A light that gets emitted from a single point in all directions. A common
  33538. * use case for this is to replicate the light emitted from a bare
  33539. * lightbulb.
  33540. *
  33541. * This light can cast shadows - see the {@link PointLightShadow} for details.
  33542. *
  33543. * ```js
  33544. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  33545. * light.position.set( 50, 50, 50 );
  33546. * scene.add( light );
  33547. * ```
  33548. *
  33549. * @augments Light
  33550. */
  33551. class PointLight extends Light {
  33552. /**
  33553. * Constructs a new point light.
  33554. *
  33555. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33556. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33557. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33558. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33559. */
  33560. constructor( color, intensity, distance = 0, decay = 2 ) {
  33561. super( color, intensity );
  33562. /**
  33563. * This flag can be used for type testing.
  33564. *
  33565. * @type {boolean}
  33566. * @readonly
  33567. * @default true
  33568. */
  33569. this.isPointLight = true;
  33570. this.type = 'PointLight';
  33571. /**
  33572. * When distance is zero, light will attenuate according to inverse-square
  33573. * law to infinite distance. When distance is non-zero, light will attenuate
  33574. * according to inverse-square law until near the distance cutoff, where it
  33575. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  33576. * physically correct.
  33577. *
  33578. * @type {number}
  33579. * @default 0
  33580. */
  33581. this.distance = distance;
  33582. /**
  33583. * The amount the light dims along the distance of the light. In context of
  33584. * physically-correct rendering the default value should not be changed.
  33585. *
  33586. * @type {number}
  33587. * @default 2
  33588. */
  33589. this.decay = decay;
  33590. /**
  33591. * This property holds the light's shadow configuration.
  33592. *
  33593. * @type {PointLightShadow}
  33594. */
  33595. this.shadow = new PointLightShadow();
  33596. }
  33597. /**
  33598. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33599. * Changing the power will also change the light's intensity.
  33600. *
  33601. * @type {number}
  33602. */
  33603. get power() {
  33604. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33605. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  33606. return this.intensity * 4 * Math.PI;
  33607. }
  33608. set power( power ) {
  33609. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33610. this.intensity = power / ( 4 * Math.PI );
  33611. }
  33612. dispose() {
  33613. this.shadow.dispose();
  33614. }
  33615. copy( source, recursive ) {
  33616. super.copy( source, recursive );
  33617. this.distance = source.distance;
  33618. this.decay = source.decay;
  33619. this.shadow = source.shadow.clone();
  33620. return this;
  33621. }
  33622. }
  33623. /**
  33624. * Camera that uses [orthographic projection]{@link https://en.wikipedia.org/wiki/Orthographic_projection}.
  33625. *
  33626. * In this projection mode, an object's size in the rendered image stays
  33627. * constant regardless of its distance from the camera. This can be useful
  33628. * for rendering 2D scenes and UI elements, amongst other things.
  33629. *
  33630. * ```js
  33631. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  33632. * scene.add( camera );
  33633. * ```
  33634. *
  33635. * @augments Camera
  33636. */
  33637. class OrthographicCamera extends Camera {
  33638. /**
  33639. * Constructs a new orthographic camera.
  33640. *
  33641. * @param {number} [left=-1] - The left plane of the camera's frustum.
  33642. * @param {number} [right=1] - The right plane of the camera's frustum.
  33643. * @param {number} [top=1] - The top plane of the camera's frustum.
  33644. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  33645. * @param {number} [near=0.1] - The camera's near plane.
  33646. * @param {number} [far=2000] - The camera's far plane.
  33647. */
  33648. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  33649. super();
  33650. /**
  33651. * This flag can be used for type testing.
  33652. *
  33653. * @type {boolean}
  33654. * @readonly
  33655. * @default true
  33656. */
  33657. this.isOrthographicCamera = true;
  33658. this.type = 'OrthographicCamera';
  33659. /**
  33660. * The zoom factor of the camera.
  33661. *
  33662. * @type {number}
  33663. * @default 1
  33664. */
  33665. this.zoom = 1;
  33666. /**
  33667. * Represents the frustum window specification. This property should not be edited
  33668. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  33669. *
  33670. * @type {?Object}
  33671. * @default null
  33672. */
  33673. this.view = null;
  33674. /**
  33675. * The left plane of the camera's frustum.
  33676. *
  33677. * @type {number}
  33678. * @default -1
  33679. */
  33680. this.left = left;
  33681. /**
  33682. * The right plane of the camera's frustum.
  33683. *
  33684. * @type {number}
  33685. * @default 1
  33686. */
  33687. this.right = right;
  33688. /**
  33689. * The top plane of the camera's frustum.
  33690. *
  33691. * @type {number}
  33692. * @default 1
  33693. */
  33694. this.top = top;
  33695. /**
  33696. * The bottom plane of the camera's frustum.
  33697. *
  33698. * @type {number}
  33699. * @default -1
  33700. */
  33701. this.bottom = bottom;
  33702. /**
  33703. * The camera's near plane. The valid range is greater than `0`
  33704. * and less than the current value of {@link OrthographicCamera#far}.
  33705. *
  33706. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  33707. * valid value for an orthographic camera's near plane.
  33708. *
  33709. * @type {number}
  33710. * @default 0.1
  33711. */
  33712. this.near = near;
  33713. /**
  33714. * The camera's far plane. Must be greater than the
  33715. * current value of {@link OrthographicCamera#near}.
  33716. *
  33717. * @type {number}
  33718. * @default 2000
  33719. */
  33720. this.far = far;
  33721. this.updateProjectionMatrix();
  33722. }
  33723. copy( source, recursive ) {
  33724. super.copy( source, recursive );
  33725. this.left = source.left;
  33726. this.right = source.right;
  33727. this.top = source.top;
  33728. this.bottom = source.bottom;
  33729. this.near = source.near;
  33730. this.far = source.far;
  33731. this.zoom = source.zoom;
  33732. this.view = source.view === null ? null : Object.assign( {}, source.view );
  33733. return this;
  33734. }
  33735. /**
  33736. * Sets an offset in a larger frustum. This is useful for multi-window or
  33737. * multi-monitor/multi-machine setups.
  33738. *
  33739. * @param {number} fullWidth - The full width of multiview setup.
  33740. * @param {number} fullHeight - The full height of multiview setup.
  33741. * @param {number} x - The horizontal offset of the subcamera.
  33742. * @param {number} y - The vertical offset of the subcamera.
  33743. * @param {number} width - The width of subcamera.
  33744. * @param {number} height - The height of subcamera.
  33745. * @see {@link PerspectiveCamera#setViewOffset}
  33746. */
  33747. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  33748. if ( this.view === null ) {
  33749. this.view = {
  33750. enabled: true,
  33751. fullWidth: 1,
  33752. fullHeight: 1,
  33753. offsetX: 0,
  33754. offsetY: 0,
  33755. width: 1,
  33756. height: 1
  33757. };
  33758. }
  33759. this.view.enabled = true;
  33760. this.view.fullWidth = fullWidth;
  33761. this.view.fullHeight = fullHeight;
  33762. this.view.offsetX = x;
  33763. this.view.offsetY = y;
  33764. this.view.width = width;
  33765. this.view.height = height;
  33766. this.updateProjectionMatrix();
  33767. }
  33768. /**
  33769. * Removes the view offset from the projection matrix.
  33770. */
  33771. clearViewOffset() {
  33772. if ( this.view !== null ) {
  33773. this.view.enabled = false;
  33774. }
  33775. this.updateProjectionMatrix();
  33776. }
  33777. /**
  33778. * Updates the camera's projection matrix. Must be called after any change of
  33779. * camera properties.
  33780. */
  33781. updateProjectionMatrix() {
  33782. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  33783. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  33784. const cx = ( this.right + this.left ) / 2;
  33785. const cy = ( this.top + this.bottom ) / 2;
  33786. let left = cx - dx;
  33787. let right = cx + dx;
  33788. let top = cy + dy;
  33789. let bottom = cy - dy;
  33790. if ( this.view !== null && this.view.enabled ) {
  33791. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  33792. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  33793. left += scaleW * this.view.offsetX;
  33794. right = left + scaleW * this.view.width;
  33795. top -= scaleH * this.view.offsetY;
  33796. bottom = top - scaleH * this.view.height;
  33797. }
  33798. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth );
  33799. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  33800. }
  33801. toJSON( meta ) {
  33802. const data = super.toJSON( meta );
  33803. data.object.zoom = this.zoom;
  33804. data.object.left = this.left;
  33805. data.object.right = this.right;
  33806. data.object.top = this.top;
  33807. data.object.bottom = this.bottom;
  33808. data.object.near = this.near;
  33809. data.object.far = this.far;
  33810. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  33811. return data;
  33812. }
  33813. }
  33814. /**
  33815. * Represents the shadow configuration of directional lights.
  33816. *
  33817. * @augments LightShadow
  33818. */
  33819. class DirectionalLightShadow extends LightShadow {
  33820. /**
  33821. * Constructs a new directional light shadow.
  33822. */
  33823. constructor() {
  33824. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  33825. /**
  33826. * This flag can be used for type testing.
  33827. *
  33828. * @type {boolean}
  33829. * @readonly
  33830. * @default true
  33831. */
  33832. this.isDirectionalLightShadow = true;
  33833. }
  33834. }
  33835. /**
  33836. * A light that gets emitted in a specific direction. This light will behave
  33837. * as though it is infinitely far away and the rays produced from it are all
  33838. * parallel. The common use case for this is to simulate daylight; the sun is
  33839. * far enough away that its position can be considered to be infinite, and
  33840. * all light rays coming from it are parallel.
  33841. *
  33842. * A common point of confusion for directional lights is that setting the
  33843. * rotation has no effect. This is because three.js's DirectionalLight is the
  33844. * equivalent to what is often called a 'Target Direct Light' in other
  33845. * applications.
  33846. *
  33847. * This means that its direction is calculated as pointing from the light's
  33848. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  33849. * (as opposed to a 'Free Direct Light' that just has a rotation
  33850. * component).
  33851. *
  33852. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  33853. *
  33854. * ```js
  33855. * // White directional light at half intensity shining from the top.
  33856. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  33857. * scene.add( directionalLight );
  33858. * ```
  33859. *
  33860. * @augments Light
  33861. */
  33862. class DirectionalLight extends Light {
  33863. /**
  33864. * Constructs a new directional light.
  33865. *
  33866. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33867. * @param {number} [intensity=1] - The light's strength/intensity.
  33868. */
  33869. constructor( color, intensity ) {
  33870. super( color, intensity );
  33871. /**
  33872. * This flag can be used for type testing.
  33873. *
  33874. * @type {boolean}
  33875. * @readonly
  33876. * @default true
  33877. */
  33878. this.isDirectionalLight = true;
  33879. this.type = 'DirectionalLight';
  33880. this.position.copy( Object3D.DEFAULT_UP );
  33881. this.updateMatrix();
  33882. /**
  33883. * The directional light points from its position to the
  33884. * target's position.
  33885. *
  33886. * For the target's position to be changed to anything other
  33887. * than the default, it must be added to the scene.
  33888. *
  33889. * It is also possible to set the target to be another 3D object
  33890. * in the scene. The light will now track the target object.
  33891. *
  33892. * @type {Object3D}
  33893. */
  33894. this.target = new Object3D();
  33895. /**
  33896. * This property holds the light's shadow configuration.
  33897. *
  33898. * @type {DirectionalLightShadow}
  33899. */
  33900. this.shadow = new DirectionalLightShadow();
  33901. }
  33902. dispose() {
  33903. this.shadow.dispose();
  33904. }
  33905. copy( source ) {
  33906. super.copy( source );
  33907. this.target = source.target.clone();
  33908. this.shadow = source.shadow.clone();
  33909. return this;
  33910. }
  33911. }
  33912. /**
  33913. * This light globally illuminates all objects in the scene equally.
  33914. *
  33915. * It cannot be used to cast shadows as it does not have a direction.
  33916. *
  33917. * ```js
  33918. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  33919. * scene.add( light );
  33920. * ```
  33921. *
  33922. * @augments Light
  33923. */
  33924. class AmbientLight extends Light {
  33925. /**
  33926. * Constructs a new ambient light.
  33927. *
  33928. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33929. * @param {number} [intensity=1] - The light's strength/intensity.
  33930. */
  33931. constructor( color, intensity ) {
  33932. super( color, intensity );
  33933. /**
  33934. * This flag can be used for type testing.
  33935. *
  33936. * @type {boolean}
  33937. * @readonly
  33938. * @default true
  33939. */
  33940. this.isAmbientLight = true;
  33941. this.type = 'AmbientLight';
  33942. }
  33943. }
  33944. /**
  33945. * This class emits light uniformly across the face a rectangular plane.
  33946. * This light type can be used to simulate light sources such as bright
  33947. * windows or strip lighting.
  33948. *
  33949. * Important Notes:
  33950. *
  33951. * - There is no shadow support.
  33952. * - Only PBR materials are supported.
  33953. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  33954. * into your app and init the uniforms/textures.
  33955. *
  33956. * ```js
  33957. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  33958. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  33959. *
  33960. * const intensity = 1; const width = 10; const height = 10;
  33961. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  33962. * rectLight.position.set( 5, 5, 0 );
  33963. * rectLight.lookAt( 0, 0, 0 );
  33964. * scene.add( rectLight )
  33965. * ```
  33966. *
  33967. * @augments Light
  33968. */
  33969. class RectAreaLight extends Light {
  33970. /**
  33971. * Constructs a new area light.
  33972. *
  33973. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33974. * @param {number} [intensity=1] - The light's strength/intensity.
  33975. * @param {number} [width=10] - The width of the light.
  33976. * @param {number} [height=10] - The height of the light.
  33977. */
  33978. constructor( color, intensity, width = 10, height = 10 ) {
  33979. super( color, intensity );
  33980. /**
  33981. * This flag can be used for type testing.
  33982. *
  33983. * @type {boolean}
  33984. * @readonly
  33985. * @default true
  33986. */
  33987. this.isRectAreaLight = true;
  33988. this.type = 'RectAreaLight';
  33989. /**
  33990. * The width of the light.
  33991. *
  33992. * @type {number}
  33993. * @default 10
  33994. */
  33995. this.width = width;
  33996. /**
  33997. * The height of the light.
  33998. *
  33999. * @type {number}
  34000. * @default 10
  34001. */
  34002. this.height = height;
  34003. }
  34004. /**
  34005. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34006. * Changing the power will also change the light's intensity.
  34007. *
  34008. * @type {number}
  34009. */
  34010. get power() {
  34011. // compute the light's luminous power (in lumens) from its intensity (in nits)
  34012. return this.intensity * this.width * this.height * Math.PI;
  34013. }
  34014. set power( power ) {
  34015. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  34016. this.intensity = power / ( this.width * this.height * Math.PI );
  34017. }
  34018. copy( source ) {
  34019. super.copy( source );
  34020. this.width = source.width;
  34021. this.height = source.height;
  34022. return this;
  34023. }
  34024. toJSON( meta ) {
  34025. const data = super.toJSON( meta );
  34026. data.object.width = this.width;
  34027. data.object.height = this.height;
  34028. return data;
  34029. }
  34030. }
  34031. /**
  34032. * Represents a third-order spherical harmonics (SH). Light probes use this class
  34033. * to encode lighting information.
  34034. *
  34035. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  34036. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  34037. */
  34038. class SphericalHarmonics3 {
  34039. /**
  34040. * Constructs a new spherical harmonics.
  34041. */
  34042. constructor() {
  34043. /**
  34044. * This flag can be used for type testing.
  34045. *
  34046. * @type {boolean}
  34047. * @readonly
  34048. * @default true
  34049. */
  34050. this.isSphericalHarmonics3 = true;
  34051. /**
  34052. * An array holding the (9) SH coefficients.
  34053. *
  34054. * @type {Array<Vector3>}
  34055. */
  34056. this.coefficients = [];
  34057. for ( let i = 0; i < 9; i ++ ) {
  34058. this.coefficients.push( new Vector3() );
  34059. }
  34060. }
  34061. /**
  34062. * Sets the given SH coefficients to this instance by copying
  34063. * the values.
  34064. *
  34065. * @param {Array<Vector3>} coefficients - The SH coefficients.
  34066. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34067. */
  34068. set( coefficients ) {
  34069. for ( let i = 0; i < 9; i ++ ) {
  34070. this.coefficients[ i ].copy( coefficients[ i ] );
  34071. }
  34072. return this;
  34073. }
  34074. /**
  34075. * Sets all SH coefficients to `0`.
  34076. *
  34077. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34078. */
  34079. zero() {
  34080. for ( let i = 0; i < 9; i ++ ) {
  34081. this.coefficients[ i ].set( 0, 0, 0 );
  34082. }
  34083. return this;
  34084. }
  34085. /**
  34086. * Returns the radiance in the direction of the given normal.
  34087. *
  34088. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34089. * @param {Vector3} target - The target vector that is used to store the method's result.
  34090. * @return {Vector3} The radiance.
  34091. */
  34092. getAt( normal, target ) {
  34093. // normal is assumed to be unit length
  34094. const x = normal.x, y = normal.y, z = normal.z;
  34095. const coeff = this.coefficients;
  34096. // band 0
  34097. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  34098. // band 1
  34099. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  34100. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  34101. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  34102. // band 2
  34103. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  34104. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  34105. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  34106. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  34107. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  34108. return target;
  34109. }
  34110. /**
  34111. * Returns the irradiance (radiance convolved with cosine lobe) in the
  34112. * direction of the given normal.
  34113. *
  34114. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34115. * @param {Vector3} target - The target vector that is used to store the method's result.
  34116. * @return {Vector3} The irradiance.
  34117. */
  34118. getIrradianceAt( normal, target ) {
  34119. // normal is assumed to be unit length
  34120. const x = normal.x, y = normal.y, z = normal.z;
  34121. const coeff = this.coefficients;
  34122. // band 0
  34123. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  34124. // band 1
  34125. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  34126. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  34127. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  34128. // band 2
  34129. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  34130. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  34131. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  34132. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  34133. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  34134. return target;
  34135. }
  34136. /**
  34137. * Adds the given SH to this instance.
  34138. *
  34139. * @param {SphericalHarmonics3} sh - The SH to add.
  34140. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34141. */
  34142. add( sh ) {
  34143. for ( let i = 0; i < 9; i ++ ) {
  34144. this.coefficients[ i ].add( sh.coefficients[ i ] );
  34145. }
  34146. return this;
  34147. }
  34148. /**
  34149. * A convenience method for performing {@link SphericalHarmonics3#add} and
  34150. * {@link SphericalHarmonics3#scale} at once.
  34151. *
  34152. * @param {SphericalHarmonics3} sh - The SH to add.
  34153. * @param {number} s - The scale factor.
  34154. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34155. */
  34156. addScaledSH( sh, s ) {
  34157. for ( let i = 0; i < 9; i ++ ) {
  34158. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  34159. }
  34160. return this;
  34161. }
  34162. /**
  34163. * Scales this SH by the given scale factor.
  34164. *
  34165. * @param {number} s - The scale factor.
  34166. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34167. */
  34168. scale( s ) {
  34169. for ( let i = 0; i < 9; i ++ ) {
  34170. this.coefficients[ i ].multiplyScalar( s );
  34171. }
  34172. return this;
  34173. }
  34174. /**
  34175. * Linear interpolates between the given SH and this instance by the given
  34176. * alpha factor.
  34177. *
  34178. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  34179. * @param {number} alpha - The alpha factor.
  34180. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34181. */
  34182. lerp( sh, alpha ) {
  34183. for ( let i = 0; i < 9; i ++ ) {
  34184. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  34185. }
  34186. return this;
  34187. }
  34188. /**
  34189. * Returns `true` if this spherical harmonics is equal with the given one.
  34190. *
  34191. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  34192. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  34193. */
  34194. equals( sh ) {
  34195. for ( let i = 0; i < 9; i ++ ) {
  34196. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  34197. return false;
  34198. }
  34199. }
  34200. return true;
  34201. }
  34202. /**
  34203. * Copies the values of the given spherical harmonics to this instance.
  34204. *
  34205. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  34206. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34207. */
  34208. copy( sh ) {
  34209. return this.set( sh.coefficients );
  34210. }
  34211. /**
  34212. * Returns a new spherical harmonics with copied values from this instance.
  34213. *
  34214. * @return {SphericalHarmonics3} A clone of this instance.
  34215. */
  34216. clone() {
  34217. return new this.constructor().copy( this );
  34218. }
  34219. /**
  34220. * Sets the SH coefficients of this instance from the given array.
  34221. *
  34222. * @param {Array<number>} array - An array holding the SH coefficients.
  34223. * @param {number} [offset=0] - The array offset where to start copying.
  34224. * @return {SphericalHarmonics3} A clone of this instance.
  34225. */
  34226. fromArray( array, offset = 0 ) {
  34227. const coefficients = this.coefficients;
  34228. for ( let i = 0; i < 9; i ++ ) {
  34229. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  34230. }
  34231. return this;
  34232. }
  34233. /**
  34234. * Returns an array with the SH coefficients, or copies them into the provided
  34235. * array. The coefficients are represented as numbers.
  34236. *
  34237. * @param {Array<number>} [array=[]] - The target array.
  34238. * @param {number} [offset=0] - The array offset where to start copying.
  34239. * @return {Array<number>} An array with flat SH coefficients.
  34240. */
  34241. toArray( array = [], offset = 0 ) {
  34242. const coefficients = this.coefficients;
  34243. for ( let i = 0; i < 9; i ++ ) {
  34244. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  34245. }
  34246. return array;
  34247. }
  34248. /**
  34249. * Computes the SH basis for the given normal vector.
  34250. *
  34251. * @param {Vector3} normal - The normal.
  34252. * @param {Array<number>} shBasis - The target array holding the SH basis.
  34253. */
  34254. static getBasisAt( normal, shBasis ) {
  34255. // normal is assumed to be unit length
  34256. const x = normal.x, y = normal.y, z = normal.z;
  34257. // band 0
  34258. shBasis[ 0 ] = 0.282095;
  34259. // band 1
  34260. shBasis[ 1 ] = 0.488603 * y;
  34261. shBasis[ 2 ] = 0.488603 * z;
  34262. shBasis[ 3 ] = 0.488603 * x;
  34263. // band 2
  34264. shBasis[ 4 ] = 1.092548 * x * y;
  34265. shBasis[ 5 ] = 1.092548 * y * z;
  34266. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  34267. shBasis[ 7 ] = 1.092548 * x * z;
  34268. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  34269. }
  34270. }
  34271. /**
  34272. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  34273. * classical light sources (e.g. directional, point or spot lights), light
  34274. * probes do not emit light. Instead they store information about light
  34275. * passing through 3D space. During rendering, the light that hits a 3D
  34276. * object is approximated by using the data from the light probe.
  34277. *
  34278. * Light probes are usually created from (radiance) environment maps. The
  34279. * class {@link LightProbeGenerator} can be used to create light probes from
  34280. * cube textures or render targets. However, light estimation data could also
  34281. * be provided in other forms e.g. by WebXR. This enables the rendering of
  34282. * augmented reality content that reacts to real world lighting.
  34283. *
  34284. * The current probe implementation in three.js supports so-called diffuse
  34285. * light probes. This type of light probe is functionally equivalent to an
  34286. * irradiance environment map.
  34287. *
  34288. * @augments Light
  34289. */
  34290. class LightProbe extends Light {
  34291. /**
  34292. * Constructs a new light probe.
  34293. *
  34294. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  34295. * @param {number} [intensity=1] - The light's strength/intensity.
  34296. */
  34297. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  34298. super( undefined, intensity );
  34299. /**
  34300. * This flag can be used for type testing.
  34301. *
  34302. * @type {boolean}
  34303. * @readonly
  34304. * @default true
  34305. */
  34306. this.isLightProbe = true;
  34307. /**
  34308. * A light probe uses spherical harmonics to encode lighting information.
  34309. *
  34310. * @type {SphericalHarmonics3}
  34311. */
  34312. this.sh = sh;
  34313. }
  34314. copy( source ) {
  34315. super.copy( source );
  34316. this.sh.copy( source.sh );
  34317. return this;
  34318. }
  34319. /**
  34320. * Deserializes the light prove from the given JSON.
  34321. *
  34322. * @param {Object} json - The JSON holding the serialized light probe.
  34323. * @return {LightProbe} A reference to this light probe.
  34324. */
  34325. fromJSON( json ) {
  34326. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  34327. this.sh.fromArray( json.sh );
  34328. return this;
  34329. }
  34330. toJSON( meta ) {
  34331. const data = super.toJSON( meta );
  34332. data.object.sh = this.sh.toArray();
  34333. return data;
  34334. }
  34335. }
  34336. /**
  34337. * Class for loading geometries. The files are internally
  34338. * loaded via {@link FileLoader}.
  34339. *
  34340. * ```js
  34341. * const loader = new THREE.MaterialLoader();
  34342. * const material = await loader.loadAsync( 'material.json' );
  34343. * ```
  34344. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  34345. *
  34346. * @augments Loader
  34347. */
  34348. class MaterialLoader extends Loader {
  34349. /**
  34350. * Constructs a new material loader.
  34351. *
  34352. * @param {LoadingManager} [manager] - The loading manager.
  34353. */
  34354. constructor( manager ) {
  34355. super( manager );
  34356. /**
  34357. * A dictionary holding textures used by the material.
  34358. *
  34359. * @type {Object<string,Texture>}
  34360. */
  34361. this.textures = {};
  34362. }
  34363. /**
  34364. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  34365. *
  34366. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34367. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  34368. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34369. * @param {onErrorCallback} onError - Executed when errors occur.
  34370. */
  34371. load( url, onLoad, onProgress, onError ) {
  34372. const scope = this;
  34373. const loader = new FileLoader( scope.manager );
  34374. loader.setPath( scope.path );
  34375. loader.setRequestHeader( scope.requestHeader );
  34376. loader.setWithCredentials( scope.withCredentials );
  34377. loader.load( url, function ( text ) {
  34378. try {
  34379. onLoad( scope.parse( JSON.parse( text ) ) );
  34380. } catch ( e ) {
  34381. if ( onError ) {
  34382. onError( e );
  34383. } else {
  34384. console.error( e );
  34385. }
  34386. scope.manager.itemError( url );
  34387. }
  34388. }, onProgress, onError );
  34389. }
  34390. /**
  34391. * Parses the given JSON object and returns a material.
  34392. *
  34393. * @param {Object} json - The serialized material.
  34394. * @return {Material} The parsed material.
  34395. */
  34396. parse( json ) {
  34397. const textures = this.textures;
  34398. function getTexture( name ) {
  34399. if ( textures[ name ] === undefined ) {
  34400. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  34401. }
  34402. return textures[ name ];
  34403. }
  34404. const material = this.createMaterialFromType( json.type );
  34405. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  34406. if ( json.name !== undefined ) material.name = json.name;
  34407. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  34408. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  34409. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  34410. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  34411. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  34412. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  34413. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  34414. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  34415. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  34416. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  34417. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  34418. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  34419. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  34420. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  34421. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  34422. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  34423. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  34424. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  34425. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  34426. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  34427. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  34428. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  34429. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  34430. if ( json.fog !== undefined ) material.fog = json.fog;
  34431. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  34432. if ( json.blending !== undefined ) material.blending = json.blending;
  34433. if ( json.combine !== undefined ) material.combine = json.combine;
  34434. if ( json.side !== undefined ) material.side = json.side;
  34435. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  34436. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  34437. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  34438. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  34439. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  34440. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  34441. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  34442. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  34443. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  34444. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  34445. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  34446. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  34447. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  34448. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  34449. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  34450. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  34451. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  34452. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  34453. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  34454. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  34455. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  34456. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  34457. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  34458. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  34459. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  34460. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  34461. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  34462. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  34463. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  34464. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  34465. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  34466. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  34467. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  34468. if ( json.scale !== undefined ) material.scale = json.scale;
  34469. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  34470. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  34471. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  34472. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  34473. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  34474. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  34475. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  34476. if ( json.visible !== undefined ) material.visible = json.visible;
  34477. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  34478. if ( json.userData !== undefined ) material.userData = json.userData;
  34479. if ( json.vertexColors !== undefined ) {
  34480. if ( typeof json.vertexColors === 'number' ) {
  34481. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  34482. } else {
  34483. material.vertexColors = json.vertexColors;
  34484. }
  34485. }
  34486. // Shader Material
  34487. if ( json.uniforms !== undefined ) {
  34488. for ( const name in json.uniforms ) {
  34489. const uniform = json.uniforms[ name ];
  34490. material.uniforms[ name ] = {};
  34491. switch ( uniform.type ) {
  34492. case 't':
  34493. material.uniforms[ name ].value = getTexture( uniform.value );
  34494. break;
  34495. case 'c':
  34496. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  34497. break;
  34498. case 'v2':
  34499. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  34500. break;
  34501. case 'v3':
  34502. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  34503. break;
  34504. case 'v4':
  34505. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  34506. break;
  34507. case 'm3':
  34508. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  34509. break;
  34510. case 'm4':
  34511. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  34512. break;
  34513. default:
  34514. material.uniforms[ name ].value = uniform.value;
  34515. }
  34516. }
  34517. }
  34518. if ( json.defines !== undefined ) material.defines = json.defines;
  34519. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  34520. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  34521. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  34522. if ( json.extensions !== undefined ) {
  34523. for ( const key in json.extensions ) {
  34524. material.extensions[ key ] = json.extensions[ key ];
  34525. }
  34526. }
  34527. if ( json.lights !== undefined ) material.lights = json.lights;
  34528. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  34529. // for PointsMaterial
  34530. if ( json.size !== undefined ) material.size = json.size;
  34531. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  34532. // maps
  34533. if ( json.map !== undefined ) material.map = getTexture( json.map );
  34534. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  34535. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  34536. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  34537. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  34538. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  34539. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  34540. if ( json.normalScale !== undefined ) {
  34541. let normalScale = json.normalScale;
  34542. if ( Array.isArray( normalScale ) === false ) {
  34543. // Blender exporter used to export a scalar. See #7459
  34544. normalScale = [ normalScale, normalScale ];
  34545. }
  34546. material.normalScale = new Vector2().fromArray( normalScale );
  34547. }
  34548. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  34549. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  34550. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  34551. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  34552. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  34553. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  34554. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  34555. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  34556. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  34557. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  34558. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  34559. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  34560. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  34561. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  34562. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  34563. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  34564. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  34565. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  34566. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  34567. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  34568. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  34569. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  34570. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  34571. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  34572. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  34573. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  34574. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  34575. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  34576. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  34577. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  34578. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  34579. return material;
  34580. }
  34581. /**
  34582. * Textures are not embedded in the material JSON so they have
  34583. * to be injected before the loading process starts.
  34584. *
  34585. * @param {Object} value - A dictionary holding textures for material properties.
  34586. * @return {MaterialLoader} A reference to this material loader.
  34587. */
  34588. setTextures( value ) {
  34589. this.textures = value;
  34590. return this;
  34591. }
  34592. /**
  34593. * Creates a material for the given type.
  34594. *
  34595. * @param {string} type - The material type.
  34596. * @return {Material} The new material.
  34597. */
  34598. createMaterialFromType( type ) {
  34599. return MaterialLoader.createMaterialFromType( type );
  34600. }
  34601. /**
  34602. * Creates a material for the given type.
  34603. *
  34604. * @static
  34605. * @param {string} type - The material type.
  34606. * @return {Material} The new material.
  34607. */
  34608. static createMaterialFromType( type ) {
  34609. const materialLib = {
  34610. ShadowMaterial,
  34611. SpriteMaterial,
  34612. RawShaderMaterial,
  34613. ShaderMaterial,
  34614. PointsMaterial,
  34615. MeshPhysicalMaterial,
  34616. MeshStandardMaterial,
  34617. MeshPhongMaterial,
  34618. MeshToonMaterial,
  34619. MeshNormalMaterial,
  34620. MeshLambertMaterial,
  34621. MeshDepthMaterial,
  34622. MeshDistanceMaterial,
  34623. MeshBasicMaterial,
  34624. MeshMatcapMaterial,
  34625. LineDashedMaterial,
  34626. LineBasicMaterial,
  34627. Material
  34628. };
  34629. return new materialLib[ type ]();
  34630. }
  34631. }
  34632. /**
  34633. * A class with loader utility functions.
  34634. */
  34635. class LoaderUtils {
  34636. /**
  34637. * Extracts the base URL from the given URL.
  34638. *
  34639. * @param {string} url -The URL to extract the base URL from.
  34640. * @return {string} The extracted base URL.
  34641. */
  34642. static extractUrlBase( url ) {
  34643. const index = url.lastIndexOf( '/' );
  34644. if ( index === -1 ) return './';
  34645. return url.slice( 0, index + 1 );
  34646. }
  34647. /**
  34648. * Resolves relative URLs against the given path. Absolute paths, data urls,
  34649. * and blob URLs will be returned as is. Invalid URLs will return an empty
  34650. * string.
  34651. *
  34652. * @param {string} url -The URL to resolve.
  34653. * @param {string} path - The base path for relative URLs to be resolved against.
  34654. * @return {string} The resolved URL.
  34655. */
  34656. static resolveURL( url, path ) {
  34657. // Invalid URL
  34658. if ( typeof url !== 'string' || url === '' ) return '';
  34659. // Host Relative URL
  34660. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  34661. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  34662. }
  34663. // Absolute URL http://,https://,//
  34664. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  34665. // Data URI
  34666. if ( /^data:.*,.*$/i.test( url ) ) return url;
  34667. // Blob URL
  34668. if ( /^blob:.*$/i.test( url ) ) return url;
  34669. // Relative URL
  34670. return path + url;
  34671. }
  34672. }
  34673. /**
  34674. * An instanced version of a geometry.
  34675. */
  34676. class InstancedBufferGeometry extends BufferGeometry {
  34677. /**
  34678. * Constructs a new instanced buffer geometry.
  34679. */
  34680. constructor() {
  34681. super();
  34682. /**
  34683. * This flag can be used for type testing.
  34684. *
  34685. * @type {boolean}
  34686. * @readonly
  34687. * @default true
  34688. */
  34689. this.isInstancedBufferGeometry = true;
  34690. this.type = 'InstancedBufferGeometry';
  34691. /**
  34692. * The instance count.
  34693. *
  34694. * @type {number}
  34695. * @default Infinity
  34696. */
  34697. this.instanceCount = Infinity;
  34698. }
  34699. copy( source ) {
  34700. super.copy( source );
  34701. this.instanceCount = source.instanceCount;
  34702. return this;
  34703. }
  34704. toJSON() {
  34705. const data = super.toJSON();
  34706. data.instanceCount = this.instanceCount;
  34707. data.isInstancedBufferGeometry = true;
  34708. return data;
  34709. }
  34710. }
  34711. /**
  34712. * Class for loading geometries. The files are internally
  34713. * loaded via {@link FileLoader}.
  34714. *
  34715. * ```js
  34716. * const loader = new THREE.BufferGeometryLoader();
  34717. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  34718. *
  34719. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  34720. * const object = new THREE.Mesh( geometry, material );
  34721. * scene.add( object );
  34722. * ```
  34723. *
  34724. * @augments Loader
  34725. */
  34726. class BufferGeometryLoader extends Loader {
  34727. /**
  34728. * Constructs a new geometry loader.
  34729. *
  34730. * @param {LoadingManager} [manager] - The loading manager.
  34731. */
  34732. constructor( manager ) {
  34733. super( manager );
  34734. }
  34735. /**
  34736. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  34737. *
  34738. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34739. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  34740. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34741. * @param {onErrorCallback} onError - Executed when errors occur.
  34742. */
  34743. load( url, onLoad, onProgress, onError ) {
  34744. const scope = this;
  34745. const loader = new FileLoader( scope.manager );
  34746. loader.setPath( scope.path );
  34747. loader.setRequestHeader( scope.requestHeader );
  34748. loader.setWithCredentials( scope.withCredentials );
  34749. loader.load( url, function ( text ) {
  34750. try {
  34751. onLoad( scope.parse( JSON.parse( text ) ) );
  34752. } catch ( e ) {
  34753. if ( onError ) {
  34754. onError( e );
  34755. } else {
  34756. console.error( e );
  34757. }
  34758. scope.manager.itemError( url );
  34759. }
  34760. }, onProgress, onError );
  34761. }
  34762. /**
  34763. * Parses the given JSON object and returns a geometry.
  34764. *
  34765. * @param {Object} json - The serialized geometry.
  34766. * @return {BufferGeometry} The parsed geometry.
  34767. */
  34768. parse( json ) {
  34769. const interleavedBufferMap = {};
  34770. const arrayBufferMap = {};
  34771. function getInterleavedBuffer( json, uuid ) {
  34772. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  34773. const interleavedBuffers = json.interleavedBuffers;
  34774. const interleavedBuffer = interleavedBuffers[ uuid ];
  34775. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  34776. const array = getTypedArray( interleavedBuffer.type, buffer );
  34777. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  34778. ib.uuid = interleavedBuffer.uuid;
  34779. interleavedBufferMap[ uuid ] = ib;
  34780. return ib;
  34781. }
  34782. function getArrayBuffer( json, uuid ) {
  34783. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  34784. const arrayBuffers = json.arrayBuffers;
  34785. const arrayBuffer = arrayBuffers[ uuid ];
  34786. const ab = new Uint32Array( arrayBuffer ).buffer;
  34787. arrayBufferMap[ uuid ] = ab;
  34788. return ab;
  34789. }
  34790. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  34791. const index = json.data.index;
  34792. if ( index !== undefined ) {
  34793. const typedArray = getTypedArray( index.type, index.array );
  34794. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  34795. }
  34796. const attributes = json.data.attributes;
  34797. for ( const key in attributes ) {
  34798. const attribute = attributes[ key ];
  34799. let bufferAttribute;
  34800. if ( attribute.isInterleavedBufferAttribute ) {
  34801. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34802. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34803. } else {
  34804. const typedArray = getTypedArray( attribute.type, attribute.array );
  34805. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  34806. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  34807. }
  34808. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  34809. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  34810. geometry.setAttribute( key, bufferAttribute );
  34811. }
  34812. const morphAttributes = json.data.morphAttributes;
  34813. if ( morphAttributes ) {
  34814. for ( const key in morphAttributes ) {
  34815. const attributeArray = morphAttributes[ key ];
  34816. const array = [];
  34817. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  34818. const attribute = attributeArray[ i ];
  34819. let bufferAttribute;
  34820. if ( attribute.isInterleavedBufferAttribute ) {
  34821. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34822. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34823. } else {
  34824. const typedArray = getTypedArray( attribute.type, attribute.array );
  34825. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  34826. }
  34827. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  34828. array.push( bufferAttribute );
  34829. }
  34830. geometry.morphAttributes[ key ] = array;
  34831. }
  34832. }
  34833. const morphTargetsRelative = json.data.morphTargetsRelative;
  34834. if ( morphTargetsRelative ) {
  34835. geometry.morphTargetsRelative = true;
  34836. }
  34837. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  34838. if ( groups !== undefined ) {
  34839. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  34840. const group = groups[ i ];
  34841. geometry.addGroup( group.start, group.count, group.materialIndex );
  34842. }
  34843. }
  34844. const boundingSphere = json.data.boundingSphere;
  34845. if ( boundingSphere !== undefined ) {
  34846. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  34847. }
  34848. if ( json.name ) geometry.name = json.name;
  34849. if ( json.userData ) geometry.userData = json.userData;
  34850. return geometry;
  34851. }
  34852. }
  34853. /**
  34854. * 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}.
  34855. * The files are internally loaded via {@link FileLoader}.
  34856. *
  34857. * ```js
  34858. * const loader = new THREE.ObjectLoader();
  34859. * const obj = await loader.loadAsync( 'models/json/example.json' );
  34860. * scene.add( obj );
  34861. *
  34862. * // Alternatively, to parse a previously loaded JSON structure
  34863. * const object = await loader.parseAsync( a_json_object );
  34864. * scene.add( object );
  34865. * ```
  34866. *
  34867. * @augments Loader
  34868. */
  34869. class ObjectLoader extends Loader {
  34870. /**
  34871. * Constructs a new object loader.
  34872. *
  34873. * @param {LoadingManager} [manager] - The loading manager.
  34874. */
  34875. constructor( manager ) {
  34876. super( manager );
  34877. }
  34878. /**
  34879. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  34880. *
  34881. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34882. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  34883. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34884. * @param {onErrorCallback} onError - Executed when errors occur.
  34885. */
  34886. load( url, onLoad, onProgress, onError ) {
  34887. const scope = this;
  34888. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  34889. this.resourcePath = this.resourcePath || path;
  34890. const loader = new FileLoader( this.manager );
  34891. loader.setPath( this.path );
  34892. loader.setRequestHeader( this.requestHeader );
  34893. loader.setWithCredentials( this.withCredentials );
  34894. loader.load( url, function ( text ) {
  34895. let json = null;
  34896. try {
  34897. json = JSON.parse( text );
  34898. } catch ( error ) {
  34899. if ( onError !== undefined ) onError( error );
  34900. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  34901. return;
  34902. }
  34903. const metadata = json.metadata;
  34904. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  34905. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  34906. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  34907. return;
  34908. }
  34909. scope.parse( json, onLoad );
  34910. }, onProgress, onError );
  34911. }
  34912. /**
  34913. * Async version of {@link ObjectLoader#load}.
  34914. *
  34915. * @async
  34916. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34917. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34918. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  34919. */
  34920. async loadAsync( url, onProgress ) {
  34921. const scope = this;
  34922. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  34923. this.resourcePath = this.resourcePath || path;
  34924. const loader = new FileLoader( this.manager );
  34925. loader.setPath( this.path );
  34926. loader.setRequestHeader( this.requestHeader );
  34927. loader.setWithCredentials( this.withCredentials );
  34928. const text = await loader.loadAsync( url, onProgress );
  34929. const json = JSON.parse( text );
  34930. const metadata = json.metadata;
  34931. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  34932. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  34933. }
  34934. return await scope.parseAsync( json );
  34935. }
  34936. /**
  34937. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  34938. * but can also be used directly to parse a previously loaded JSON structure.
  34939. *
  34940. * @param {Object} json - The serialized 3D object.
  34941. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  34942. * @return {Object3D} The parsed 3D object.
  34943. */
  34944. parse( json, onLoad ) {
  34945. const animations = this.parseAnimations( json.animations );
  34946. const shapes = this.parseShapes( json.shapes );
  34947. const geometries = this.parseGeometries( json.geometries, shapes );
  34948. const images = this.parseImages( json.images, function () {
  34949. if ( onLoad !== undefined ) onLoad( object );
  34950. } );
  34951. const textures = this.parseTextures( json.textures, images );
  34952. const materials = this.parseMaterials( json.materials, textures );
  34953. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  34954. const skeletons = this.parseSkeletons( json.skeletons, object );
  34955. this.bindSkeletons( object, skeletons );
  34956. this.bindLightTargets( object );
  34957. //
  34958. if ( onLoad !== undefined ) {
  34959. let hasImages = false;
  34960. for ( const uuid in images ) {
  34961. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  34962. hasImages = true;
  34963. break;
  34964. }
  34965. }
  34966. if ( hasImages === false ) onLoad( object );
  34967. }
  34968. return object;
  34969. }
  34970. /**
  34971. * Async version of {@link ObjectLoader#parse}.
  34972. *
  34973. * @param {Object} json - The serialized 3D object.
  34974. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  34975. */
  34976. async parseAsync( json ) {
  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 = await this.parseImagesAsync( json.images );
  34981. const textures = this.parseTextures( json.textures, images );
  34982. const materials = this.parseMaterials( json.materials, textures );
  34983. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  34984. const skeletons = this.parseSkeletons( json.skeletons, object );
  34985. this.bindSkeletons( object, skeletons );
  34986. this.bindLightTargets( object );
  34987. return object;
  34988. }
  34989. // internals
  34990. parseShapes( json ) {
  34991. const shapes = {};
  34992. if ( json !== undefined ) {
  34993. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34994. const shape = new Shape().fromJSON( json[ i ] );
  34995. shapes[ shape.uuid ] = shape;
  34996. }
  34997. }
  34998. return shapes;
  34999. }
  35000. parseSkeletons( json, object ) {
  35001. const skeletons = {};
  35002. const bones = {};
  35003. // generate bone lookup table
  35004. object.traverse( function ( child ) {
  35005. if ( child.isBone ) bones[ child.uuid ] = child;
  35006. } );
  35007. // create skeletons
  35008. if ( json !== undefined ) {
  35009. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35010. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  35011. skeletons[ skeleton.uuid ] = skeleton;
  35012. }
  35013. }
  35014. return skeletons;
  35015. }
  35016. parseGeometries( json, shapes ) {
  35017. const geometries = {};
  35018. if ( json !== undefined ) {
  35019. const bufferGeometryLoader = new BufferGeometryLoader();
  35020. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35021. let geometry;
  35022. const data = json[ i ];
  35023. switch ( data.type ) {
  35024. case 'BufferGeometry':
  35025. case 'InstancedBufferGeometry':
  35026. geometry = bufferGeometryLoader.parse( data );
  35027. break;
  35028. default:
  35029. if ( data.type in Geometries ) {
  35030. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  35031. } else {
  35032. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  35033. }
  35034. }
  35035. geometry.uuid = data.uuid;
  35036. if ( data.name !== undefined ) geometry.name = data.name;
  35037. if ( data.userData !== undefined ) geometry.userData = data.userData;
  35038. geometries[ data.uuid ] = geometry;
  35039. }
  35040. }
  35041. return geometries;
  35042. }
  35043. parseMaterials( json, textures ) {
  35044. const cache = {}; // MultiMaterial
  35045. const materials = {};
  35046. if ( json !== undefined ) {
  35047. const loader = new MaterialLoader();
  35048. loader.setTextures( textures );
  35049. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35050. const data = json[ i ];
  35051. if ( cache[ data.uuid ] === undefined ) {
  35052. cache[ data.uuid ] = loader.parse( data );
  35053. }
  35054. materials[ data.uuid ] = cache[ data.uuid ];
  35055. }
  35056. }
  35057. return materials;
  35058. }
  35059. parseAnimations( json ) {
  35060. const animations = {};
  35061. if ( json !== undefined ) {
  35062. for ( let i = 0; i < json.length; i ++ ) {
  35063. const data = json[ i ];
  35064. const clip = AnimationClip.parse( data );
  35065. animations[ clip.uuid ] = clip;
  35066. }
  35067. }
  35068. return animations;
  35069. }
  35070. parseImages( json, onLoad ) {
  35071. const scope = this;
  35072. const images = {};
  35073. let loader;
  35074. function loadImage( url ) {
  35075. scope.manager.itemStart( url );
  35076. return loader.load( url, function () {
  35077. scope.manager.itemEnd( url );
  35078. }, undefined, function () {
  35079. scope.manager.itemError( url );
  35080. scope.manager.itemEnd( url );
  35081. } );
  35082. }
  35083. function deserializeImage( image ) {
  35084. if ( typeof image === 'string' ) {
  35085. const url = image;
  35086. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35087. return loadImage( path );
  35088. } else {
  35089. if ( image.data ) {
  35090. return {
  35091. data: getTypedArray( image.type, image.data ),
  35092. width: image.width,
  35093. height: image.height
  35094. };
  35095. } else {
  35096. return null;
  35097. }
  35098. }
  35099. }
  35100. if ( json !== undefined && json.length > 0 ) {
  35101. const manager = new LoadingManager( onLoad );
  35102. loader = new ImageLoader( manager );
  35103. loader.setCrossOrigin( this.crossOrigin );
  35104. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35105. const image = json[ i ];
  35106. const url = image.url;
  35107. if ( Array.isArray( url ) ) {
  35108. // load array of images e.g CubeTexture
  35109. const imageArray = [];
  35110. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35111. const currentUrl = url[ j ];
  35112. const deserializedImage = deserializeImage( currentUrl );
  35113. if ( deserializedImage !== null ) {
  35114. if ( deserializedImage instanceof HTMLImageElement ) {
  35115. imageArray.push( deserializedImage );
  35116. } else {
  35117. // special case: handle array of data textures for cube textures
  35118. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35119. }
  35120. }
  35121. }
  35122. images[ image.uuid ] = new Source( imageArray );
  35123. } else {
  35124. // load single image
  35125. const deserializedImage = deserializeImage( image.url );
  35126. images[ image.uuid ] = new Source( deserializedImage );
  35127. }
  35128. }
  35129. }
  35130. return images;
  35131. }
  35132. async parseImagesAsync( json ) {
  35133. const scope = this;
  35134. const images = {};
  35135. let loader;
  35136. async function deserializeImage( image ) {
  35137. if ( typeof image === 'string' ) {
  35138. const url = image;
  35139. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35140. return await loader.loadAsync( path );
  35141. } else {
  35142. if ( image.data ) {
  35143. return {
  35144. data: getTypedArray( image.type, image.data ),
  35145. width: image.width,
  35146. height: image.height
  35147. };
  35148. } else {
  35149. return null;
  35150. }
  35151. }
  35152. }
  35153. if ( json !== undefined && json.length > 0 ) {
  35154. loader = new ImageLoader( this.manager );
  35155. loader.setCrossOrigin( this.crossOrigin );
  35156. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35157. const image = json[ i ];
  35158. const url = image.url;
  35159. if ( Array.isArray( url ) ) {
  35160. // load array of images e.g CubeTexture
  35161. const imageArray = [];
  35162. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35163. const currentUrl = url[ j ];
  35164. const deserializedImage = await deserializeImage( currentUrl );
  35165. if ( deserializedImage !== null ) {
  35166. if ( deserializedImage instanceof HTMLImageElement ) {
  35167. imageArray.push( deserializedImage );
  35168. } else {
  35169. // special case: handle array of data textures for cube textures
  35170. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35171. }
  35172. }
  35173. }
  35174. images[ image.uuid ] = new Source( imageArray );
  35175. } else {
  35176. // load single image
  35177. const deserializedImage = await deserializeImage( image.url );
  35178. images[ image.uuid ] = new Source( deserializedImage );
  35179. }
  35180. }
  35181. }
  35182. return images;
  35183. }
  35184. parseTextures( json, images ) {
  35185. function parseConstant( value, type ) {
  35186. if ( typeof value === 'number' ) return value;
  35187. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  35188. return type[ value ];
  35189. }
  35190. const textures = {};
  35191. if ( json !== undefined ) {
  35192. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35193. const data = json[ i ];
  35194. if ( data.image === undefined ) {
  35195. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  35196. }
  35197. if ( images[ data.image ] === undefined ) {
  35198. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  35199. }
  35200. const source = images[ data.image ];
  35201. const image = source.data;
  35202. let texture;
  35203. if ( Array.isArray( image ) ) {
  35204. texture = new CubeTexture();
  35205. if ( image.length === 6 ) texture.needsUpdate = true;
  35206. } else {
  35207. if ( image && image.data ) {
  35208. texture = new DataTexture();
  35209. } else {
  35210. texture = new Texture();
  35211. }
  35212. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  35213. }
  35214. texture.source = source;
  35215. texture.uuid = data.uuid;
  35216. if ( data.name !== undefined ) texture.name = data.name;
  35217. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  35218. if ( data.channel !== undefined ) texture.channel = data.channel;
  35219. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  35220. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  35221. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  35222. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  35223. if ( data.wrap !== undefined ) {
  35224. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  35225. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  35226. }
  35227. if ( data.format !== undefined ) texture.format = data.format;
  35228. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  35229. if ( data.type !== undefined ) texture.type = data.type;
  35230. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  35231. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  35232. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  35233. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  35234. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  35235. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  35236. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  35237. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  35238. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  35239. if ( data.userData !== undefined ) texture.userData = data.userData;
  35240. textures[ data.uuid ] = texture;
  35241. }
  35242. }
  35243. return textures;
  35244. }
  35245. parseObject( data, geometries, materials, textures, animations ) {
  35246. let object;
  35247. function getGeometry( name ) {
  35248. if ( geometries[ name ] === undefined ) {
  35249. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  35250. }
  35251. return geometries[ name ];
  35252. }
  35253. function getMaterial( name ) {
  35254. if ( name === undefined ) return undefined;
  35255. if ( Array.isArray( name ) ) {
  35256. const array = [];
  35257. for ( let i = 0, l = name.length; i < l; i ++ ) {
  35258. const uuid = name[ i ];
  35259. if ( materials[ uuid ] === undefined ) {
  35260. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  35261. }
  35262. array.push( materials[ uuid ] );
  35263. }
  35264. return array;
  35265. }
  35266. if ( materials[ name ] === undefined ) {
  35267. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  35268. }
  35269. return materials[ name ];
  35270. }
  35271. function getTexture( uuid ) {
  35272. if ( textures[ uuid ] === undefined ) {
  35273. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  35274. }
  35275. return textures[ uuid ];
  35276. }
  35277. let geometry, material;
  35278. switch ( data.type ) {
  35279. case 'Scene':
  35280. object = new Scene();
  35281. if ( data.background !== undefined ) {
  35282. if ( Number.isInteger( data.background ) ) {
  35283. object.background = new Color( data.background );
  35284. } else {
  35285. object.background = getTexture( data.background );
  35286. }
  35287. }
  35288. if ( data.environment !== undefined ) {
  35289. object.environment = getTexture( data.environment );
  35290. }
  35291. if ( data.fog !== undefined ) {
  35292. if ( data.fog.type === 'Fog' ) {
  35293. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  35294. } else if ( data.fog.type === 'FogExp2' ) {
  35295. object.fog = new FogExp2( data.fog.color, data.fog.density );
  35296. }
  35297. if ( data.fog.name !== '' ) {
  35298. object.fog.name = data.fog.name;
  35299. }
  35300. }
  35301. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  35302. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  35303. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  35304. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  35305. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  35306. break;
  35307. case 'PerspectiveCamera':
  35308. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  35309. if ( data.focus !== undefined ) object.focus = data.focus;
  35310. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35311. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  35312. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  35313. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35314. break;
  35315. case 'OrthographicCamera':
  35316. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  35317. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35318. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35319. break;
  35320. case 'AmbientLight':
  35321. object = new AmbientLight( data.color, data.intensity );
  35322. break;
  35323. case 'DirectionalLight':
  35324. object = new DirectionalLight( data.color, data.intensity );
  35325. object.target = data.target || '';
  35326. break;
  35327. case 'PointLight':
  35328. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  35329. break;
  35330. case 'RectAreaLight':
  35331. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  35332. break;
  35333. case 'SpotLight':
  35334. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  35335. object.target = data.target || '';
  35336. break;
  35337. case 'HemisphereLight':
  35338. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  35339. break;
  35340. case 'LightProbe':
  35341. object = new LightProbe().fromJSON( data );
  35342. break;
  35343. case 'SkinnedMesh':
  35344. geometry = getGeometry( data.geometry );
  35345. material = getMaterial( data.material );
  35346. object = new SkinnedMesh( geometry, material );
  35347. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  35348. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  35349. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  35350. break;
  35351. case 'Mesh':
  35352. geometry = getGeometry( data.geometry );
  35353. material = getMaterial( data.material );
  35354. object = new Mesh( geometry, material );
  35355. break;
  35356. case 'InstancedMesh':
  35357. geometry = getGeometry( data.geometry );
  35358. material = getMaterial( data.material );
  35359. const count = data.count;
  35360. const instanceMatrix = data.instanceMatrix;
  35361. const instanceColor = data.instanceColor;
  35362. object = new InstancedMesh( geometry, material, count );
  35363. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  35364. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  35365. break;
  35366. case 'BatchedMesh':
  35367. geometry = getGeometry( data.geometry );
  35368. material = getMaterial( data.material );
  35369. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  35370. object.geometry = geometry;
  35371. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  35372. object.sortObjects = data.sortObjects;
  35373. object._drawRanges = data.drawRanges;
  35374. object._reservedRanges = data.reservedRanges;
  35375. object._geometryInfo = data.geometryInfo.map( info => {
  35376. let box = null;
  35377. let sphere = null;
  35378. if ( info.boundingBox !== undefined ) {
  35379. box = new Box3().fromJSON( info.boundingBox );
  35380. }
  35381. if ( info.boundingSphere !== undefined ) {
  35382. sphere = new Sphere().fromJSON( info.boundingSphere );
  35383. }
  35384. return {
  35385. ...info,
  35386. boundingBox: box,
  35387. boundingSphere: sphere
  35388. };
  35389. } );
  35390. object._instanceInfo = data.instanceInfo;
  35391. object._availableInstanceIds = data._availableInstanceIds;
  35392. object._availableGeometryIds = data._availableGeometryIds;
  35393. object._nextIndexStart = data.nextIndexStart;
  35394. object._nextVertexStart = data.nextVertexStart;
  35395. object._geometryCount = data.geometryCount;
  35396. object._maxInstanceCount = data.maxInstanceCount;
  35397. object._maxVertexCount = data.maxVertexCount;
  35398. object._maxIndexCount = data.maxIndexCount;
  35399. object._geometryInitialized = data.geometryInitialized;
  35400. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  35401. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  35402. if ( data.colorsTexture !== undefined ) {
  35403. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  35404. }
  35405. if ( data.boundingSphere !== undefined ) {
  35406. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  35407. }
  35408. if ( data.boundingBox !== undefined ) {
  35409. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  35410. }
  35411. break;
  35412. case 'LOD':
  35413. object = new LOD();
  35414. break;
  35415. case 'Line':
  35416. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  35417. break;
  35418. case 'LineLoop':
  35419. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  35420. break;
  35421. case 'LineSegments':
  35422. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  35423. break;
  35424. case 'PointCloud':
  35425. case 'Points':
  35426. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  35427. break;
  35428. case 'Sprite':
  35429. object = new Sprite( getMaterial( data.material ) );
  35430. break;
  35431. case 'Group':
  35432. object = new Group();
  35433. break;
  35434. case 'Bone':
  35435. object = new Bone();
  35436. break;
  35437. default:
  35438. object = new Object3D();
  35439. }
  35440. object.uuid = data.uuid;
  35441. if ( data.name !== undefined ) object.name = data.name;
  35442. if ( data.matrix !== undefined ) {
  35443. object.matrix.fromArray( data.matrix );
  35444. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  35445. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  35446. } else {
  35447. if ( data.position !== undefined ) object.position.fromArray( data.position );
  35448. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  35449. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  35450. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  35451. }
  35452. if ( data.up !== undefined ) object.up.fromArray( data.up );
  35453. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  35454. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  35455. if ( data.shadow ) {
  35456. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  35457. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  35458. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  35459. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  35460. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  35461. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  35462. }
  35463. if ( data.visible !== undefined ) object.visible = data.visible;
  35464. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  35465. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  35466. if ( data.userData !== undefined ) object.userData = data.userData;
  35467. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  35468. if ( data.children !== undefined ) {
  35469. const children = data.children;
  35470. for ( let i = 0; i < children.length; i ++ ) {
  35471. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  35472. }
  35473. }
  35474. if ( data.animations !== undefined ) {
  35475. const objectAnimations = data.animations;
  35476. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  35477. const uuid = objectAnimations[ i ];
  35478. object.animations.push( animations[ uuid ] );
  35479. }
  35480. }
  35481. if ( data.type === 'LOD' ) {
  35482. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  35483. const levels = data.levels;
  35484. for ( let l = 0; l < levels.length; l ++ ) {
  35485. const level = levels[ l ];
  35486. const child = object.getObjectByProperty( 'uuid', level.object );
  35487. if ( child !== undefined ) {
  35488. object.addLevel( child, level.distance, level.hysteresis );
  35489. }
  35490. }
  35491. }
  35492. return object;
  35493. }
  35494. bindSkeletons( object, skeletons ) {
  35495. if ( Object.keys( skeletons ).length === 0 ) return;
  35496. object.traverse( function ( child ) {
  35497. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  35498. const skeleton = skeletons[ child.skeleton ];
  35499. if ( skeleton === undefined ) {
  35500. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  35501. } else {
  35502. child.bind( skeleton, child.bindMatrix );
  35503. }
  35504. }
  35505. } );
  35506. }
  35507. bindLightTargets( object ) {
  35508. object.traverse( function ( child ) {
  35509. if ( child.isDirectionalLight || child.isSpotLight ) {
  35510. const uuid = child.target;
  35511. const target = object.getObjectByProperty( 'uuid', uuid );
  35512. if ( target !== undefined ) {
  35513. child.target = target;
  35514. } else {
  35515. child.target = new Object3D();
  35516. }
  35517. }
  35518. } );
  35519. }
  35520. }
  35521. const TEXTURE_MAPPING = {
  35522. UVMapping: UVMapping,
  35523. CubeReflectionMapping: CubeReflectionMapping,
  35524. CubeRefractionMapping: CubeRefractionMapping,
  35525. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  35526. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  35527. CubeUVReflectionMapping: CubeUVReflectionMapping
  35528. };
  35529. const TEXTURE_WRAPPING = {
  35530. RepeatWrapping: RepeatWrapping,
  35531. ClampToEdgeWrapping: ClampToEdgeWrapping,
  35532. MirroredRepeatWrapping: MirroredRepeatWrapping
  35533. };
  35534. const TEXTURE_FILTER = {
  35535. NearestFilter: NearestFilter,
  35536. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  35537. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  35538. LinearFilter: LinearFilter,
  35539. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  35540. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  35541. };
  35542. const _errorMap = new WeakMap();
  35543. /**
  35544. * A loader for loading images as an [ImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap}.
  35545. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  35546. * textures for rendering.
  35547. *
  35548. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  35549. * They needs these configuration on bitmap creation unlike regular images need them on uploading to GPU.
  35550. *
  35551. * You need to set the equivalent options via {@link ImageBitmapLoader#setOptions} instead.
  35552. *
  35553. * Also note that unlike {@link FileLoader}, this loader avoids multiple concurrent requests to the same URL only if `Cache` is enabled.
  35554. *
  35555. * ```js
  35556. * const loader = new THREE.ImageBitmapLoader();
  35557. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  35558. * const imageBitmap = await loader.loadAsync( 'image.png' );
  35559. *
  35560. * const texture = new THREE.Texture( imageBitmap );
  35561. * texture.needsUpdate = true;
  35562. * ```
  35563. *
  35564. * @augments Loader
  35565. */
  35566. class ImageBitmapLoader extends Loader {
  35567. /**
  35568. * Constructs a new image bitmap loader.
  35569. *
  35570. * @param {LoadingManager} [manager] - The loading manager.
  35571. */
  35572. constructor( manager ) {
  35573. super( manager );
  35574. /**
  35575. * This flag can be used for type testing.
  35576. *
  35577. * @type {boolean}
  35578. * @readonly
  35579. * @default true
  35580. */
  35581. this.isImageBitmapLoader = true;
  35582. if ( typeof createImageBitmap === 'undefined' ) {
  35583. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  35584. }
  35585. if ( typeof fetch === 'undefined' ) {
  35586. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  35587. }
  35588. /**
  35589. * Represents the loader options.
  35590. *
  35591. * @type {Object}
  35592. * @default {premultiplyAlpha:'none'}
  35593. */
  35594. this.options = { premultiplyAlpha: 'none' };
  35595. /**
  35596. * Used for aborting requests.
  35597. *
  35598. * @private
  35599. * @type {AbortController}
  35600. */
  35601. this._abortController = new AbortController();
  35602. }
  35603. /**
  35604. * Sets the given loader options. The structure of the object must match the `options` parameter of
  35605. * [createImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap}.
  35606. *
  35607. * @param {Object} options - The loader options to set.
  35608. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  35609. */
  35610. setOptions( options ) {
  35611. this.options = options;
  35612. return this;
  35613. }
  35614. /**
  35615. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  35616. *
  35617. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35618. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  35619. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  35620. * @param {onErrorCallback} onError - Executed when errors occur.
  35621. * @return {ImageBitmap|undefined} The image bitmap.
  35622. */
  35623. load( url, onLoad, onProgress, onError ) {
  35624. if ( url === undefined ) url = '';
  35625. if ( this.path !== undefined ) url = this.path + url;
  35626. url = this.manager.resolveURL( url );
  35627. const scope = this;
  35628. const cached = Cache.get( `image-bitmap:${url}` );
  35629. if ( cached !== undefined ) {
  35630. scope.manager.itemStart( url );
  35631. // If cached is a promise, wait for it to resolve
  35632. if ( cached.then ) {
  35633. cached.then( imageBitmap => {
  35634. // check if there is an error for the cached promise
  35635. if ( _errorMap.has( cached ) === true ) {
  35636. if ( onError ) onError( _errorMap.get( cached ) );
  35637. scope.manager.itemError( url );
  35638. scope.manager.itemEnd( url );
  35639. } else {
  35640. if ( onLoad ) onLoad( imageBitmap );
  35641. scope.manager.itemEnd( url );
  35642. return imageBitmap;
  35643. }
  35644. } );
  35645. return;
  35646. }
  35647. // If cached is not a promise (i.e., it's already an imageBitmap)
  35648. setTimeout( function () {
  35649. if ( onLoad ) onLoad( cached );
  35650. scope.manager.itemEnd( url );
  35651. }, 0 );
  35652. return cached;
  35653. }
  35654. const fetchOptions = {};
  35655. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  35656. fetchOptions.headers = this.requestHeader;
  35657. fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal;
  35658. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  35659. return res.blob();
  35660. } ).then( function ( blob ) {
  35661. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  35662. } ).then( function ( imageBitmap ) {
  35663. Cache.add( `image-bitmap:${url}`, imageBitmap );
  35664. if ( onLoad ) onLoad( imageBitmap );
  35665. scope.manager.itemEnd( url );
  35666. return imageBitmap;
  35667. } ).catch( function ( e ) {
  35668. if ( onError ) onError( e );
  35669. _errorMap.set( promise, e );
  35670. Cache.remove( `image-bitmap:${url}` );
  35671. scope.manager.itemError( url );
  35672. scope.manager.itemEnd( url );
  35673. } );
  35674. Cache.add( `image-bitmap:${url}`, promise );
  35675. scope.manager.itemStart( url );
  35676. }
  35677. /**
  35678. * Aborts ongoing fetch requests.
  35679. *
  35680. * @return {ImageBitmapLoader} A reference to this instance.
  35681. */
  35682. abort() {
  35683. this._abortController.abort();
  35684. this._abortController = new AbortController();
  35685. return this;
  35686. }
  35687. }
  35688. let _context;
  35689. /**
  35690. * Manages the global audio context in the engine.
  35691. *
  35692. * @hideconstructor
  35693. */
  35694. class AudioContext {
  35695. /**
  35696. * Returns the global native audio context.
  35697. *
  35698. * @return {AudioContext} The native audio context.
  35699. */
  35700. static getContext() {
  35701. if ( _context === undefined ) {
  35702. _context = new ( window.AudioContext || window.webkitAudioContext )();
  35703. }
  35704. return _context;
  35705. }
  35706. /**
  35707. * Allows to set the global native audio context from outside.
  35708. *
  35709. * @param {AudioContext} value - The native context to set.
  35710. */
  35711. static setContext( value ) {
  35712. _context = value;
  35713. }
  35714. }
  35715. /**
  35716. * Class for loading audio buffers. Audios are internally
  35717. * loaded via {@link FileLoader}.
  35718. *
  35719. * ```js
  35720. * const audioListener = new THREE.AudioListener();
  35721. * const ambientSound = new THREE.Audio( audioListener );
  35722. *
  35723. * const loader = new THREE.AudioLoader();
  35724. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  35725. *
  35726. * ambientSound.setBuffer( audioBuffer );
  35727. * ambientSound.play();
  35728. * ```
  35729. *
  35730. * @augments Loader
  35731. */
  35732. class AudioLoader extends Loader {
  35733. /**
  35734. * Constructs a new audio loader.
  35735. *
  35736. * @param {LoadingManager} [manager] - The loading manager.
  35737. */
  35738. constructor( manager ) {
  35739. super( manager );
  35740. }
  35741. /**
  35742. * Starts loading from the given URL and passes the loaded audio buffer
  35743. * to the `onLoad()` callback.
  35744. *
  35745. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35746. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  35747. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35748. * @param {onErrorCallback} onError - Executed when errors occur.
  35749. */
  35750. load( url, onLoad, onProgress, onError ) {
  35751. const scope = this;
  35752. const loader = new FileLoader( this.manager );
  35753. loader.setResponseType( 'arraybuffer' );
  35754. loader.setPath( this.path );
  35755. loader.setRequestHeader( this.requestHeader );
  35756. loader.setWithCredentials( this.withCredentials );
  35757. loader.load( url, function ( buffer ) {
  35758. try {
  35759. // Create a copy of the buffer. The `decodeAudioData` method
  35760. // detaches the buffer when complete, preventing reuse.
  35761. const bufferCopy = buffer.slice( 0 );
  35762. const context = AudioContext.getContext();
  35763. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  35764. onLoad( audioBuffer );
  35765. } ).catch( handleError );
  35766. } catch ( e ) {
  35767. handleError( e );
  35768. }
  35769. }, onProgress, onError );
  35770. function handleError( e ) {
  35771. if ( onError ) {
  35772. onError( e );
  35773. } else {
  35774. console.error( e );
  35775. }
  35776. scope.manager.itemError( url );
  35777. }
  35778. }
  35779. }
  35780. const _eyeRight = /*@__PURE__*/ new Matrix4();
  35781. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  35782. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  35783. /**
  35784. * A special type of camera that uses two perspective cameras with
  35785. * stereoscopic projection. Can be used for rendering stereo effects
  35786. * like [3D Anaglyph]{@link https://en.wikipedia.org/wiki/Anaglyph_3D} or
  35787. * [Parallax Barrier]{@link https://en.wikipedia.org/wiki/parallax_barrier}.
  35788. */
  35789. class StereoCamera {
  35790. /**
  35791. * Constructs a new stereo camera.
  35792. */
  35793. constructor() {
  35794. /**
  35795. * The type property is used for detecting the object type
  35796. * in context of serialization/deserialization.
  35797. *
  35798. * @type {string}
  35799. * @readonly
  35800. */
  35801. this.type = 'StereoCamera';
  35802. /**
  35803. * The aspect.
  35804. *
  35805. * @type {number}
  35806. * @default 1
  35807. */
  35808. this.aspect = 1;
  35809. /**
  35810. * The eye separation which represents the distance
  35811. * between the left and right camera.
  35812. *
  35813. * @type {number}
  35814. * @default 0.064
  35815. */
  35816. this.eyeSep = 0.064;
  35817. /**
  35818. * The camera representing the left eye. This is added to layer `1` so objects to be
  35819. * rendered by the left camera must also be added to this layer.
  35820. *
  35821. * @type {PerspectiveCamera}
  35822. */
  35823. this.cameraL = new PerspectiveCamera();
  35824. this.cameraL.layers.enable( 1 );
  35825. this.cameraL.matrixAutoUpdate = false;
  35826. /**
  35827. * The camera representing the right eye. This is added to layer `2` so objects to be
  35828. * rendered by the right camera must also be added to this layer.
  35829. *
  35830. * @type {PerspectiveCamera}
  35831. */
  35832. this.cameraR = new PerspectiveCamera();
  35833. this.cameraR.layers.enable( 2 );
  35834. this.cameraR.matrixAutoUpdate = false;
  35835. this._cache = {
  35836. focus: null,
  35837. fov: null,
  35838. aspect: null,
  35839. near: null,
  35840. far: null,
  35841. zoom: null,
  35842. eyeSep: null
  35843. };
  35844. }
  35845. /**
  35846. * Updates the stereo camera based on the given perspective camera.
  35847. *
  35848. * @param {PerspectiveCamera} camera - The perspective camera.
  35849. */
  35850. update( camera ) {
  35851. const cache = this._cache;
  35852. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  35853. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  35854. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  35855. if ( needsUpdate ) {
  35856. cache.focus = camera.focus;
  35857. cache.fov = camera.fov;
  35858. cache.aspect = camera.aspect * this.aspect;
  35859. cache.near = camera.near;
  35860. cache.far = camera.far;
  35861. cache.zoom = camera.zoom;
  35862. cache.eyeSep = this.eyeSep;
  35863. // Off-axis stereoscopic effect based on
  35864. // http://paulbourke.net/stereographics/stereorender/
  35865. _projectionMatrix.copy( camera.projectionMatrix );
  35866. const eyeSepHalf = cache.eyeSep / 2;
  35867. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  35868. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  35869. let xmin, xmax;
  35870. // translate xOffset
  35871. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  35872. _eyeRight.elements[ 12 ] = eyeSepHalf;
  35873. // for left eye
  35874. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  35875. xmax = ymax * cache.aspect + eyeSepOnProjection;
  35876. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  35877. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  35878. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  35879. // for right eye
  35880. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  35881. xmax = ymax * cache.aspect - eyeSepOnProjection;
  35882. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  35883. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  35884. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  35885. }
  35886. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  35887. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  35888. }
  35889. }
  35890. /**
  35891. * This type of camera can be used in order to efficiently render a scene with a
  35892. * predefined set of cameras. This is an important performance aspect for
  35893. * rendering VR scenes.
  35894. *
  35895. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  35896. * to define for each sub camera the `viewport` property which determines the
  35897. * part of the viewport that is rendered with this camera.
  35898. *
  35899. * @augments PerspectiveCamera
  35900. */
  35901. class ArrayCamera extends PerspectiveCamera {
  35902. /**
  35903. * Constructs a new array camera.
  35904. *
  35905. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  35906. */
  35907. constructor( array = [] ) {
  35908. super();
  35909. /**
  35910. * This flag can be used for type testing.
  35911. *
  35912. * @type {boolean}
  35913. * @readonly
  35914. * @default true
  35915. */
  35916. this.isArrayCamera = true;
  35917. /**
  35918. * Whether this camera is used with multiview rendering or not.
  35919. *
  35920. * @type {boolean}
  35921. * @readonly
  35922. * @default false
  35923. */
  35924. this.isMultiViewCamera = false;
  35925. /**
  35926. * An array of perspective sub cameras.
  35927. *
  35928. * @type {Array<PerspectiveCamera>}
  35929. */
  35930. this.cameras = array;
  35931. }
  35932. }
  35933. /**
  35934. * Class for keeping track of time.
  35935. */
  35936. class Clock {
  35937. /**
  35938. * Constructs a new clock.
  35939. *
  35940. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  35941. * `getDelta()` is called for the first time.
  35942. */
  35943. constructor( autoStart = true ) {
  35944. /**
  35945. * If set to `true`, the clock starts automatically when `getDelta()` is called
  35946. * for the first time.
  35947. *
  35948. * @type {boolean}
  35949. * @default true
  35950. */
  35951. this.autoStart = autoStart;
  35952. /**
  35953. * Holds the time at which the clock's `start()` method was last called.
  35954. *
  35955. * @type {number}
  35956. * @default 0
  35957. */
  35958. this.startTime = 0;
  35959. /**
  35960. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  35961. * `getDelta()` methods were last called.
  35962. *
  35963. * @type {number}
  35964. * @default 0
  35965. */
  35966. this.oldTime = 0;
  35967. /**
  35968. * Keeps track of the total time that the clock has been running.
  35969. *
  35970. * @type {number}
  35971. * @default 0
  35972. */
  35973. this.elapsedTime = 0;
  35974. /**
  35975. * Whether the clock is running or not.
  35976. *
  35977. * @type {boolean}
  35978. * @default true
  35979. */
  35980. this.running = false;
  35981. }
  35982. /**
  35983. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  35984. * called by the class.
  35985. */
  35986. start() {
  35987. this.startTime = performance.now();
  35988. this.oldTime = this.startTime;
  35989. this.elapsedTime = 0;
  35990. this.running = true;
  35991. }
  35992. /**
  35993. * Stops the clock.
  35994. */
  35995. stop() {
  35996. this.getElapsedTime();
  35997. this.running = false;
  35998. this.autoStart = false;
  35999. }
  36000. /**
  36001. * Returns the elapsed time in seconds.
  36002. *
  36003. * @return {number} The elapsed time.
  36004. */
  36005. getElapsedTime() {
  36006. this.getDelta();
  36007. return this.elapsedTime;
  36008. }
  36009. /**
  36010. * Returns the delta time in seconds.
  36011. *
  36012. * @return {number} The delta time.
  36013. */
  36014. getDelta() {
  36015. let diff = 0;
  36016. if ( this.autoStart && ! this.running ) {
  36017. this.start();
  36018. return 0;
  36019. }
  36020. if ( this.running ) {
  36021. const newTime = performance.now();
  36022. diff = ( newTime - this.oldTime ) / 1000;
  36023. this.oldTime = newTime;
  36024. this.elapsedTime += diff;
  36025. }
  36026. return diff;
  36027. }
  36028. }
  36029. const _position$1 = /*@__PURE__*/ new Vector3();
  36030. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  36031. const _scale$1 = /*@__PURE__*/ new Vector3();
  36032. const _forward = /*@__PURE__*/ new Vector3();
  36033. const _up = /*@__PURE__*/ new Vector3();
  36034. /**
  36035. * The class represents a virtual listener of the all positional and non-positional audio effects
  36036. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  36037. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  36038. *
  36039. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  36040. * camera represents the 3D transformation of the listener.
  36041. *
  36042. * @augments Object3D
  36043. */
  36044. class AudioListener extends Object3D {
  36045. /**
  36046. * Constructs a new audio listener.
  36047. */
  36048. constructor() {
  36049. super();
  36050. this.type = 'AudioListener';
  36051. /**
  36052. * The native audio context.
  36053. *
  36054. * @type {AudioContext}
  36055. * @readonly
  36056. */
  36057. this.context = AudioContext.getContext();
  36058. /**
  36059. * The gain node used for volume control.
  36060. *
  36061. * @type {GainNode}
  36062. * @readonly
  36063. */
  36064. this.gain = this.context.createGain();
  36065. this.gain.connect( this.context.destination );
  36066. /**
  36067. * An optional filter.
  36068. *
  36069. * Defined via {@link AudioListener#setFilter}.
  36070. *
  36071. * @type {?AudioNode}
  36072. * @default null
  36073. * @readonly
  36074. */
  36075. this.filter = null;
  36076. /**
  36077. * Time delta values required for `linearRampToValueAtTime()` usage.
  36078. *
  36079. * @type {number}
  36080. * @default 0
  36081. * @readonly
  36082. */
  36083. this.timeDelta = 0;
  36084. // private
  36085. this._clock = new Clock();
  36086. }
  36087. /**
  36088. * Returns the listener's input node.
  36089. *
  36090. * This method is used by other audio nodes to connect to this listener.
  36091. *
  36092. * @return {GainNode} The input node.
  36093. */
  36094. getInput() {
  36095. return this.gain;
  36096. }
  36097. /**
  36098. * Removes the current filter from this listener.
  36099. *
  36100. * @return {AudioListener} A reference to this listener.
  36101. */
  36102. removeFilter() {
  36103. if ( this.filter !== null ) {
  36104. this.gain.disconnect( this.filter );
  36105. this.filter.disconnect( this.context.destination );
  36106. this.gain.connect( this.context.destination );
  36107. this.filter = null;
  36108. }
  36109. return this;
  36110. }
  36111. /**
  36112. * Returns the current set filter.
  36113. *
  36114. * @return {?AudioNode} The filter.
  36115. */
  36116. getFilter() {
  36117. return this.filter;
  36118. }
  36119. /**
  36120. * Sets the given filter to this listener.
  36121. *
  36122. * @param {AudioNode} value - The filter to set.
  36123. * @return {AudioListener} A reference to this listener.
  36124. */
  36125. setFilter( value ) {
  36126. if ( this.filter !== null ) {
  36127. this.gain.disconnect( this.filter );
  36128. this.filter.disconnect( this.context.destination );
  36129. } else {
  36130. this.gain.disconnect( this.context.destination );
  36131. }
  36132. this.filter = value;
  36133. this.gain.connect( this.filter );
  36134. this.filter.connect( this.context.destination );
  36135. return this;
  36136. }
  36137. /**
  36138. * Returns the applications master volume.
  36139. *
  36140. * @return {number} The master volume.
  36141. */
  36142. getMasterVolume() {
  36143. return this.gain.gain.value;
  36144. }
  36145. /**
  36146. * Sets the applications master volume. This volume setting affects
  36147. * all audio nodes in the scene.
  36148. *
  36149. * @param {number} value - The master volume to set.
  36150. * @return {AudioListener} A reference to this listener.
  36151. */
  36152. setMasterVolume( value ) {
  36153. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36154. return this;
  36155. }
  36156. updateMatrixWorld( force ) {
  36157. super.updateMatrixWorld( force );
  36158. const listener = this.context.listener;
  36159. this.timeDelta = this._clock.getDelta();
  36160. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  36161. // the initial forward and up directions must be orthogonal
  36162. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  36163. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  36164. if ( listener.positionX ) {
  36165. // code path for Chrome (see #14393)
  36166. const endTime = this.context.currentTime + this.timeDelta;
  36167. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  36168. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  36169. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  36170. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  36171. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  36172. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  36173. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  36174. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  36175. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  36176. } else {
  36177. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  36178. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  36179. }
  36180. }
  36181. }
  36182. /**
  36183. * Represents a non-positional ( global ) audio object.
  36184. *
  36185. * This and related audio modules make use of the [Web Audio API]{@link https://www.w3.org/TR/webaudio-1.1/}.
  36186. *
  36187. * ```js
  36188. * // create an AudioListener and add it to the camera
  36189. * const listener = new THREE.AudioListener();
  36190. * camera.add( listener );
  36191. *
  36192. * // create a global audio source
  36193. * const sound = new THREE.Audio( listener );
  36194. *
  36195. * // load a sound and set it as the Audio object's buffer
  36196. * const audioLoader = new THREE.AudioLoader();
  36197. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36198. * sound.setBuffer( buffer );
  36199. * sound.setLoop( true );
  36200. * sound.setVolume( 0.5 );
  36201. * sound.play();
  36202. * });
  36203. * ```
  36204. *
  36205. * @augments Object3D
  36206. */
  36207. class Audio extends Object3D {
  36208. /**
  36209. * Constructs a new audio.
  36210. *
  36211. * @param {AudioListener} listener - The global audio listener.
  36212. */
  36213. constructor( listener ) {
  36214. super();
  36215. this.type = 'Audio';
  36216. /**
  36217. * The global audio listener.
  36218. *
  36219. * @type {AudioListener}
  36220. * @readonly
  36221. */
  36222. this.listener = listener;
  36223. /**
  36224. * The audio context.
  36225. *
  36226. * @type {AudioContext}
  36227. * @readonly
  36228. */
  36229. this.context = listener.context;
  36230. /**
  36231. * The gain node used for volume control.
  36232. *
  36233. * @type {GainNode}
  36234. * @readonly
  36235. */
  36236. this.gain = this.context.createGain();
  36237. this.gain.connect( listener.getInput() );
  36238. /**
  36239. * Whether to start playback automatically or not.
  36240. *
  36241. * @type {boolean}
  36242. * @default false
  36243. */
  36244. this.autoplay = false;
  36245. /**
  36246. * A reference to an audio buffer.
  36247. *
  36248. * Defined via {@link Audio#setBuffer}.
  36249. *
  36250. * @type {?AudioBuffer}
  36251. * @default null
  36252. * @readonly
  36253. */
  36254. this.buffer = null;
  36255. /**
  36256. * Modify pitch, measured in cents. +/- 100 is a semitone.
  36257. * +/- 1200 is an octave.
  36258. *
  36259. * Defined via {@link Audio#setDetune}.
  36260. *
  36261. * @type {number}
  36262. * @default 0
  36263. * @readonly
  36264. */
  36265. this.detune = 0;
  36266. /**
  36267. * Whether the audio should loop or not.
  36268. *
  36269. * Defined via {@link Audio#setLoop}.
  36270. *
  36271. * @type {boolean}
  36272. * @default false
  36273. * @readonly
  36274. */
  36275. this.loop = false;
  36276. /**
  36277. * Defines where in the audio buffer the replay should
  36278. * start, in seconds.
  36279. *
  36280. * @type {number}
  36281. * @default 0
  36282. */
  36283. this.loopStart = 0;
  36284. /**
  36285. * Defines where in the audio buffer the replay should
  36286. * stop, in seconds.
  36287. *
  36288. * @type {number}
  36289. * @default 0
  36290. */
  36291. this.loopEnd = 0;
  36292. /**
  36293. * An offset to the time within the audio buffer the playback
  36294. * should begin, in seconds.
  36295. *
  36296. * @type {number}
  36297. * @default 0
  36298. */
  36299. this.offset = 0;
  36300. /**
  36301. * Overrides the default duration of the audio.
  36302. *
  36303. * @type {undefined|number}
  36304. * @default undefined
  36305. */
  36306. this.duration = undefined;
  36307. /**
  36308. * The playback speed.
  36309. *
  36310. * Defined via {@link Audio#setPlaybackRate}.
  36311. *
  36312. * @type {number}
  36313. * @readonly
  36314. * @default 1
  36315. */
  36316. this.playbackRate = 1;
  36317. /**
  36318. * Indicates whether the audio is playing or not.
  36319. *
  36320. * This flag will be automatically set when using {@link Audio#play},
  36321. * {@link Audio#pause}, {@link Audio#stop}.
  36322. *
  36323. * @type {boolean}
  36324. * @readonly
  36325. * @default false
  36326. */
  36327. this.isPlaying = false;
  36328. /**
  36329. * Indicates whether the audio playback can be controlled
  36330. * with method like {@link Audio#play} or {@link Audio#pause}.
  36331. *
  36332. * This flag will be automatically set when audio sources are
  36333. * defined.
  36334. *
  36335. * @type {boolean}
  36336. * @readonly
  36337. * @default true
  36338. */
  36339. this.hasPlaybackControl = true;
  36340. /**
  36341. * Holds a reference to the current audio source.
  36342. *
  36343. * The property is automatically by one of the `set*()` methods.
  36344. *
  36345. * @type {?AudioNode}
  36346. * @readonly
  36347. * @default null
  36348. */
  36349. this.source = null;
  36350. /**
  36351. * Defines the source type.
  36352. *
  36353. * The property is automatically by one of the `set*()` methods.
  36354. *
  36355. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  36356. * @readonly
  36357. * @default 'empty'
  36358. */
  36359. this.sourceType = 'empty';
  36360. this._startedAt = 0;
  36361. this._progress = 0;
  36362. this._connected = false;
  36363. /**
  36364. * Can be used to apply a variety of low-order filters to create
  36365. * more complex sound effects e.g. via `BiquadFilterNode`.
  36366. *
  36367. * The property is automatically set by {@link Audio#setFilters}.
  36368. *
  36369. * @type {Array<AudioNode>}
  36370. * @readonly
  36371. */
  36372. this.filters = [];
  36373. }
  36374. /**
  36375. * Returns the output audio node.
  36376. *
  36377. * @return {GainNode} The output node.
  36378. */
  36379. getOutput() {
  36380. return this.gain;
  36381. }
  36382. /**
  36383. * Sets the given audio node as the source of this instance.
  36384. *
  36385. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  36386. *
  36387. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  36388. * @return {Audio} A reference to this instance.
  36389. */
  36390. setNodeSource( audioNode ) {
  36391. this.hasPlaybackControl = false;
  36392. this.sourceType = 'audioNode';
  36393. this.source = audioNode;
  36394. this.connect();
  36395. return this;
  36396. }
  36397. /**
  36398. * Sets the given media element as the source of this instance.
  36399. *
  36400. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  36401. *
  36402. * @param {HTMLMediaElement} mediaElement - The media element.
  36403. * @return {Audio} A reference to this instance.
  36404. */
  36405. setMediaElementSource( mediaElement ) {
  36406. this.hasPlaybackControl = false;
  36407. this.sourceType = 'mediaNode';
  36408. this.source = this.context.createMediaElementSource( mediaElement );
  36409. this.connect();
  36410. return this;
  36411. }
  36412. /**
  36413. * Sets the given media stream as the source of this instance.
  36414. *
  36415. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  36416. *
  36417. * @param {MediaStream} mediaStream - The media stream.
  36418. * @return {Audio} A reference to this instance.
  36419. */
  36420. setMediaStreamSource( mediaStream ) {
  36421. this.hasPlaybackControl = false;
  36422. this.sourceType = 'mediaStreamNode';
  36423. this.source = this.context.createMediaStreamSource( mediaStream );
  36424. this.connect();
  36425. return this;
  36426. }
  36427. /**
  36428. * Sets the given audio buffer as the source of this instance.
  36429. *
  36430. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  36431. *
  36432. * @param {AudioBuffer} audioBuffer - The audio buffer.
  36433. * @return {Audio} A reference to this instance.
  36434. */
  36435. setBuffer( audioBuffer ) {
  36436. this.buffer = audioBuffer;
  36437. this.sourceType = 'buffer';
  36438. if ( this.autoplay ) this.play();
  36439. return this;
  36440. }
  36441. /**
  36442. * Starts the playback of the audio.
  36443. *
  36444. * Can only be used with compatible audio sources that allow playback control.
  36445. *
  36446. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  36447. * @return {Audio|undefined} A reference to this instance.
  36448. */
  36449. play( delay = 0 ) {
  36450. if ( this.isPlaying === true ) {
  36451. console.warn( 'THREE.Audio: Audio is already playing.' );
  36452. return;
  36453. }
  36454. if ( this.hasPlaybackControl === false ) {
  36455. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36456. return;
  36457. }
  36458. this._startedAt = this.context.currentTime + delay;
  36459. const source = this.context.createBufferSource();
  36460. source.buffer = this.buffer;
  36461. source.loop = this.loop;
  36462. source.loopStart = this.loopStart;
  36463. source.loopEnd = this.loopEnd;
  36464. source.onended = this.onEnded.bind( this );
  36465. source.start( this._startedAt, this._progress + this.offset, this.duration );
  36466. this.isPlaying = true;
  36467. this.source = source;
  36468. this.setDetune( this.detune );
  36469. this.setPlaybackRate( this.playbackRate );
  36470. return this.connect();
  36471. }
  36472. /**
  36473. * Pauses the playback of the audio.
  36474. *
  36475. * Can only be used with compatible audio sources that allow playback control.
  36476. *
  36477. * @return {Audio|undefined} A reference to this instance.
  36478. */
  36479. pause() {
  36480. if ( this.hasPlaybackControl === false ) {
  36481. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36482. return;
  36483. }
  36484. if ( this.isPlaying === true ) {
  36485. // update current progress
  36486. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  36487. if ( this.loop === true ) {
  36488. // ensure _progress does not exceed duration with looped audios
  36489. this._progress = this._progress % ( this.duration || this.buffer.duration );
  36490. }
  36491. this.source.stop();
  36492. this.source.onended = null;
  36493. this.isPlaying = false;
  36494. }
  36495. return this;
  36496. }
  36497. /**
  36498. * Stops the playback of the audio.
  36499. *
  36500. * Can only be used with compatible audio sources that allow playback control.
  36501. *
  36502. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  36503. * @return {Audio|undefined} A reference to this instance.
  36504. */
  36505. stop( delay = 0 ) {
  36506. if ( this.hasPlaybackControl === false ) {
  36507. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36508. return;
  36509. }
  36510. this._progress = 0;
  36511. if ( this.source !== null ) {
  36512. this.source.stop( this.context.currentTime + delay );
  36513. this.source.onended = null;
  36514. }
  36515. this.isPlaying = false;
  36516. return this;
  36517. }
  36518. /**
  36519. * Connects to the audio source. This is used internally on
  36520. * initialisation and when setting / removing filters.
  36521. *
  36522. * @return {Audio} A reference to this instance.
  36523. */
  36524. connect() {
  36525. if ( this.filters.length > 0 ) {
  36526. this.source.connect( this.filters[ 0 ] );
  36527. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36528. this.filters[ i - 1 ].connect( this.filters[ i ] );
  36529. }
  36530. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  36531. } else {
  36532. this.source.connect( this.getOutput() );
  36533. }
  36534. this._connected = true;
  36535. return this;
  36536. }
  36537. /**
  36538. * Disconnects to the audio source. This is used internally on
  36539. * initialisation and when setting / removing filters.
  36540. *
  36541. * @return {Audio|undefined} A reference to this instance.
  36542. */
  36543. disconnect() {
  36544. if ( this._connected === false ) {
  36545. return;
  36546. }
  36547. if ( this.filters.length > 0 ) {
  36548. this.source.disconnect( this.filters[ 0 ] );
  36549. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36550. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  36551. }
  36552. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  36553. } else {
  36554. this.source.disconnect( this.getOutput() );
  36555. }
  36556. this._connected = false;
  36557. return this;
  36558. }
  36559. /**
  36560. * Returns the current set filters.
  36561. *
  36562. * @return {Array<AudioNode>} The list of filters.
  36563. */
  36564. getFilters() {
  36565. return this.filters;
  36566. }
  36567. /**
  36568. * Sets an array of filters and connects them with the audio source.
  36569. *
  36570. * @param {Array<AudioNode>} [value] - A list of filters.
  36571. * @return {Audio} A reference to this instance.
  36572. */
  36573. setFilters( value ) {
  36574. if ( ! value ) value = [];
  36575. if ( this._connected === true ) {
  36576. this.disconnect();
  36577. this.filters = value.slice();
  36578. this.connect();
  36579. } else {
  36580. this.filters = value.slice();
  36581. }
  36582. return this;
  36583. }
  36584. /**
  36585. * Defines the detuning of oscillation in cents.
  36586. *
  36587. * @param {number} value - The detuning of oscillation in cents.
  36588. * @return {Audio} A reference to this instance.
  36589. */
  36590. setDetune( value ) {
  36591. this.detune = value;
  36592. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  36593. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  36594. }
  36595. return this;
  36596. }
  36597. /**
  36598. * Returns the detuning of oscillation in cents.
  36599. *
  36600. * @return {number} The detuning of oscillation in cents.
  36601. */
  36602. getDetune() {
  36603. return this.detune;
  36604. }
  36605. /**
  36606. * Returns the first filter in the list of filters.
  36607. *
  36608. * @return {AudioNode|undefined} The first filter in the list of filters.
  36609. */
  36610. getFilter() {
  36611. return this.getFilters()[ 0 ];
  36612. }
  36613. /**
  36614. * Applies a single filter node to the audio.
  36615. *
  36616. * @param {AudioNode} [filter] - The filter to set.
  36617. * @return {Audio} A reference to this instance.
  36618. */
  36619. setFilter( filter ) {
  36620. return this.setFilters( filter ? [ filter ] : [] );
  36621. }
  36622. /**
  36623. * Sets the playback rate.
  36624. *
  36625. * Can only be used with compatible audio sources that allow playback control.
  36626. *
  36627. * @param {number} [value] - The playback rate to set.
  36628. * @return {Audio|undefined} A reference to this instance.
  36629. */
  36630. setPlaybackRate( value ) {
  36631. if ( this.hasPlaybackControl === false ) {
  36632. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36633. return;
  36634. }
  36635. this.playbackRate = value;
  36636. if ( this.isPlaying === true ) {
  36637. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  36638. }
  36639. return this;
  36640. }
  36641. /**
  36642. * Returns the current playback rate.
  36643. * @return {number} The playback rate.
  36644. */
  36645. getPlaybackRate() {
  36646. return this.playbackRate;
  36647. }
  36648. /**
  36649. * Automatically called when playback finished.
  36650. */
  36651. onEnded() {
  36652. this.isPlaying = false;
  36653. this._progress = 0;
  36654. }
  36655. /**
  36656. * Returns the loop flag.
  36657. *
  36658. * Can only be used with compatible audio sources that allow playback control.
  36659. *
  36660. * @return {boolean} Whether the audio should loop or not.
  36661. */
  36662. getLoop() {
  36663. if ( this.hasPlaybackControl === false ) {
  36664. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36665. return false;
  36666. }
  36667. return this.loop;
  36668. }
  36669. /**
  36670. * Sets the loop flag.
  36671. *
  36672. * Can only be used with compatible audio sources that allow playback control.
  36673. *
  36674. * @param {boolean} value - Whether the audio should loop or not.
  36675. * @return {Audio|undefined} A reference to this instance.
  36676. */
  36677. setLoop( value ) {
  36678. if ( this.hasPlaybackControl === false ) {
  36679. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36680. return;
  36681. }
  36682. this.loop = value;
  36683. if ( this.isPlaying === true ) {
  36684. this.source.loop = this.loop;
  36685. }
  36686. return this;
  36687. }
  36688. /**
  36689. * Sets the loop start value which defines where in the audio buffer the replay should
  36690. * start, in seconds.
  36691. *
  36692. * @param {number} value - The loop start value.
  36693. * @return {Audio} A reference to this instance.
  36694. */
  36695. setLoopStart( value ) {
  36696. this.loopStart = value;
  36697. return this;
  36698. }
  36699. /**
  36700. * Sets the loop end value which defines where in the audio buffer the replay should
  36701. * stop, in seconds.
  36702. *
  36703. * @param {number} value - The loop end value.
  36704. * @return {Audio} A reference to this instance.
  36705. */
  36706. setLoopEnd( value ) {
  36707. this.loopEnd = value;
  36708. return this;
  36709. }
  36710. /**
  36711. * Returns the volume.
  36712. *
  36713. * @return {number} The volume.
  36714. */
  36715. getVolume() {
  36716. return this.gain.gain.value;
  36717. }
  36718. /**
  36719. * Sets the volume.
  36720. *
  36721. * @param {number} value - The volume to set.
  36722. * @return {Audio} A reference to this instance.
  36723. */
  36724. setVolume( value ) {
  36725. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36726. return this;
  36727. }
  36728. copy( source, recursive ) {
  36729. super.copy( source, recursive );
  36730. if ( source.sourceType !== 'buffer' ) {
  36731. console.warn( 'THREE.Audio: Audio source type cannot be copied.' );
  36732. return this;
  36733. }
  36734. this.autoplay = source.autoplay;
  36735. this.buffer = source.buffer;
  36736. this.detune = source.detune;
  36737. this.loop = source.loop;
  36738. this.loopStart = source.loopStart;
  36739. this.loopEnd = source.loopEnd;
  36740. this.offset = source.offset;
  36741. this.duration = source.duration;
  36742. this.playbackRate = source.playbackRate;
  36743. this.hasPlaybackControl = source.hasPlaybackControl;
  36744. this.sourceType = source.sourceType;
  36745. this.filters = source.filters.slice();
  36746. return this;
  36747. }
  36748. clone( recursive ) {
  36749. return new this.constructor( this.listener ).copy( this, recursive );
  36750. }
  36751. }
  36752. const _position = /*@__PURE__*/ new Vector3();
  36753. const _quaternion = /*@__PURE__*/ new Quaternion();
  36754. const _scale = /*@__PURE__*/ new Vector3();
  36755. const _orientation = /*@__PURE__*/ new Vector3();
  36756. /**
  36757. * Represents a positional audio object.
  36758. *
  36759. * ```js
  36760. * // create an AudioListener and add it to the camera
  36761. * const listener = new THREE.AudioListener();
  36762. * camera.add( listener );
  36763. *
  36764. * // create the PositionalAudio object (passing in the listener)
  36765. * const sound = new THREE.PositionalAudio( listener );
  36766. *
  36767. * // load a sound and set it as the PositionalAudio object's buffer
  36768. * const audioLoader = new THREE.AudioLoader();
  36769. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  36770. * sound.setBuffer( buffer );
  36771. * sound.setRefDistance( 20 );
  36772. * sound.play();
  36773. * });
  36774. *
  36775. * // create an object for the sound to play from
  36776. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  36777. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  36778. * const mesh = new THREE.Mesh( sphere, material );
  36779. * scene.add( mesh );
  36780. *
  36781. * // finally add the sound to the mesh
  36782. * mesh.add( sound );
  36783. *
  36784. * @augments Audio
  36785. */
  36786. class PositionalAudio extends Audio {
  36787. /**
  36788. * Constructs a positional audio.
  36789. *
  36790. * @param {AudioListener} listener - The global audio listener.
  36791. */
  36792. constructor( listener ) {
  36793. super( listener );
  36794. /**
  36795. * The panner node represents the location, direction, and behavior of an audio
  36796. * source in 3D space.
  36797. *
  36798. * @type {PannerNode}
  36799. * @readonly
  36800. */
  36801. this.panner = this.context.createPanner();
  36802. this.panner.panningModel = 'HRTF';
  36803. this.panner.connect( this.gain );
  36804. }
  36805. connect() {
  36806. super.connect();
  36807. this.panner.connect( this.gain );
  36808. return this;
  36809. }
  36810. disconnect() {
  36811. super.disconnect();
  36812. this.panner.disconnect( this.gain );
  36813. return this;
  36814. }
  36815. getOutput() {
  36816. return this.panner;
  36817. }
  36818. /**
  36819. * Returns the current reference distance.
  36820. *
  36821. * @return {number} The reference distance.
  36822. */
  36823. getRefDistance() {
  36824. return this.panner.refDistance;
  36825. }
  36826. /**
  36827. * Defines the reference distance for reducing volume as the audio source moves
  36828. * further from the listener – i.e. the distance at which the volume reduction
  36829. * starts taking effect.
  36830. *
  36831. * @param {number} value - The reference distance to set.
  36832. * @return {PositionalAudio} A reference to this instance.
  36833. */
  36834. setRefDistance( value ) {
  36835. this.panner.refDistance = value;
  36836. return this;
  36837. }
  36838. /**
  36839. * Returns the current rolloff factor.
  36840. *
  36841. * @return {number} The rolloff factor.
  36842. */
  36843. getRolloffFactor() {
  36844. return this.panner.rolloffFactor;
  36845. }
  36846. /**
  36847. * Defines how quickly the volume is reduced as the source moves away from the listener.
  36848. *
  36849. * @param {number} value - The rolloff factor.
  36850. * @return {PositionalAudio} A reference to this instance.
  36851. */
  36852. setRolloffFactor( value ) {
  36853. this.panner.rolloffFactor = value;
  36854. return this;
  36855. }
  36856. /**
  36857. * Returns the current distance model.
  36858. *
  36859. * @return {('linear'|'inverse'|'exponential')} The distance model.
  36860. */
  36861. getDistanceModel() {
  36862. return this.panner.distanceModel;
  36863. }
  36864. /**
  36865. * Defines which algorithm to use to reduce the volume of the audio source
  36866. * as it moves away from the listener.
  36867. *
  36868. * Read [the spec]{@link https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype}
  36869. * for more details.
  36870. *
  36871. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  36872. * @return {PositionalAudio} A reference to this instance.
  36873. */
  36874. setDistanceModel( value ) {
  36875. this.panner.distanceModel = value;
  36876. return this;
  36877. }
  36878. /**
  36879. * Returns the current max distance.
  36880. *
  36881. * @return {number} The max distance.
  36882. */
  36883. getMaxDistance() {
  36884. return this.panner.maxDistance;
  36885. }
  36886. /**
  36887. * Defines the maximum distance between the audio source and the listener,
  36888. * after which the volume is not reduced any further.
  36889. *
  36890. * This value is used only by the `linear` distance model.
  36891. *
  36892. * @param {number} value - The max distance.
  36893. * @return {PositionalAudio} A reference to this instance.
  36894. */
  36895. setMaxDistance( value ) {
  36896. this.panner.maxDistance = value;
  36897. return this;
  36898. }
  36899. /**
  36900. * Sets the directional cone in which the audio can be listened.
  36901. *
  36902. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  36903. * @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.
  36904. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  36905. * @return {PositionalAudio} A reference to this instance.
  36906. */
  36907. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  36908. this.panner.coneInnerAngle = coneInnerAngle;
  36909. this.panner.coneOuterAngle = coneOuterAngle;
  36910. this.panner.coneOuterGain = coneOuterGain;
  36911. return this;
  36912. }
  36913. updateMatrixWorld( force ) {
  36914. super.updateMatrixWorld( force );
  36915. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  36916. this.matrixWorld.decompose( _position, _quaternion, _scale );
  36917. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  36918. const panner = this.panner;
  36919. if ( panner.positionX ) {
  36920. // code path for Chrome and Firefox (see #14393)
  36921. const endTime = this.context.currentTime + this.listener.timeDelta;
  36922. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  36923. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  36924. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  36925. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  36926. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  36927. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  36928. } else {
  36929. panner.setPosition( _position.x, _position.y, _position.z );
  36930. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  36931. }
  36932. }
  36933. }
  36934. /**
  36935. * This class can be used to analyse audio data.
  36936. *
  36937. * ```js
  36938. * // create an AudioListener and add it to the camera
  36939. * const listener = new THREE.AudioListener();
  36940. * camera.add( listener );
  36941. *
  36942. * // create an Audio source
  36943. * const sound = new THREE.Audio( listener );
  36944. *
  36945. * // load a sound and set it as the Audio object's buffer
  36946. * const audioLoader = new THREE.AudioLoader();
  36947. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36948. * sound.setBuffer( buffer );
  36949. * sound.setLoop(true);
  36950. * sound.setVolume(0.5);
  36951. * sound.play();
  36952. * });
  36953. *
  36954. * // create an AudioAnalyser, passing in the sound and desired fftSize
  36955. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  36956. *
  36957. * // get the average frequency of the sound
  36958. * const data = analyser.getAverageFrequency();
  36959. * ```
  36960. */
  36961. class AudioAnalyser {
  36962. /**
  36963. * Constructs a new audio analyzer.
  36964. *
  36965. * @param {Audio} audio - The audio to analyze.
  36966. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  36967. */
  36968. constructor( audio, fftSize = 2048 ) {
  36969. /**
  36970. * The global audio listener.
  36971. *
  36972. * @type {AnalyserNode}
  36973. */
  36974. this.analyser = audio.context.createAnalyser();
  36975. this.analyser.fftSize = fftSize;
  36976. /**
  36977. * Holds the analyzed data.
  36978. *
  36979. * @type {Uint8Array}
  36980. */
  36981. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  36982. audio.getOutput().connect( this.analyser );
  36983. }
  36984. /**
  36985. * Returns an array with frequency data of the audio.
  36986. *
  36987. * Each item in the array represents the decibel value for a specific frequency.
  36988. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  36989. * For example, for 48000 sample rate, the last item of the array will represent
  36990. * the decibel value for 24000 Hz.
  36991. *
  36992. * @return {Uint8Array} The frequency data.
  36993. */
  36994. getFrequencyData() {
  36995. this.analyser.getByteFrequencyData( this.data );
  36996. return this.data;
  36997. }
  36998. /**
  36999. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  37000. *
  37001. * @return {number} The average frequency.
  37002. */
  37003. getAverageFrequency() {
  37004. let value = 0;
  37005. const data = this.getFrequencyData();
  37006. for ( let i = 0; i < data.length; i ++ ) {
  37007. value += data[ i ];
  37008. }
  37009. return value / data.length;
  37010. }
  37011. }
  37012. /**
  37013. * Buffered scene graph property that allows weighted accumulation; used internally.
  37014. */
  37015. class PropertyMixer {
  37016. /**
  37017. * Constructs a new property mixer.
  37018. *
  37019. * @param {PropertyBinding} binding - The property binding.
  37020. * @param {string} typeName - The keyframe track type name.
  37021. * @param {number} valueSize - The keyframe track value size.
  37022. */
  37023. constructor( binding, typeName, valueSize ) {
  37024. /**
  37025. * The property binding.
  37026. *
  37027. * @type {PropertyBinding}
  37028. */
  37029. this.binding = binding;
  37030. /**
  37031. * The keyframe track value size.
  37032. *
  37033. * @type {number}
  37034. */
  37035. this.valueSize = valueSize;
  37036. let mixFunction,
  37037. mixFunctionAdditive,
  37038. setIdentity;
  37039. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  37040. //
  37041. // interpolators can use .buffer as their .result
  37042. // the data then goes to 'incoming'
  37043. //
  37044. // 'accu0' and 'accu1' are used frame-interleaved for
  37045. // the cumulative result and are compared to detect
  37046. // changes
  37047. //
  37048. // 'orig' stores the original state of the property
  37049. //
  37050. // 'add' is used for additive cumulative results
  37051. //
  37052. // 'work' is optional and is only present for quaternion types. It is used
  37053. // to store intermediate quaternion multiplication results
  37054. switch ( typeName ) {
  37055. case 'quaternion':
  37056. mixFunction = this._slerp;
  37057. mixFunctionAdditive = this._slerpAdditive;
  37058. setIdentity = this._setAdditiveIdentityQuaternion;
  37059. this.buffer = new Float64Array( valueSize * 6 );
  37060. this._workIndex = 5;
  37061. break;
  37062. case 'string':
  37063. case 'bool':
  37064. mixFunction = this._select;
  37065. // Use the regular mix function and for additive on these types,
  37066. // additive is not relevant for non-numeric types
  37067. mixFunctionAdditive = this._select;
  37068. setIdentity = this._setAdditiveIdentityOther;
  37069. this.buffer = new Array( valueSize * 5 );
  37070. break;
  37071. default:
  37072. mixFunction = this._lerp;
  37073. mixFunctionAdditive = this._lerpAdditive;
  37074. setIdentity = this._setAdditiveIdentityNumeric;
  37075. this.buffer = new Float64Array( valueSize * 5 );
  37076. }
  37077. this._mixBufferRegion = mixFunction;
  37078. this._mixBufferRegionAdditive = mixFunctionAdditive;
  37079. this._setIdentity = setIdentity;
  37080. this._origIndex = 3;
  37081. this._addIndex = 4;
  37082. /**
  37083. * TODO
  37084. *
  37085. * @type {number}
  37086. * @default 0
  37087. */
  37088. this.cumulativeWeight = 0;
  37089. /**
  37090. * TODO
  37091. *
  37092. * @type {number}
  37093. * @default 0
  37094. */
  37095. this.cumulativeWeightAdditive = 0;
  37096. /**
  37097. * TODO
  37098. *
  37099. * @type {number}
  37100. * @default 0
  37101. */
  37102. this.useCount = 0;
  37103. /**
  37104. * TODO
  37105. *
  37106. * @type {number}
  37107. * @default 0
  37108. */
  37109. this.referenceCount = 0;
  37110. }
  37111. /**
  37112. * Accumulates data in the `incoming` region into `accu<i>`.
  37113. *
  37114. * @param {number} accuIndex - The accumulation index.
  37115. * @param {number} weight - The weight.
  37116. */
  37117. accumulate( accuIndex, weight ) {
  37118. // note: happily accumulating nothing when weight = 0, the caller knows
  37119. // the weight and shouldn't have made the call in the first place
  37120. const buffer = this.buffer,
  37121. stride = this.valueSize,
  37122. offset = accuIndex * stride + stride;
  37123. let currentWeight = this.cumulativeWeight;
  37124. if ( currentWeight === 0 ) {
  37125. // accuN := incoming * weight
  37126. for ( let i = 0; i !== stride; ++ i ) {
  37127. buffer[ offset + i ] = buffer[ i ];
  37128. }
  37129. currentWeight = weight;
  37130. } else {
  37131. // accuN := accuN + incoming * weight
  37132. currentWeight += weight;
  37133. const mix = weight / currentWeight;
  37134. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  37135. }
  37136. this.cumulativeWeight = currentWeight;
  37137. }
  37138. /**
  37139. * Accumulates data in the `incoming` region into `add`.
  37140. *
  37141. * @param {number} weight - The weight.
  37142. */
  37143. accumulateAdditive( weight ) {
  37144. const buffer = this.buffer,
  37145. stride = this.valueSize,
  37146. offset = stride * this._addIndex;
  37147. if ( this.cumulativeWeightAdditive === 0 ) {
  37148. // add = identity
  37149. this._setIdentity();
  37150. }
  37151. // add := add + incoming * weight
  37152. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  37153. this.cumulativeWeightAdditive += weight;
  37154. }
  37155. /**
  37156. * Applies the state of `accu<i>` to the binding when accus differ.
  37157. *
  37158. * @param {number} accuIndex - The accumulation index.
  37159. */
  37160. apply( accuIndex ) {
  37161. const stride = this.valueSize,
  37162. buffer = this.buffer,
  37163. offset = accuIndex * stride + stride,
  37164. weight = this.cumulativeWeight,
  37165. weightAdditive = this.cumulativeWeightAdditive,
  37166. binding = this.binding;
  37167. this.cumulativeWeight = 0;
  37168. this.cumulativeWeightAdditive = 0;
  37169. if ( weight < 1 ) {
  37170. // accuN := accuN + original * ( 1 - cumulativeWeight )
  37171. const originalValueOffset = stride * this._origIndex;
  37172. this._mixBufferRegion(
  37173. buffer, offset, originalValueOffset, 1 - weight, stride );
  37174. }
  37175. if ( weightAdditive > 0 ) {
  37176. // accuN := accuN + additive accuN
  37177. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  37178. }
  37179. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  37180. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  37181. // value has changed -> update scene graph
  37182. binding.setValue( buffer, offset );
  37183. break;
  37184. }
  37185. }
  37186. }
  37187. /**
  37188. * Remembers the state of the bound property and copy it to both accus.
  37189. */
  37190. saveOriginalState() {
  37191. const binding = this.binding;
  37192. const buffer = this.buffer,
  37193. stride = this.valueSize,
  37194. originalValueOffset = stride * this._origIndex;
  37195. binding.getValue( buffer, originalValueOffset );
  37196. // accu[0..1] := orig -- initially detect changes against the original
  37197. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  37198. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  37199. }
  37200. // Add to identity for additive
  37201. this._setIdentity();
  37202. this.cumulativeWeight = 0;
  37203. this.cumulativeWeightAdditive = 0;
  37204. }
  37205. /**
  37206. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  37207. */
  37208. restoreOriginalState() {
  37209. const originalValueOffset = this.valueSize * 3;
  37210. this.binding.setValue( this.buffer, originalValueOffset );
  37211. }
  37212. // internals
  37213. _setAdditiveIdentityNumeric() {
  37214. const startIndex = this._addIndex * this.valueSize;
  37215. const endIndex = startIndex + this.valueSize;
  37216. for ( let i = startIndex; i < endIndex; i ++ ) {
  37217. this.buffer[ i ] = 0;
  37218. }
  37219. }
  37220. _setAdditiveIdentityQuaternion() {
  37221. this._setAdditiveIdentityNumeric();
  37222. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  37223. }
  37224. _setAdditiveIdentityOther() {
  37225. const startIndex = this._origIndex * this.valueSize;
  37226. const targetIndex = this._addIndex * this.valueSize;
  37227. for ( let i = 0; i < this.valueSize; i ++ ) {
  37228. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  37229. }
  37230. }
  37231. // mix functions
  37232. _select( buffer, dstOffset, srcOffset, t, stride ) {
  37233. if ( t >= 0.5 ) {
  37234. for ( let i = 0; i !== stride; ++ i ) {
  37235. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  37236. }
  37237. }
  37238. }
  37239. _slerp( buffer, dstOffset, srcOffset, t ) {
  37240. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  37241. }
  37242. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37243. const workOffset = this._workIndex * stride;
  37244. // Store result in intermediate buffer offset
  37245. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  37246. // Slerp to the intermediate result
  37247. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  37248. }
  37249. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  37250. const s = 1 - t;
  37251. for ( let i = 0; i !== stride; ++ i ) {
  37252. const j = dstOffset + i;
  37253. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  37254. }
  37255. }
  37256. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37257. for ( let i = 0; i !== stride; ++ i ) {
  37258. const j = dstOffset + i;
  37259. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  37260. }
  37261. }
  37262. }
  37263. // Characters [].:/ are reserved for track binding syntax.
  37264. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  37265. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  37266. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  37267. // only latin characters, and the unicode \p{L} is not yet supported. So
  37268. // instead, we exclude reserved characters and match everything else.
  37269. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  37270. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  37271. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  37272. // be matched to parse the rest of the track name.
  37273. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  37274. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  37275. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  37276. // Object on target node, and accessor. May not contain reserved
  37277. // characters. Accessor may contain any character except closing bracket.
  37278. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  37279. // Property and accessor. May not contain reserved characters. Accessor may
  37280. // contain any non-bracket characters.
  37281. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  37282. const _trackRe = new RegExp( ''
  37283. + '^'
  37284. + _directoryRe
  37285. + _nodeRe
  37286. + _objectRe
  37287. + _propertyRe
  37288. + '$'
  37289. );
  37290. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  37291. class Composite {
  37292. constructor( targetGroup, path, optionalParsedPath ) {
  37293. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  37294. this._targetGroup = targetGroup;
  37295. this._bindings = targetGroup.subscribe_( path, parsedPath );
  37296. }
  37297. getValue( array, offset ) {
  37298. this.bind(); // bind all binding
  37299. const firstValidIndex = this._targetGroup.nCachedObjects_,
  37300. binding = this._bindings[ firstValidIndex ];
  37301. // and only call .getValue on the first
  37302. if ( binding !== undefined ) binding.getValue( array, offset );
  37303. }
  37304. setValue( array, offset ) {
  37305. const bindings = this._bindings;
  37306. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37307. bindings[ i ].setValue( array, offset );
  37308. }
  37309. }
  37310. bind() {
  37311. const bindings = this._bindings;
  37312. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37313. bindings[ i ].bind();
  37314. }
  37315. }
  37316. unbind() {
  37317. const bindings = this._bindings;
  37318. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37319. bindings[ i ].unbind();
  37320. }
  37321. }
  37322. }
  37323. // Note: This class uses a State pattern on a per-method basis:
  37324. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  37325. // prototype version of these methods with one that represents
  37326. // the bound state. When the property is not found, the methods
  37327. // become no-ops.
  37328. /**
  37329. * This holds a reference to a real property in the scene graph; used internally.
  37330. */
  37331. class PropertyBinding {
  37332. /**
  37333. * Constructs a new property binding.
  37334. *
  37335. * @param {Object} rootNode - The root node.
  37336. * @param {string} path - The path.
  37337. * @param {?Object} [parsedPath] - The parsed path.
  37338. */
  37339. constructor( rootNode, path, parsedPath ) {
  37340. /**
  37341. * The object path to the animated property.
  37342. *
  37343. * @type {string}
  37344. */
  37345. this.path = path;
  37346. /**
  37347. * An object holding information about the path.
  37348. *
  37349. * @type {Object}
  37350. */
  37351. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  37352. /**
  37353. * The object owns the animated property.
  37354. *
  37355. * @type {?Object}
  37356. */
  37357. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  37358. /**
  37359. * The root node.
  37360. *
  37361. * @type {Object3D|Skeleton}
  37362. */
  37363. this.rootNode = rootNode;
  37364. // initial state of these methods that calls 'bind'
  37365. this.getValue = this._getValue_unbound;
  37366. this.setValue = this._setValue_unbound;
  37367. }
  37368. /**
  37369. * Factory method for creating a property binding from the given parameters.
  37370. *
  37371. * @static
  37372. * @param {Object} root - The root node.
  37373. * @param {string} path - The path.
  37374. * @param {?Object} [parsedPath] - The parsed path.
  37375. * @return {PropertyBinding|Composite} The created property binding or composite.
  37376. */
  37377. static create( root, path, parsedPath ) {
  37378. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  37379. return new PropertyBinding( root, path, parsedPath );
  37380. } else {
  37381. return new PropertyBinding.Composite( root, path, parsedPath );
  37382. }
  37383. }
  37384. /**
  37385. * Replaces spaces with underscores and removes unsupported characters from
  37386. * node names, to ensure compatibility with parseTrackName().
  37387. *
  37388. * @param {string} name - Node name to be sanitized.
  37389. * @return {string} The sanitized node name.
  37390. */
  37391. static sanitizeNodeName( name ) {
  37392. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  37393. }
  37394. /**
  37395. * Parses the given track name (an object path to an animated property) and
  37396. * returns an object with information about the path. Matches strings in the following forms:
  37397. *
  37398. * - nodeName.property
  37399. * - nodeName.property[accessor]
  37400. * - nodeName.material.property[accessor]
  37401. * - uuid.property[accessor]
  37402. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  37403. * - parentName/nodeName.property
  37404. * - parentName/parentName/nodeName.property[index]
  37405. * - .bone[Armature.DEF_cog].position
  37406. * - scene:helium_balloon_model:helium_balloon_model.position
  37407. *
  37408. * @static
  37409. * @param {string} trackName - The track name to parse.
  37410. * @return {Object} The parsed track name as an object.
  37411. */
  37412. static parseTrackName( trackName ) {
  37413. const matches = _trackRe.exec( trackName );
  37414. if ( matches === null ) {
  37415. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  37416. }
  37417. const results = {
  37418. // directoryName: matches[ 1 ], // (tschw) currently unused
  37419. nodeName: matches[ 2 ],
  37420. objectName: matches[ 3 ],
  37421. objectIndex: matches[ 4 ],
  37422. propertyName: matches[ 5 ], // required
  37423. propertyIndex: matches[ 6 ]
  37424. };
  37425. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  37426. if ( lastDot !== undefined && lastDot !== -1 ) {
  37427. const objectName = results.nodeName.substring( lastDot + 1 );
  37428. // Object names must be checked against an allowlist. Otherwise, there
  37429. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  37430. // 'bar' could be the objectName, or part of a nodeName (which can
  37431. // include '.' characters).
  37432. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  37433. results.nodeName = results.nodeName.substring( 0, lastDot );
  37434. results.objectName = objectName;
  37435. }
  37436. }
  37437. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  37438. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  37439. }
  37440. return results;
  37441. }
  37442. /**
  37443. * Searches for a node in the hierarchy of the given root object by the given
  37444. * node name.
  37445. *
  37446. * @static
  37447. * @param {Object} root - The root object.
  37448. * @param {string|number} nodeName - The name of the node.
  37449. * @return {?Object} The found node. Returns `null` if no object was found.
  37450. */
  37451. static findNode( root, nodeName ) {
  37452. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  37453. return root;
  37454. }
  37455. // search into skeleton bones.
  37456. if ( root.skeleton ) {
  37457. const bone = root.skeleton.getBoneByName( nodeName );
  37458. if ( bone !== undefined ) {
  37459. return bone;
  37460. }
  37461. }
  37462. // search into node subtree.
  37463. if ( root.children ) {
  37464. const searchNodeSubtree = function ( children ) {
  37465. for ( let i = 0; i < children.length; i ++ ) {
  37466. const childNode = children[ i ];
  37467. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  37468. return childNode;
  37469. }
  37470. const result = searchNodeSubtree( childNode.children );
  37471. if ( result ) return result;
  37472. }
  37473. return null;
  37474. };
  37475. const subTreeNode = searchNodeSubtree( root.children );
  37476. if ( subTreeNode ) {
  37477. return subTreeNode;
  37478. }
  37479. }
  37480. return null;
  37481. }
  37482. // these are used to "bind" a nonexistent property
  37483. _getValue_unavailable() {}
  37484. _setValue_unavailable() {}
  37485. // Getters
  37486. _getValue_direct( buffer, offset ) {
  37487. buffer[ offset ] = this.targetObject[ this.propertyName ];
  37488. }
  37489. _getValue_array( buffer, offset ) {
  37490. const source = this.resolvedProperty;
  37491. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  37492. buffer[ offset ++ ] = source[ i ];
  37493. }
  37494. }
  37495. _getValue_arrayElement( buffer, offset ) {
  37496. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  37497. }
  37498. _getValue_toArray( buffer, offset ) {
  37499. this.resolvedProperty.toArray( buffer, offset );
  37500. }
  37501. // Direct
  37502. _setValue_direct( buffer, offset ) {
  37503. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37504. }
  37505. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  37506. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37507. this.targetObject.needsUpdate = true;
  37508. }
  37509. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37510. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37511. this.targetObject.matrixWorldNeedsUpdate = true;
  37512. }
  37513. // EntireArray
  37514. _setValue_array( buffer, offset ) {
  37515. const dest = this.resolvedProperty;
  37516. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37517. dest[ i ] = buffer[ offset ++ ];
  37518. }
  37519. }
  37520. _setValue_array_setNeedsUpdate( buffer, offset ) {
  37521. const dest = this.resolvedProperty;
  37522. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37523. dest[ i ] = buffer[ offset ++ ];
  37524. }
  37525. this.targetObject.needsUpdate = true;
  37526. }
  37527. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37528. const dest = this.resolvedProperty;
  37529. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37530. dest[ i ] = buffer[ offset ++ ];
  37531. }
  37532. this.targetObject.matrixWorldNeedsUpdate = true;
  37533. }
  37534. // ArrayElement
  37535. _setValue_arrayElement( buffer, offset ) {
  37536. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37537. }
  37538. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  37539. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37540. this.targetObject.needsUpdate = true;
  37541. }
  37542. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37543. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37544. this.targetObject.matrixWorldNeedsUpdate = true;
  37545. }
  37546. // HasToFromArray
  37547. _setValue_fromArray( buffer, offset ) {
  37548. this.resolvedProperty.fromArray( buffer, offset );
  37549. }
  37550. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  37551. this.resolvedProperty.fromArray( buffer, offset );
  37552. this.targetObject.needsUpdate = true;
  37553. }
  37554. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37555. this.resolvedProperty.fromArray( buffer, offset );
  37556. this.targetObject.matrixWorldNeedsUpdate = true;
  37557. }
  37558. _getValue_unbound( targetArray, offset ) {
  37559. this.bind();
  37560. this.getValue( targetArray, offset );
  37561. }
  37562. _setValue_unbound( sourceArray, offset ) {
  37563. this.bind();
  37564. this.setValue( sourceArray, offset );
  37565. }
  37566. /**
  37567. * Creates a getter / setter pair for the property tracked by this binding.
  37568. */
  37569. bind() {
  37570. let targetObject = this.node;
  37571. const parsedPath = this.parsedPath;
  37572. const objectName = parsedPath.objectName;
  37573. const propertyName = parsedPath.propertyName;
  37574. let propertyIndex = parsedPath.propertyIndex;
  37575. if ( ! targetObject ) {
  37576. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  37577. this.node = targetObject;
  37578. }
  37579. // set fail state so we can just 'return' on error
  37580. this.getValue = this._getValue_unavailable;
  37581. this.setValue = this._setValue_unavailable;
  37582. // ensure there is a value node
  37583. if ( ! targetObject ) {
  37584. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  37585. return;
  37586. }
  37587. if ( objectName ) {
  37588. let objectIndex = parsedPath.objectIndex;
  37589. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  37590. switch ( objectName ) {
  37591. case 'materials':
  37592. if ( ! targetObject.material ) {
  37593. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  37594. return;
  37595. }
  37596. if ( ! targetObject.material.materials ) {
  37597. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  37598. return;
  37599. }
  37600. targetObject = targetObject.material.materials;
  37601. break;
  37602. case 'bones':
  37603. if ( ! targetObject.skeleton ) {
  37604. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  37605. return;
  37606. }
  37607. // potential future optimization: skip this if propertyIndex is already an integer
  37608. // and convert the integer string to a true integer.
  37609. targetObject = targetObject.skeleton.bones;
  37610. // support resolving morphTarget names into indices.
  37611. for ( let i = 0; i < targetObject.length; i ++ ) {
  37612. if ( targetObject[ i ].name === objectIndex ) {
  37613. objectIndex = i;
  37614. break;
  37615. }
  37616. }
  37617. break;
  37618. case 'map':
  37619. if ( 'map' in targetObject ) {
  37620. targetObject = targetObject.map;
  37621. break;
  37622. }
  37623. if ( ! targetObject.material ) {
  37624. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  37625. return;
  37626. }
  37627. if ( ! targetObject.material.map ) {
  37628. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  37629. return;
  37630. }
  37631. targetObject = targetObject.material.map;
  37632. break;
  37633. default:
  37634. if ( targetObject[ objectName ] === undefined ) {
  37635. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  37636. return;
  37637. }
  37638. targetObject = targetObject[ objectName ];
  37639. }
  37640. if ( objectIndex !== undefined ) {
  37641. if ( targetObject[ objectIndex ] === undefined ) {
  37642. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  37643. return;
  37644. }
  37645. targetObject = targetObject[ objectIndex ];
  37646. }
  37647. }
  37648. // resolve property
  37649. const nodeProperty = targetObject[ propertyName ];
  37650. if ( nodeProperty === undefined ) {
  37651. const nodeName = parsedPath.nodeName;
  37652. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  37653. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  37654. return;
  37655. }
  37656. // determine versioning scheme
  37657. let versioning = this.Versioning.None;
  37658. this.targetObject = targetObject;
  37659. if ( targetObject.isMaterial === true ) {
  37660. versioning = this.Versioning.NeedsUpdate;
  37661. } else if ( targetObject.isObject3D === true ) {
  37662. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  37663. }
  37664. // determine how the property gets bound
  37665. let bindingType = this.BindingType.Direct;
  37666. if ( propertyIndex !== undefined ) {
  37667. // access a sub element of the property array (only primitives are supported right now)
  37668. if ( propertyName === 'morphTargetInfluences' ) {
  37669. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  37670. // support resolving morphTarget names into indices.
  37671. if ( ! targetObject.geometry ) {
  37672. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  37673. return;
  37674. }
  37675. if ( ! targetObject.geometry.morphAttributes ) {
  37676. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  37677. return;
  37678. }
  37679. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  37680. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  37681. }
  37682. }
  37683. bindingType = this.BindingType.ArrayElement;
  37684. this.resolvedProperty = nodeProperty;
  37685. this.propertyIndex = propertyIndex;
  37686. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  37687. // must use copy for Object3D.Euler/Quaternion
  37688. bindingType = this.BindingType.HasFromToArray;
  37689. this.resolvedProperty = nodeProperty;
  37690. } else if ( Array.isArray( nodeProperty ) ) {
  37691. bindingType = this.BindingType.EntireArray;
  37692. this.resolvedProperty = nodeProperty;
  37693. } else {
  37694. this.propertyName = propertyName;
  37695. }
  37696. // select getter / setter
  37697. this.getValue = this.GetterByBindingType[ bindingType ];
  37698. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  37699. }
  37700. /**
  37701. * Unbinds the property.
  37702. */
  37703. unbind() {
  37704. this.node = null;
  37705. // back to the prototype version of getValue / setValue
  37706. // note: avoiding to mutate the shape of 'this' via 'delete'
  37707. this.getValue = this._getValue_unbound;
  37708. this.setValue = this._setValue_unbound;
  37709. }
  37710. }
  37711. PropertyBinding.Composite = Composite;
  37712. PropertyBinding.prototype.BindingType = {
  37713. Direct: 0,
  37714. EntireArray: 1,
  37715. ArrayElement: 2,
  37716. HasFromToArray: 3
  37717. };
  37718. PropertyBinding.prototype.Versioning = {
  37719. None: 0,
  37720. NeedsUpdate: 1,
  37721. MatrixWorldNeedsUpdate: 2
  37722. };
  37723. PropertyBinding.prototype.GetterByBindingType = [
  37724. PropertyBinding.prototype._getValue_direct,
  37725. PropertyBinding.prototype._getValue_array,
  37726. PropertyBinding.prototype._getValue_arrayElement,
  37727. PropertyBinding.prototype._getValue_toArray,
  37728. ];
  37729. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  37730. [
  37731. // Direct
  37732. PropertyBinding.prototype._setValue_direct,
  37733. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  37734. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  37735. ], [
  37736. // EntireArray
  37737. PropertyBinding.prototype._setValue_array,
  37738. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  37739. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  37740. ], [
  37741. // ArrayElement
  37742. PropertyBinding.prototype._setValue_arrayElement,
  37743. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  37744. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  37745. ], [
  37746. // HasToFromArray
  37747. PropertyBinding.prototype._setValue_fromArray,
  37748. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  37749. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  37750. ]
  37751. ];
  37752. /**
  37753. * A group of objects that receives a shared animation state.
  37754. *
  37755. * Usage:
  37756. *
  37757. * - Add objects you would otherwise pass as 'root' to the
  37758. * constructor or the .clipAction method of AnimationMixer.
  37759. * - Instead pass this object as 'root'.
  37760. * - You can also add and remove objects later when the mixer is running.
  37761. *
  37762. * Note:
  37763. *
  37764. * - Objects of this class appear as one object to the mixer,
  37765. * so cache control of the individual objects must be done on the group.
  37766. *
  37767. * Limitation:
  37768. *
  37769. * - The animated properties must be compatible among the all objects in the group.
  37770. * - A single property can either be controlled through a target group or directly, but not both.
  37771. */
  37772. class AnimationObjectGroup {
  37773. /**
  37774. * Constructs a new animation group.
  37775. *
  37776. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  37777. */
  37778. constructor() {
  37779. /**
  37780. * This flag can be used for type testing.
  37781. *
  37782. * @type {boolean}
  37783. * @readonly
  37784. * @default true
  37785. */
  37786. this.isAnimationObjectGroup = true;
  37787. /**
  37788. * The UUID of the 3D object.
  37789. *
  37790. * @type {string}
  37791. * @readonly
  37792. */
  37793. this.uuid = generateUUID();
  37794. // cached objects followed by the active ones
  37795. this._objects = Array.prototype.slice.call( arguments );
  37796. this.nCachedObjects_ = 0; // threshold
  37797. // note: read by PropertyBinding.Composite
  37798. const indices = {};
  37799. this._indicesByUUID = indices; // for bookkeeping
  37800. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37801. indices[ arguments[ i ].uuid ] = i;
  37802. }
  37803. this._paths = []; // inside: string
  37804. this._parsedPaths = []; // inside: { we don't care, here }
  37805. this._bindings = []; // inside: Array< PropertyBinding >
  37806. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  37807. const scope = this;
  37808. this.stats = {
  37809. objects: {
  37810. get total() {
  37811. return scope._objects.length;
  37812. },
  37813. get inUse() {
  37814. return this.total - scope.nCachedObjects_;
  37815. }
  37816. },
  37817. get bindingsPerObject() {
  37818. return scope._bindings.length;
  37819. }
  37820. };
  37821. }
  37822. /**
  37823. * Adds an arbitrary number of objects to this animation group.
  37824. *
  37825. * @param {...Object3D} arguments - The 3D objects to add.
  37826. */
  37827. add() {
  37828. const objects = this._objects,
  37829. indicesByUUID = this._indicesByUUID,
  37830. paths = this._paths,
  37831. parsedPaths = this._parsedPaths,
  37832. bindings = this._bindings,
  37833. nBindings = bindings.length;
  37834. let knownObject = undefined,
  37835. nObjects = objects.length,
  37836. nCachedObjects = this.nCachedObjects_;
  37837. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37838. const object = arguments[ i ],
  37839. uuid = object.uuid;
  37840. let index = indicesByUUID[ uuid ];
  37841. if ( index === undefined ) {
  37842. // unknown object -> add it to the ACTIVE region
  37843. index = nObjects ++;
  37844. indicesByUUID[ uuid ] = index;
  37845. objects.push( object );
  37846. // accounting is done, now do the same for all bindings
  37847. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37848. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  37849. }
  37850. } else if ( index < nCachedObjects ) {
  37851. knownObject = objects[ index ];
  37852. // move existing object to the ACTIVE region
  37853. const firstActiveIndex = -- nCachedObjects,
  37854. lastCachedObject = objects[ firstActiveIndex ];
  37855. indicesByUUID[ lastCachedObject.uuid ] = index;
  37856. objects[ index ] = lastCachedObject;
  37857. indicesByUUID[ uuid ] = firstActiveIndex;
  37858. objects[ firstActiveIndex ] = object;
  37859. // accounting is done, now do the same for all bindings
  37860. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37861. const bindingsForPath = bindings[ j ],
  37862. lastCached = bindingsForPath[ firstActiveIndex ];
  37863. let binding = bindingsForPath[ index ];
  37864. bindingsForPath[ index ] = lastCached;
  37865. if ( binding === undefined ) {
  37866. // since we do not bother to create new bindings
  37867. // for objects that are cached, the binding may
  37868. // or may not exist
  37869. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  37870. }
  37871. bindingsForPath[ firstActiveIndex ] = binding;
  37872. }
  37873. } else if ( objects[ index ] !== knownObject ) {
  37874. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  37875. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  37876. } // else the object is already where we want it to be
  37877. } // for arguments
  37878. this.nCachedObjects_ = nCachedObjects;
  37879. }
  37880. /**
  37881. * Removes an arbitrary number of objects to this animation group
  37882. *
  37883. * @param {...Object3D} arguments - The 3D objects to remove.
  37884. */
  37885. remove() {
  37886. const objects = this._objects,
  37887. indicesByUUID = this._indicesByUUID,
  37888. bindings = this._bindings,
  37889. nBindings = bindings.length;
  37890. let nCachedObjects = this.nCachedObjects_;
  37891. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37892. const object = arguments[ i ],
  37893. uuid = object.uuid,
  37894. index = indicesByUUID[ uuid ];
  37895. if ( index !== undefined && index >= nCachedObjects ) {
  37896. // move existing object into the CACHED region
  37897. const lastCachedIndex = nCachedObjects ++,
  37898. firstActiveObject = objects[ lastCachedIndex ];
  37899. indicesByUUID[ firstActiveObject.uuid ] = index;
  37900. objects[ index ] = firstActiveObject;
  37901. indicesByUUID[ uuid ] = lastCachedIndex;
  37902. objects[ lastCachedIndex ] = object;
  37903. // accounting is done, now do the same for all bindings
  37904. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37905. const bindingsForPath = bindings[ j ],
  37906. firstActive = bindingsForPath[ lastCachedIndex ],
  37907. binding = bindingsForPath[ index ];
  37908. bindingsForPath[ index ] = firstActive;
  37909. bindingsForPath[ lastCachedIndex ] = binding;
  37910. }
  37911. }
  37912. } // for arguments
  37913. this.nCachedObjects_ = nCachedObjects;
  37914. }
  37915. /**
  37916. * Deallocates all memory resources for the passed 3D objects of this animation group.
  37917. *
  37918. * @param {...Object3D} arguments - The 3D objects to uncache.
  37919. */
  37920. uncache() {
  37921. const objects = this._objects,
  37922. indicesByUUID = this._indicesByUUID,
  37923. bindings = this._bindings,
  37924. nBindings = bindings.length;
  37925. let nCachedObjects = this.nCachedObjects_,
  37926. nObjects = objects.length;
  37927. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37928. const object = arguments[ i ],
  37929. uuid = object.uuid,
  37930. index = indicesByUUID[ uuid ];
  37931. if ( index !== undefined ) {
  37932. delete indicesByUUID[ uuid ];
  37933. if ( index < nCachedObjects ) {
  37934. // object is cached, shrink the CACHED region
  37935. const firstActiveIndex = -- nCachedObjects,
  37936. lastCachedObject = objects[ firstActiveIndex ],
  37937. lastIndex = -- nObjects,
  37938. lastObject = objects[ lastIndex ];
  37939. // last cached object takes this object's place
  37940. indicesByUUID[ lastCachedObject.uuid ] = index;
  37941. objects[ index ] = lastCachedObject;
  37942. // last object goes to the activated slot and pop
  37943. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  37944. objects[ firstActiveIndex ] = lastObject;
  37945. objects.pop();
  37946. // accounting is done, now do the same for all bindings
  37947. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37948. const bindingsForPath = bindings[ j ],
  37949. lastCached = bindingsForPath[ firstActiveIndex ],
  37950. last = bindingsForPath[ lastIndex ];
  37951. bindingsForPath[ index ] = lastCached;
  37952. bindingsForPath[ firstActiveIndex ] = last;
  37953. bindingsForPath.pop();
  37954. }
  37955. } else {
  37956. // object is active, just swap with the last and pop
  37957. const lastIndex = -- nObjects,
  37958. lastObject = objects[ lastIndex ];
  37959. if ( lastIndex > 0 ) {
  37960. indicesByUUID[ lastObject.uuid ] = index;
  37961. }
  37962. objects[ index ] = lastObject;
  37963. objects.pop();
  37964. // accounting is done, now do the same for all bindings
  37965. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37966. const bindingsForPath = bindings[ j ];
  37967. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  37968. bindingsForPath.pop();
  37969. }
  37970. } // cached or active
  37971. } // if object is known
  37972. } // for arguments
  37973. this.nCachedObjects_ = nCachedObjects;
  37974. }
  37975. // Internal interface used by befriended PropertyBinding.Composite:
  37976. subscribe_( path, parsedPath ) {
  37977. // returns an array of bindings for the given path that is changed
  37978. // according to the contained objects in the group
  37979. const indicesByPath = this._bindingsIndicesByPath;
  37980. let index = indicesByPath[ path ];
  37981. const bindings = this._bindings;
  37982. if ( index !== undefined ) return bindings[ index ];
  37983. const paths = this._paths,
  37984. parsedPaths = this._parsedPaths,
  37985. objects = this._objects,
  37986. nObjects = objects.length,
  37987. nCachedObjects = this.nCachedObjects_,
  37988. bindingsForPath = new Array( nObjects );
  37989. index = bindings.length;
  37990. indicesByPath[ path ] = index;
  37991. paths.push( path );
  37992. parsedPaths.push( parsedPath );
  37993. bindings.push( bindingsForPath );
  37994. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  37995. const object = objects[ i ];
  37996. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  37997. }
  37998. return bindingsForPath;
  37999. }
  38000. unsubscribe_( path ) {
  38001. // tells the group to forget about a property path and no longer
  38002. // update the array previously obtained with 'subscribe_'
  38003. const indicesByPath = this._bindingsIndicesByPath,
  38004. index = indicesByPath[ path ];
  38005. if ( index !== undefined ) {
  38006. const paths = this._paths,
  38007. parsedPaths = this._parsedPaths,
  38008. bindings = this._bindings,
  38009. lastBindingsIndex = bindings.length - 1,
  38010. lastBindings = bindings[ lastBindingsIndex ],
  38011. lastBindingsPath = path[ lastBindingsIndex ];
  38012. indicesByPath[ lastBindingsPath ] = index;
  38013. bindings[ index ] = lastBindings;
  38014. bindings.pop();
  38015. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  38016. parsedPaths.pop();
  38017. paths[ index ] = paths[ lastBindingsIndex ];
  38018. paths.pop();
  38019. }
  38020. }
  38021. }
  38022. /**
  38023. * An instance of `AnimationAction` schedules the playback of an animation which is
  38024. * stored in {@link AnimationClip}.
  38025. */
  38026. class AnimationAction {
  38027. /**
  38028. * Constructs a new animation action.
  38029. *
  38030. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  38031. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  38032. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  38033. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38034. */
  38035. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  38036. this._mixer = mixer;
  38037. this._clip = clip;
  38038. this._localRoot = localRoot;
  38039. /**
  38040. * Defines how the animation is blended/combined when two or more animations
  38041. * are simultaneously played.
  38042. *
  38043. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  38044. */
  38045. this.blendMode = blendMode;
  38046. const tracks = clip.tracks,
  38047. nTracks = tracks.length,
  38048. interpolants = new Array( nTracks );
  38049. const interpolantSettings = {
  38050. endingStart: ZeroCurvatureEnding,
  38051. endingEnd: ZeroCurvatureEnding
  38052. };
  38053. for ( let i = 0; i !== nTracks; ++ i ) {
  38054. const interpolant = tracks[ i ].createInterpolant( null );
  38055. interpolants[ i ] = interpolant;
  38056. interpolant.settings = interpolantSettings;
  38057. }
  38058. this._interpolantSettings = interpolantSettings;
  38059. this._interpolants = interpolants; // bound by the mixer
  38060. // inside: PropertyMixer (managed by the mixer)
  38061. this._propertyBindings = new Array( nTracks );
  38062. this._cacheIndex = null; // for the memory manager
  38063. this._byClipCacheIndex = null; // for the memory manager
  38064. this._timeScaleInterpolant = null;
  38065. this._weightInterpolant = null;
  38066. /**
  38067. * The loop mode, set via {@link AnimationAction#setLoop}.
  38068. *
  38069. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  38070. * @default LoopRepeat
  38071. */
  38072. this.loop = LoopRepeat;
  38073. this._loopCount = -1;
  38074. // global mixer time when the action is to be started
  38075. // it's set back to 'null' upon start of the action
  38076. this._startTime = null;
  38077. /**
  38078. * The local time of this action (in seconds, starting with `0`).
  38079. *
  38080. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  38081. * loop state).
  38082. *
  38083. * @type {number}
  38084. * @default Infinity
  38085. */
  38086. this.time = 0;
  38087. /**
  38088. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  38089. * animation to pause. Negative values cause the animation to play backwards.
  38090. *
  38091. * @type {number}
  38092. * @default 1
  38093. */
  38094. this.timeScale = 1;
  38095. this._effectiveTimeScale = 1;
  38096. /**
  38097. * The degree of influence of this action (in the interval `[0, 1]`). Values
  38098. * between `0` (no impact) and `1` (full impact) can be used to blend between
  38099. * several actions.
  38100. *
  38101. * @type {number}
  38102. * @default 1
  38103. */
  38104. this.weight = 1;
  38105. this._effectiveWeight = 1;
  38106. /**
  38107. * The number of repetitions of the performed clip over the course of this action.
  38108. * Can be set via {@link AnimationAction#setLoop}.
  38109. *
  38110. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  38111. * `THREE:LoopOnce`.
  38112. *
  38113. * @type {number}
  38114. * @default Infinity
  38115. */
  38116. this.repetitions = Infinity;
  38117. /**
  38118. * If set to `true`, the playback of the action is paused.
  38119. *
  38120. * @type {boolean}
  38121. * @default false
  38122. */
  38123. this.paused = false;
  38124. /**
  38125. * If set to `false`, the action is disabled so it has no impact.
  38126. *
  38127. * When the action is re-enabled, the animation continues from its current
  38128. * time (setting `enabled` to `false` doesn't reset the action).
  38129. *
  38130. * @type {boolean}
  38131. * @default true
  38132. */
  38133. this.enabled = true;
  38134. /**
  38135. * If set to true the animation will automatically be paused on its last frame.
  38136. *
  38137. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  38138. * to `false` when the last loop of the action has finished, so that this action has
  38139. * no further impact.
  38140. *
  38141. * Note: This member has no impact if the action is interrupted (it
  38142. * has only an effect if its last loop has really finished).
  38143. *
  38144. * @type {boolean}
  38145. * @default false
  38146. */
  38147. this.clampWhenFinished = false;
  38148. /**
  38149. * Enables smooth interpolation without separate clips for start, loop and end.
  38150. *
  38151. * @type {boolean}
  38152. * @default true
  38153. */
  38154. this.zeroSlopeAtStart = true;
  38155. /**
  38156. * Enables smooth interpolation without separate clips for start, loop and end.
  38157. *
  38158. * @type {boolean}
  38159. * @default true
  38160. */
  38161. this.zeroSlopeAtEnd = true;
  38162. }
  38163. /**
  38164. * Starts the playback of the animation.
  38165. *
  38166. * @return {AnimationAction} A reference to this animation action.
  38167. */
  38168. play() {
  38169. this._mixer._activateAction( this );
  38170. return this;
  38171. }
  38172. /**
  38173. * Stops the playback of the animation.
  38174. *
  38175. * @return {AnimationAction} A reference to this animation action.
  38176. */
  38177. stop() {
  38178. this._mixer._deactivateAction( this );
  38179. return this.reset();
  38180. }
  38181. /**
  38182. * Resets the playback of the animation.
  38183. *
  38184. * @return {AnimationAction} A reference to this animation action.
  38185. */
  38186. reset() {
  38187. this.paused = false;
  38188. this.enabled = true;
  38189. this.time = 0; // restart clip
  38190. this._loopCount = -1;// forget previous loops
  38191. this._startTime = null;// forget scheduling
  38192. return this.stopFading().stopWarping();
  38193. }
  38194. /**
  38195. * Returns `true` if the animation is running.
  38196. *
  38197. * @return {boolean} Whether the animation is running or not.
  38198. */
  38199. isRunning() {
  38200. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  38201. this._startTime === null && this._mixer._isActiveAction( this );
  38202. }
  38203. /**
  38204. * Returns `true` when {@link AnimationAction#play} has been called.
  38205. *
  38206. * @return {boolean} Whether the animation is scheduled or not.
  38207. */
  38208. isScheduled() {
  38209. return this._mixer._isActiveAction( this );
  38210. }
  38211. /**
  38212. * Defines the time when the animation should start.
  38213. *
  38214. * @param {number} time - The start time in seconds.
  38215. * @return {AnimationAction} A reference to this animation action.
  38216. */
  38217. startAt( time ) {
  38218. this._startTime = time;
  38219. return this;
  38220. }
  38221. /**
  38222. * Configures the loop settings for this action.
  38223. *
  38224. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  38225. * @param {number} repetitions - The number of repetitions.
  38226. * @return {AnimationAction} A reference to this animation action.
  38227. */
  38228. setLoop( mode, repetitions ) {
  38229. this.loop = mode;
  38230. this.repetitions = repetitions;
  38231. return this;
  38232. }
  38233. /**
  38234. * Sets the effective weight of this action.
  38235. *
  38236. * An action has no effect and thus an effective weight of zero when the
  38237. * action is disabled.
  38238. *
  38239. * @param {number} weight - The weight to set.
  38240. * @return {AnimationAction} A reference to this animation action.
  38241. */
  38242. setEffectiveWeight( weight ) {
  38243. this.weight = weight;
  38244. // note: same logic as when updated at runtime
  38245. this._effectiveWeight = this.enabled ? weight : 0;
  38246. return this.stopFading();
  38247. }
  38248. /**
  38249. * Returns the effective weight of this action.
  38250. *
  38251. * @return {number} The effective weight.
  38252. */
  38253. getEffectiveWeight() {
  38254. return this._effectiveWeight;
  38255. }
  38256. /**
  38257. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  38258. * within the passed time interval.
  38259. *
  38260. * @param {number} duration - The duration of the fade.
  38261. * @return {AnimationAction} A reference to this animation action.
  38262. */
  38263. fadeIn( duration ) {
  38264. return this._scheduleFading( duration, 0, 1 );
  38265. }
  38266. /**
  38267. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  38268. * within the passed time interval.
  38269. *
  38270. * @param {number} duration - The duration of the fade.
  38271. * @return {AnimationAction} A reference to this animation action.
  38272. */
  38273. fadeOut( duration ) {
  38274. return this._scheduleFading( duration, 1, 0 );
  38275. }
  38276. /**
  38277. * Causes this action to fade in and the given action to fade out,
  38278. * within the passed time interval.
  38279. *
  38280. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  38281. * @param {number} duration - The duration of the fade.
  38282. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38283. * @return {AnimationAction} A reference to this animation action.
  38284. */
  38285. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  38286. fadeOutAction.fadeOut( duration );
  38287. this.fadeIn( duration );
  38288. if ( warp === true ) {
  38289. const fadeInDuration = this._clip.duration,
  38290. fadeOutDuration = fadeOutAction._clip.duration,
  38291. startEndRatio = fadeOutDuration / fadeInDuration,
  38292. endStartRatio = fadeInDuration / fadeOutDuration;
  38293. fadeOutAction.warp( 1.0, startEndRatio, duration );
  38294. this.warp( endStartRatio, 1.0, duration );
  38295. }
  38296. return this;
  38297. }
  38298. /**
  38299. * Causes this action to fade out and the given action to fade in,
  38300. * within the passed time interval.
  38301. *
  38302. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  38303. * @param {number} duration - The duration of the fade.
  38304. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38305. * @return {AnimationAction} A reference to this animation action.
  38306. */
  38307. crossFadeTo( fadeInAction, duration, warp = false ) {
  38308. return fadeInAction.crossFadeFrom( this, duration, warp );
  38309. }
  38310. /**
  38311. * Stops any fading which is applied to this action.
  38312. *
  38313. * @return {AnimationAction} A reference to this animation action.
  38314. */
  38315. stopFading() {
  38316. const weightInterpolant = this._weightInterpolant;
  38317. if ( weightInterpolant !== null ) {
  38318. this._weightInterpolant = null;
  38319. this._mixer._takeBackControlInterpolant( weightInterpolant );
  38320. }
  38321. return this;
  38322. }
  38323. /**
  38324. * Sets the effective time scale of this action.
  38325. *
  38326. * An action has no effect and thus an effective time scale of zero when the
  38327. * action is paused.
  38328. *
  38329. * @param {number} timeScale - The time scale to set.
  38330. * @return {AnimationAction} A reference to this animation action.
  38331. */
  38332. setEffectiveTimeScale( timeScale ) {
  38333. this.timeScale = timeScale;
  38334. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  38335. return this.stopWarping();
  38336. }
  38337. /**
  38338. * Returns the effective time scale of this action.
  38339. *
  38340. * @return {number} The effective time scale.
  38341. */
  38342. getEffectiveTimeScale() {
  38343. return this._effectiveTimeScale;
  38344. }
  38345. /**
  38346. * Sets the duration for a single loop of this action.
  38347. *
  38348. * @param {number} duration - The duration to set.
  38349. * @return {AnimationAction} A reference to this animation action.
  38350. */
  38351. setDuration( duration ) {
  38352. this.timeScale = this._clip.duration / duration;
  38353. return this.stopWarping();
  38354. }
  38355. /**
  38356. * Synchronizes this action with the passed other action.
  38357. *
  38358. * @param {AnimationAction} action - The action to sync with.
  38359. * @return {AnimationAction} A reference to this animation action.
  38360. */
  38361. syncWith( action ) {
  38362. this.time = action.time;
  38363. this.timeScale = action.timeScale;
  38364. return this.stopWarping();
  38365. }
  38366. /**
  38367. * Decelerates this animation's speed to `0` within the passed time interval.
  38368. *
  38369. * @param {number} duration - The duration.
  38370. * @return {AnimationAction} A reference to this animation action.
  38371. */
  38372. halt( duration ) {
  38373. return this.warp( this._effectiveTimeScale, 0, duration );
  38374. }
  38375. /**
  38376. * Changes the playback speed, within the passed time interval, by modifying
  38377. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  38378. * `endTimeScale`.
  38379. *
  38380. * @param {number} startTimeScale - The start time scale.
  38381. * @param {number} endTimeScale - The end time scale.
  38382. * @param {number} duration - The duration.
  38383. * @return {AnimationAction} A reference to this animation action.
  38384. */
  38385. warp( startTimeScale, endTimeScale, duration ) {
  38386. const mixer = this._mixer,
  38387. now = mixer.time,
  38388. timeScale = this.timeScale;
  38389. let interpolant = this._timeScaleInterpolant;
  38390. if ( interpolant === null ) {
  38391. interpolant = mixer._lendControlInterpolant();
  38392. this._timeScaleInterpolant = interpolant;
  38393. }
  38394. const times = interpolant.parameterPositions,
  38395. values = interpolant.sampleValues;
  38396. times[ 0 ] = now;
  38397. times[ 1 ] = now + duration;
  38398. values[ 0 ] = startTimeScale / timeScale;
  38399. values[ 1 ] = endTimeScale / timeScale;
  38400. return this;
  38401. }
  38402. /**
  38403. * Stops any scheduled warping which is applied to this action.
  38404. *
  38405. * @return {AnimationAction} A reference to this animation action.
  38406. */
  38407. stopWarping() {
  38408. const timeScaleInterpolant = this._timeScaleInterpolant;
  38409. if ( timeScaleInterpolant !== null ) {
  38410. this._timeScaleInterpolant = null;
  38411. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  38412. }
  38413. return this;
  38414. }
  38415. /**
  38416. * Returns the animation mixer of this animation action.
  38417. *
  38418. * @return {AnimationMixer} The animation mixer.
  38419. */
  38420. getMixer() {
  38421. return this._mixer;
  38422. }
  38423. /**
  38424. * Returns the animation clip of this animation action.
  38425. *
  38426. * @return {AnimationClip} The animation clip.
  38427. */
  38428. getClip() {
  38429. return this._clip;
  38430. }
  38431. /**
  38432. * Returns the root object of this animation action.
  38433. *
  38434. * @return {Object3D} The root object.
  38435. */
  38436. getRoot() {
  38437. return this._localRoot || this._mixer._root;
  38438. }
  38439. // Interna
  38440. _update( time, deltaTime, timeDirection, accuIndex ) {
  38441. // called by the mixer
  38442. if ( ! this.enabled ) {
  38443. // call ._updateWeight() to update ._effectiveWeight
  38444. this._updateWeight( time );
  38445. return;
  38446. }
  38447. const startTime = this._startTime;
  38448. if ( startTime !== null ) {
  38449. // check for scheduled start of action
  38450. const timeRunning = ( time - startTime ) * timeDirection;
  38451. if ( timeRunning < 0 || timeDirection === 0 ) {
  38452. deltaTime = 0;
  38453. } else {
  38454. this._startTime = null; // unschedule
  38455. deltaTime = timeDirection * timeRunning;
  38456. }
  38457. }
  38458. // apply time scale and advance time
  38459. deltaTime *= this._updateTimeScale( time );
  38460. const clipTime = this._updateTime( deltaTime );
  38461. // note: _updateTime may disable the action resulting in
  38462. // an effective weight of 0
  38463. const weight = this._updateWeight( time );
  38464. if ( weight > 0 ) {
  38465. const interpolants = this._interpolants;
  38466. const propertyMixers = this._propertyBindings;
  38467. switch ( this.blendMode ) {
  38468. case AdditiveAnimationBlendMode:
  38469. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38470. interpolants[ j ].evaluate( clipTime );
  38471. propertyMixers[ j ].accumulateAdditive( weight );
  38472. }
  38473. break;
  38474. case NormalAnimationBlendMode:
  38475. default:
  38476. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38477. interpolants[ j ].evaluate( clipTime );
  38478. propertyMixers[ j ].accumulate( accuIndex, weight );
  38479. }
  38480. }
  38481. }
  38482. }
  38483. _updateWeight( time ) {
  38484. let weight = 0;
  38485. if ( this.enabled ) {
  38486. weight = this.weight;
  38487. const interpolant = this._weightInterpolant;
  38488. if ( interpolant !== null ) {
  38489. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38490. weight *= interpolantValue;
  38491. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38492. this.stopFading();
  38493. if ( interpolantValue === 0 ) {
  38494. // faded out, disable
  38495. this.enabled = false;
  38496. }
  38497. }
  38498. }
  38499. }
  38500. this._effectiveWeight = weight;
  38501. return weight;
  38502. }
  38503. _updateTimeScale( time ) {
  38504. let timeScale = 0;
  38505. if ( ! this.paused ) {
  38506. timeScale = this.timeScale;
  38507. const interpolant = this._timeScaleInterpolant;
  38508. if ( interpolant !== null ) {
  38509. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38510. timeScale *= interpolantValue;
  38511. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38512. this.stopWarping();
  38513. if ( timeScale === 0 ) {
  38514. // motion has halted, pause
  38515. this.paused = true;
  38516. } else {
  38517. // warp done - apply final time scale
  38518. this.timeScale = timeScale;
  38519. }
  38520. }
  38521. }
  38522. }
  38523. this._effectiveTimeScale = timeScale;
  38524. return timeScale;
  38525. }
  38526. _updateTime( deltaTime ) {
  38527. const duration = this._clip.duration;
  38528. const loop = this.loop;
  38529. let time = this.time + deltaTime;
  38530. let loopCount = this._loopCount;
  38531. const pingPong = ( loop === LoopPingPong );
  38532. if ( deltaTime === 0 ) {
  38533. if ( loopCount === -1 ) return time;
  38534. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  38535. }
  38536. if ( loop === LoopOnce ) {
  38537. if ( loopCount === -1 ) {
  38538. // just started
  38539. this._loopCount = 0;
  38540. this._setEndings( true, true, false );
  38541. }
  38542. handle_stop: {
  38543. if ( time >= duration ) {
  38544. time = duration;
  38545. } else if ( time < 0 ) {
  38546. time = 0;
  38547. } else {
  38548. this.time = time;
  38549. break handle_stop;
  38550. }
  38551. if ( this.clampWhenFinished ) this.paused = true;
  38552. else this.enabled = false;
  38553. this.time = time;
  38554. this._mixer.dispatchEvent( {
  38555. type: 'finished', action: this,
  38556. direction: deltaTime < 0 ? -1 : 1
  38557. } );
  38558. }
  38559. } else { // repetitive Repeat or PingPong
  38560. if ( loopCount === -1 ) {
  38561. // just started
  38562. if ( deltaTime >= 0 ) {
  38563. loopCount = 0;
  38564. this._setEndings( true, this.repetitions === 0, pingPong );
  38565. } else {
  38566. // when looping in reverse direction, the initial
  38567. // transition through zero counts as a repetition,
  38568. // so leave loopCount at -1
  38569. this._setEndings( this.repetitions === 0, true, pingPong );
  38570. }
  38571. }
  38572. if ( time >= duration || time < 0 ) {
  38573. // wrap around
  38574. const loopDelta = Math.floor( time / duration ); // signed
  38575. time -= duration * loopDelta;
  38576. loopCount += Math.abs( loopDelta );
  38577. const pending = this.repetitions - loopCount;
  38578. if ( pending <= 0 ) {
  38579. // have to stop (switch state, clamp time, fire event)
  38580. if ( this.clampWhenFinished ) this.paused = true;
  38581. else this.enabled = false;
  38582. time = deltaTime > 0 ? duration : 0;
  38583. this.time = time;
  38584. this._mixer.dispatchEvent( {
  38585. type: 'finished', action: this,
  38586. direction: deltaTime > 0 ? 1 : -1
  38587. } );
  38588. } else {
  38589. // keep running
  38590. if ( pending === 1 ) {
  38591. // entering the last round
  38592. const atStart = deltaTime < 0;
  38593. this._setEndings( atStart, ! atStart, pingPong );
  38594. } else {
  38595. this._setEndings( false, false, pingPong );
  38596. }
  38597. this._loopCount = loopCount;
  38598. this.time = time;
  38599. this._mixer.dispatchEvent( {
  38600. type: 'loop', action: this, loopDelta: loopDelta
  38601. } );
  38602. }
  38603. } else {
  38604. this.time = time;
  38605. }
  38606. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  38607. // invert time for the "pong round"
  38608. return duration - time;
  38609. }
  38610. }
  38611. return time;
  38612. }
  38613. _setEndings( atStart, atEnd, pingPong ) {
  38614. const settings = this._interpolantSettings;
  38615. if ( pingPong ) {
  38616. settings.endingStart = ZeroSlopeEnding;
  38617. settings.endingEnd = ZeroSlopeEnding;
  38618. } else {
  38619. // assuming for LoopOnce atStart == atEnd == true
  38620. if ( atStart ) {
  38621. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38622. } else {
  38623. settings.endingStart = WrapAroundEnding;
  38624. }
  38625. if ( atEnd ) {
  38626. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38627. } else {
  38628. settings.endingEnd = WrapAroundEnding;
  38629. }
  38630. }
  38631. }
  38632. _scheduleFading( duration, weightNow, weightThen ) {
  38633. const mixer = this._mixer, now = mixer.time;
  38634. let interpolant = this._weightInterpolant;
  38635. if ( interpolant === null ) {
  38636. interpolant = mixer._lendControlInterpolant();
  38637. this._weightInterpolant = interpolant;
  38638. }
  38639. const times = interpolant.parameterPositions,
  38640. values = interpolant.sampleValues;
  38641. times[ 0 ] = now;
  38642. values[ 0 ] = weightNow;
  38643. times[ 1 ] = now + duration;
  38644. values[ 1 ] = weightThen;
  38645. return this;
  38646. }
  38647. }
  38648. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  38649. /**
  38650. * `AnimationMixer` is a player for animations on a particular object in
  38651. * the scene. When multiple objects in the scene are animated independently,
  38652. * one `AnimationMixer` may be used for each object.
  38653. */
  38654. class AnimationMixer extends EventDispatcher {
  38655. /**
  38656. * Constructs a new animation mixer.
  38657. *
  38658. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  38659. */
  38660. constructor( root ) {
  38661. super();
  38662. this._root = root;
  38663. this._initMemoryManager();
  38664. this._accuIndex = 0;
  38665. /**
  38666. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  38667. *
  38668. * @type {number}
  38669. * @default 0
  38670. */
  38671. this.time = 0;
  38672. /**
  38673. * A scaling factor for the global time.
  38674. *
  38675. * Note: Setting this member to `0` and later back to `1` is a
  38676. * possibility to pause/unpause all actions that are controlled by this
  38677. * mixer.
  38678. *
  38679. * @type {number}
  38680. * @default 1
  38681. */
  38682. this.timeScale = 1.0;
  38683. }
  38684. _bindAction( action, prototypeAction ) {
  38685. const root = action._localRoot || this._root,
  38686. tracks = action._clip.tracks,
  38687. nTracks = tracks.length,
  38688. bindings = action._propertyBindings,
  38689. interpolants = action._interpolants,
  38690. rootUuid = root.uuid,
  38691. bindingsByRoot = this._bindingsByRootAndName;
  38692. let bindingsByName = bindingsByRoot[ rootUuid ];
  38693. if ( bindingsByName === undefined ) {
  38694. bindingsByName = {};
  38695. bindingsByRoot[ rootUuid ] = bindingsByName;
  38696. }
  38697. for ( let i = 0; i !== nTracks; ++ i ) {
  38698. const track = tracks[ i ],
  38699. trackName = track.name;
  38700. let binding = bindingsByName[ trackName ];
  38701. if ( binding !== undefined ) {
  38702. ++ binding.referenceCount;
  38703. bindings[ i ] = binding;
  38704. } else {
  38705. binding = bindings[ i ];
  38706. if ( binding !== undefined ) {
  38707. // existing binding, make sure the cache knows
  38708. if ( binding._cacheIndex === null ) {
  38709. ++ binding.referenceCount;
  38710. this._addInactiveBinding( binding, rootUuid, trackName );
  38711. }
  38712. continue;
  38713. }
  38714. const path = prototypeAction && prototypeAction.
  38715. _propertyBindings[ i ].binding.parsedPath;
  38716. binding = new PropertyMixer(
  38717. PropertyBinding.create( root, trackName, path ),
  38718. track.ValueTypeName, track.getValueSize() );
  38719. ++ binding.referenceCount;
  38720. this._addInactiveBinding( binding, rootUuid, trackName );
  38721. bindings[ i ] = binding;
  38722. }
  38723. interpolants[ i ].resultBuffer = binding.buffer;
  38724. }
  38725. }
  38726. _activateAction( action ) {
  38727. if ( ! this._isActiveAction( action ) ) {
  38728. if ( action._cacheIndex === null ) {
  38729. // this action has been forgotten by the cache, but the user
  38730. // appears to be still using it -> rebind
  38731. const rootUuid = ( action._localRoot || this._root ).uuid,
  38732. clipUuid = action._clip.uuid,
  38733. actionsForClip = this._actionsByClip[ clipUuid ];
  38734. this._bindAction( action,
  38735. actionsForClip && actionsForClip.knownActions[ 0 ] );
  38736. this._addInactiveAction( action, clipUuid, rootUuid );
  38737. }
  38738. const bindings = action._propertyBindings;
  38739. // increment reference counts / sort out state
  38740. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38741. const binding = bindings[ i ];
  38742. if ( binding.useCount ++ === 0 ) {
  38743. this._lendBinding( binding );
  38744. binding.saveOriginalState();
  38745. }
  38746. }
  38747. this._lendAction( action );
  38748. }
  38749. }
  38750. _deactivateAction( action ) {
  38751. if ( this._isActiveAction( action ) ) {
  38752. const bindings = action._propertyBindings;
  38753. // decrement reference counts / sort out state
  38754. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38755. const binding = bindings[ i ];
  38756. if ( -- binding.useCount === 0 ) {
  38757. binding.restoreOriginalState();
  38758. this._takeBackBinding( binding );
  38759. }
  38760. }
  38761. this._takeBackAction( action );
  38762. }
  38763. }
  38764. // Memory manager
  38765. _initMemoryManager() {
  38766. this._actions = []; // 'nActiveActions' followed by inactive ones
  38767. this._nActiveActions = 0;
  38768. this._actionsByClip = {};
  38769. // inside:
  38770. // {
  38771. // knownActions: Array< AnimationAction > - used as prototypes
  38772. // actionByRoot: AnimationAction - lookup
  38773. // }
  38774. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  38775. this._nActiveBindings = 0;
  38776. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  38777. this._controlInterpolants = []; // same game as above
  38778. this._nActiveControlInterpolants = 0;
  38779. const scope = this;
  38780. this.stats = {
  38781. actions: {
  38782. get total() {
  38783. return scope._actions.length;
  38784. },
  38785. get inUse() {
  38786. return scope._nActiveActions;
  38787. }
  38788. },
  38789. bindings: {
  38790. get total() {
  38791. return scope._bindings.length;
  38792. },
  38793. get inUse() {
  38794. return scope._nActiveBindings;
  38795. }
  38796. },
  38797. controlInterpolants: {
  38798. get total() {
  38799. return scope._controlInterpolants.length;
  38800. },
  38801. get inUse() {
  38802. return scope._nActiveControlInterpolants;
  38803. }
  38804. }
  38805. };
  38806. }
  38807. // Memory management for AnimationAction objects
  38808. _isActiveAction( action ) {
  38809. const index = action._cacheIndex;
  38810. return index !== null && index < this._nActiveActions;
  38811. }
  38812. _addInactiveAction( action, clipUuid, rootUuid ) {
  38813. const actions = this._actions,
  38814. actionsByClip = this._actionsByClip;
  38815. let actionsForClip = actionsByClip[ clipUuid ];
  38816. if ( actionsForClip === undefined ) {
  38817. actionsForClip = {
  38818. knownActions: [ action ],
  38819. actionByRoot: {}
  38820. };
  38821. action._byClipCacheIndex = 0;
  38822. actionsByClip[ clipUuid ] = actionsForClip;
  38823. } else {
  38824. const knownActions = actionsForClip.knownActions;
  38825. action._byClipCacheIndex = knownActions.length;
  38826. knownActions.push( action );
  38827. }
  38828. action._cacheIndex = actions.length;
  38829. actions.push( action );
  38830. actionsForClip.actionByRoot[ rootUuid ] = action;
  38831. }
  38832. _removeInactiveAction( action ) {
  38833. const actions = this._actions,
  38834. lastInactiveAction = actions[ actions.length - 1 ],
  38835. cacheIndex = action._cacheIndex;
  38836. lastInactiveAction._cacheIndex = cacheIndex;
  38837. actions[ cacheIndex ] = lastInactiveAction;
  38838. actions.pop();
  38839. action._cacheIndex = null;
  38840. const clipUuid = action._clip.uuid,
  38841. actionsByClip = this._actionsByClip,
  38842. actionsForClip = actionsByClip[ clipUuid ],
  38843. knownActionsForClip = actionsForClip.knownActions,
  38844. lastKnownAction =
  38845. knownActionsForClip[ knownActionsForClip.length - 1 ],
  38846. byClipCacheIndex = action._byClipCacheIndex;
  38847. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  38848. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  38849. knownActionsForClip.pop();
  38850. action._byClipCacheIndex = null;
  38851. const actionByRoot = actionsForClip.actionByRoot,
  38852. rootUuid = ( action._localRoot || this._root ).uuid;
  38853. delete actionByRoot[ rootUuid ];
  38854. if ( knownActionsForClip.length === 0 ) {
  38855. delete actionsByClip[ clipUuid ];
  38856. }
  38857. this._removeInactiveBindingsForAction( action );
  38858. }
  38859. _removeInactiveBindingsForAction( action ) {
  38860. const bindings = action._propertyBindings;
  38861. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38862. const binding = bindings[ i ];
  38863. if ( -- binding.referenceCount === 0 ) {
  38864. this._removeInactiveBinding( binding );
  38865. }
  38866. }
  38867. }
  38868. _lendAction( action ) {
  38869. // [ active actions | inactive actions ]
  38870. // [ active actions >| inactive actions ]
  38871. // s a
  38872. // <-swap->
  38873. // a s
  38874. const actions = this._actions,
  38875. prevIndex = action._cacheIndex,
  38876. lastActiveIndex = this._nActiveActions ++,
  38877. firstInactiveAction = actions[ lastActiveIndex ];
  38878. action._cacheIndex = lastActiveIndex;
  38879. actions[ lastActiveIndex ] = action;
  38880. firstInactiveAction._cacheIndex = prevIndex;
  38881. actions[ prevIndex ] = firstInactiveAction;
  38882. }
  38883. _takeBackAction( action ) {
  38884. // [ active actions | inactive actions ]
  38885. // [ active actions |< inactive actions ]
  38886. // a s
  38887. // <-swap->
  38888. // s a
  38889. const actions = this._actions,
  38890. prevIndex = action._cacheIndex,
  38891. firstInactiveIndex = -- this._nActiveActions,
  38892. lastActiveAction = actions[ firstInactiveIndex ];
  38893. action._cacheIndex = firstInactiveIndex;
  38894. actions[ firstInactiveIndex ] = action;
  38895. lastActiveAction._cacheIndex = prevIndex;
  38896. actions[ prevIndex ] = lastActiveAction;
  38897. }
  38898. // Memory management for PropertyMixer objects
  38899. _addInactiveBinding( binding, rootUuid, trackName ) {
  38900. const bindingsByRoot = this._bindingsByRootAndName,
  38901. bindings = this._bindings;
  38902. let bindingByName = bindingsByRoot[ rootUuid ];
  38903. if ( bindingByName === undefined ) {
  38904. bindingByName = {};
  38905. bindingsByRoot[ rootUuid ] = bindingByName;
  38906. }
  38907. bindingByName[ trackName ] = binding;
  38908. binding._cacheIndex = bindings.length;
  38909. bindings.push( binding );
  38910. }
  38911. _removeInactiveBinding( binding ) {
  38912. const bindings = this._bindings,
  38913. propBinding = binding.binding,
  38914. rootUuid = propBinding.rootNode.uuid,
  38915. trackName = propBinding.path,
  38916. bindingsByRoot = this._bindingsByRootAndName,
  38917. bindingByName = bindingsByRoot[ rootUuid ],
  38918. lastInactiveBinding = bindings[ bindings.length - 1 ],
  38919. cacheIndex = binding._cacheIndex;
  38920. lastInactiveBinding._cacheIndex = cacheIndex;
  38921. bindings[ cacheIndex ] = lastInactiveBinding;
  38922. bindings.pop();
  38923. delete bindingByName[ trackName ];
  38924. if ( Object.keys( bindingByName ).length === 0 ) {
  38925. delete bindingsByRoot[ rootUuid ];
  38926. }
  38927. }
  38928. _lendBinding( binding ) {
  38929. const bindings = this._bindings,
  38930. prevIndex = binding._cacheIndex,
  38931. lastActiveIndex = this._nActiveBindings ++,
  38932. firstInactiveBinding = bindings[ lastActiveIndex ];
  38933. binding._cacheIndex = lastActiveIndex;
  38934. bindings[ lastActiveIndex ] = binding;
  38935. firstInactiveBinding._cacheIndex = prevIndex;
  38936. bindings[ prevIndex ] = firstInactiveBinding;
  38937. }
  38938. _takeBackBinding( binding ) {
  38939. const bindings = this._bindings,
  38940. prevIndex = binding._cacheIndex,
  38941. firstInactiveIndex = -- this._nActiveBindings,
  38942. lastActiveBinding = bindings[ firstInactiveIndex ];
  38943. binding._cacheIndex = firstInactiveIndex;
  38944. bindings[ firstInactiveIndex ] = binding;
  38945. lastActiveBinding._cacheIndex = prevIndex;
  38946. bindings[ prevIndex ] = lastActiveBinding;
  38947. }
  38948. // Memory management of Interpolants for weight and time scale
  38949. _lendControlInterpolant() {
  38950. const interpolants = this._controlInterpolants,
  38951. lastActiveIndex = this._nActiveControlInterpolants ++;
  38952. let interpolant = interpolants[ lastActiveIndex ];
  38953. if ( interpolant === undefined ) {
  38954. interpolant = new LinearInterpolant(
  38955. new Float32Array( 2 ), new Float32Array( 2 ),
  38956. 1, _controlInterpolantsResultBuffer );
  38957. interpolant.__cacheIndex = lastActiveIndex;
  38958. interpolants[ lastActiveIndex ] = interpolant;
  38959. }
  38960. return interpolant;
  38961. }
  38962. _takeBackControlInterpolant( interpolant ) {
  38963. const interpolants = this._controlInterpolants,
  38964. prevIndex = interpolant.__cacheIndex,
  38965. firstInactiveIndex = -- this._nActiveControlInterpolants,
  38966. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  38967. interpolant.__cacheIndex = firstInactiveIndex;
  38968. interpolants[ firstInactiveIndex ] = interpolant;
  38969. lastActiveInterpolant.__cacheIndex = prevIndex;
  38970. interpolants[ prevIndex ] = lastActiveInterpolant;
  38971. }
  38972. /**
  38973. * Returns an instance of {@link AnimationAction} for the passed clip.
  38974. *
  38975. * If an action fitting the clip and root parameters doesn't yet exist, it
  38976. * will be created by this method. Calling this method several times with the
  38977. * same clip and root parameters always returns the same action.
  38978. *
  38979. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  38980. * @param {Object3D} [optionalRoot] - An alternative root object.
  38981. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38982. * @return {?AnimationAction} The animation action.
  38983. */
  38984. clipAction( clip, optionalRoot, blendMode ) {
  38985. const root = optionalRoot || this._root,
  38986. rootUuid = root.uuid;
  38987. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  38988. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  38989. const actionsForClip = this._actionsByClip[ clipUuid ];
  38990. let prototypeAction = null;
  38991. if ( blendMode === undefined ) {
  38992. if ( clipObject !== null ) {
  38993. blendMode = clipObject.blendMode;
  38994. } else {
  38995. blendMode = NormalAnimationBlendMode;
  38996. }
  38997. }
  38998. if ( actionsForClip !== undefined ) {
  38999. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  39000. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  39001. return existingAction;
  39002. }
  39003. // we know the clip, so we don't have to parse all
  39004. // the bindings again but can just copy
  39005. prototypeAction = actionsForClip.knownActions[ 0 ];
  39006. // also, take the clip from the prototype action
  39007. if ( clipObject === null )
  39008. clipObject = prototypeAction._clip;
  39009. }
  39010. // clip must be known when specified via string
  39011. if ( clipObject === null ) return null;
  39012. // allocate all resources required to run it
  39013. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  39014. this._bindAction( newAction, prototypeAction );
  39015. // and make the action known to the memory manager
  39016. this._addInactiveAction( newAction, clipUuid, rootUuid );
  39017. return newAction;
  39018. }
  39019. /**
  39020. * Returns an existing animation action for the passed clip.
  39021. *
  39022. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39023. * @param {Object3D} [optionalRoot] - An alternative root object.
  39024. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  39025. */
  39026. existingAction( clip, optionalRoot ) {
  39027. const root = optionalRoot || this._root,
  39028. rootUuid = root.uuid,
  39029. clipObject = typeof clip === 'string' ?
  39030. AnimationClip.findByName( root, clip ) : clip,
  39031. clipUuid = clipObject ? clipObject.uuid : clip,
  39032. actionsForClip = this._actionsByClip[ clipUuid ];
  39033. if ( actionsForClip !== undefined ) {
  39034. return actionsForClip.actionByRoot[ rootUuid ] || null;
  39035. }
  39036. return null;
  39037. }
  39038. /**
  39039. * Deactivates all previously scheduled actions on this mixer.
  39040. *
  39041. * @return {AnimationMixer} A reference to thi animation mixer.
  39042. */
  39043. stopAllAction() {
  39044. const actions = this._actions,
  39045. nActions = this._nActiveActions;
  39046. for ( let i = nActions - 1; i >= 0; -- i ) {
  39047. actions[ i ].stop();
  39048. }
  39049. return this;
  39050. }
  39051. /**
  39052. * Advances the global mixer time and updates the animation.
  39053. *
  39054. * This is usually done in the render loop by passing the delta
  39055. * time from {@link Clock} or {@link Timer}.
  39056. *
  39057. * @param {number} deltaTime - The delta time in seconds.
  39058. * @return {AnimationMixer} A reference to thi animation mixer.
  39059. */
  39060. update( deltaTime ) {
  39061. deltaTime *= this.timeScale;
  39062. const actions = this._actions,
  39063. nActions = this._nActiveActions,
  39064. time = this.time += deltaTime,
  39065. timeDirection = Math.sign( deltaTime ),
  39066. accuIndex = this._accuIndex ^= 1;
  39067. // run active actions
  39068. for ( let i = 0; i !== nActions; ++ i ) {
  39069. const action = actions[ i ];
  39070. action._update( time, deltaTime, timeDirection, accuIndex );
  39071. }
  39072. // update scene graph
  39073. const bindings = this._bindings,
  39074. nBindings = this._nActiveBindings;
  39075. for ( let i = 0; i !== nBindings; ++ i ) {
  39076. bindings[ i ].apply( accuIndex );
  39077. }
  39078. return this;
  39079. }
  39080. /**
  39081. * Sets the global mixer to a specific time and updates the animation accordingly.
  39082. *
  39083. * This is useful when you need to jump to an exact time in an animation. The
  39084. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  39085. *
  39086. * @param {number} time - The time to set in seconds.
  39087. * @return {AnimationMixer} A reference to thi animation mixer.
  39088. */
  39089. setTime( time ) {
  39090. this.time = 0; // Zero out time attribute for AnimationMixer object;
  39091. for ( let i = 0; i < this._actions.length; i ++ ) {
  39092. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  39093. }
  39094. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  39095. }
  39096. /**
  39097. * Returns this mixer's root object.
  39098. *
  39099. * @return {Object3D} The mixer's root object.
  39100. */
  39101. getRoot() {
  39102. return this._root;
  39103. }
  39104. /**
  39105. * Deallocates all memory resources for a clip. Before using this method make
  39106. * sure to call {@link AnimationAction#stop} for all related actions.
  39107. *
  39108. * @param {AnimationClip} clip - The clip to uncache.
  39109. */
  39110. uncacheClip( clip ) {
  39111. const actions = this._actions,
  39112. clipUuid = clip.uuid,
  39113. actionsByClip = this._actionsByClip,
  39114. actionsForClip = actionsByClip[ clipUuid ];
  39115. if ( actionsForClip !== undefined ) {
  39116. // note: just calling _removeInactiveAction would mess up the
  39117. // iteration state and also require updating the state we can
  39118. // just throw away
  39119. const actionsToRemove = actionsForClip.knownActions;
  39120. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  39121. const action = actionsToRemove[ i ];
  39122. this._deactivateAction( action );
  39123. const cacheIndex = action._cacheIndex,
  39124. lastInactiveAction = actions[ actions.length - 1 ];
  39125. action._cacheIndex = null;
  39126. action._byClipCacheIndex = null;
  39127. lastInactiveAction._cacheIndex = cacheIndex;
  39128. actions[ cacheIndex ] = lastInactiveAction;
  39129. actions.pop();
  39130. this._removeInactiveBindingsForAction( action );
  39131. }
  39132. delete actionsByClip[ clipUuid ];
  39133. }
  39134. }
  39135. /**
  39136. * Deallocates all memory resources for a root object. Before using this
  39137. * method make sure to call {@link AnimationAction#stop} for all related
  39138. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  39139. * mixer operates on a single root.
  39140. *
  39141. * @param {Object3D} root - The root object to uncache.
  39142. */
  39143. uncacheRoot( root ) {
  39144. const rootUuid = root.uuid,
  39145. actionsByClip = this._actionsByClip;
  39146. for ( const clipUuid in actionsByClip ) {
  39147. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  39148. action = actionByRoot[ rootUuid ];
  39149. if ( action !== undefined ) {
  39150. this._deactivateAction( action );
  39151. this._removeInactiveAction( action );
  39152. }
  39153. }
  39154. const bindingsByRoot = this._bindingsByRootAndName,
  39155. bindingByName = bindingsByRoot[ rootUuid ];
  39156. if ( bindingByName !== undefined ) {
  39157. for ( const trackName in bindingByName ) {
  39158. const binding = bindingByName[ trackName ];
  39159. binding.restoreOriginalState();
  39160. this._removeInactiveBinding( binding );
  39161. }
  39162. }
  39163. }
  39164. /**
  39165. * Deallocates all memory resources for an action. The action is identified by the
  39166. * given clip and an optional root object. Before using this method make
  39167. * sure to call {@link AnimationAction#stop} to deactivate the action.
  39168. *
  39169. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39170. * @param {Object3D} [optionalRoot] - An alternative root object.
  39171. */
  39172. uncacheAction( clip, optionalRoot ) {
  39173. const action = this.existingAction( clip, optionalRoot );
  39174. if ( action !== null ) {
  39175. this._deactivateAction( action );
  39176. this._removeInactiveAction( action );
  39177. }
  39178. }
  39179. }
  39180. /**
  39181. * Represents a 3D render target.
  39182. *
  39183. * @augments RenderTarget
  39184. */
  39185. class RenderTarget3D extends RenderTarget {
  39186. /**
  39187. * Constructs a new 3D render target.
  39188. *
  39189. * @param {number} [width=1] - The width of the render target.
  39190. * @param {number} [height=1] - The height of the render target.
  39191. * @param {number} [depth=1] - The height of the render target.
  39192. * @param {RenderTarget~Options} [options] - The configuration object.
  39193. */
  39194. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  39195. super( width, height, options );
  39196. /**
  39197. * This flag can be used for type testing.
  39198. *
  39199. * @type {boolean}
  39200. * @readonly
  39201. * @default true
  39202. */
  39203. this.isRenderTarget3D = true;
  39204. this.depth = depth;
  39205. /**
  39206. * Overwritten with a different texture type.
  39207. *
  39208. * @type {Data3DTexture}
  39209. */
  39210. this.texture = new Data3DTexture( null, width, height, depth );
  39211. this._setTextureOptions( options );
  39212. this.texture.isRenderTargetTexture = true;
  39213. }
  39214. }
  39215. /**
  39216. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  39217. *
  39218. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  39219. * ```js
  39220. * uniforms: {
  39221. * time: { value: 1.0 },
  39222. * resolution: new Uniform( new Vector2() )
  39223. * };
  39224. * ```
  39225. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39226. * in {@link WebGLRenderer}.
  39227. */
  39228. class Uniform {
  39229. /**
  39230. * Constructs a new uniform.
  39231. *
  39232. * @param {any} value - The uniform value.
  39233. */
  39234. constructor( value ) {
  39235. /**
  39236. * The uniform value.
  39237. *
  39238. * @type {any}
  39239. */
  39240. this.value = value;
  39241. }
  39242. /**
  39243. * Returns a new uniform with copied values from this instance.
  39244. * If the value has a `clone()` method, the value is cloned as well.
  39245. *
  39246. * @return {Uniform} A clone of this instance.
  39247. */
  39248. clone() {
  39249. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  39250. }
  39251. }
  39252. let _id$1 = 0;
  39253. /**
  39254. * A class for managing multiple uniforms in a single group. The renderer will process
  39255. * such a definition as a single UBO.
  39256. *
  39257. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39258. * in {@link WebGLRenderer}.
  39259. *
  39260. * @augments EventDispatcher
  39261. */
  39262. class UniformsGroup extends EventDispatcher {
  39263. /**
  39264. * Constructs a new uniforms group.
  39265. */
  39266. constructor() {
  39267. super();
  39268. /**
  39269. * This flag can be used for type testing.
  39270. *
  39271. * @type {boolean}
  39272. * @readonly
  39273. * @default true
  39274. */
  39275. this.isUniformsGroup = true;
  39276. /**
  39277. * The ID of the 3D object.
  39278. *
  39279. * @name UniformsGroup#id
  39280. * @type {number}
  39281. * @readonly
  39282. */
  39283. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  39284. /**
  39285. * The name of the uniforms group.
  39286. *
  39287. * @type {string}
  39288. */
  39289. this.name = '';
  39290. /**
  39291. * The buffer usage.
  39292. *
  39293. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  39294. * @default StaticDrawUsage
  39295. */
  39296. this.usage = StaticDrawUsage;
  39297. /**
  39298. * An array holding the uniforms.
  39299. *
  39300. * @type {Array<Uniform>}
  39301. */
  39302. this.uniforms = [];
  39303. }
  39304. /**
  39305. * Adds the given uniform to this uniforms group.
  39306. *
  39307. * @param {Uniform} uniform - The uniform to add.
  39308. * @return {UniformsGroup} A reference to this uniforms group.
  39309. */
  39310. add( uniform ) {
  39311. this.uniforms.push( uniform );
  39312. return this;
  39313. }
  39314. /**
  39315. * Removes the given uniform from this uniforms group.
  39316. *
  39317. * @param {Uniform} uniform - The uniform to remove.
  39318. * @return {UniformsGroup} A reference to this uniforms group.
  39319. */
  39320. remove( uniform ) {
  39321. const index = this.uniforms.indexOf( uniform );
  39322. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  39323. return this;
  39324. }
  39325. /**
  39326. * Sets the name of this uniforms group.
  39327. *
  39328. * @param {string} name - The name to set.
  39329. * @return {UniformsGroup} A reference to this uniforms group.
  39330. */
  39331. setName( name ) {
  39332. this.name = name;
  39333. return this;
  39334. }
  39335. /**
  39336. * Sets the usage of this uniforms group.
  39337. *
  39338. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  39339. * @return {UniformsGroup} A reference to this uniforms group.
  39340. */
  39341. setUsage( value ) {
  39342. this.usage = value;
  39343. return this;
  39344. }
  39345. /**
  39346. * Frees the GPU-related resources allocated by this instance. Call this
  39347. * method whenever this instance is no longer used in your app.
  39348. *
  39349. * @fires Texture#dispose
  39350. */
  39351. dispose() {
  39352. this.dispatchEvent( { type: 'dispose' } );
  39353. }
  39354. /**
  39355. * Copies the values of the given uniforms group to this instance.
  39356. *
  39357. * @param {UniformsGroup} source - The uniforms group to copy.
  39358. * @return {UniformsGroup} A reference to this uniforms group.
  39359. */
  39360. copy( source ) {
  39361. this.name = source.name;
  39362. this.usage = source.usage;
  39363. const uniformsSource = source.uniforms;
  39364. this.uniforms.length = 0;
  39365. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  39366. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  39367. for ( let j = 0; j < uniforms.length; j ++ ) {
  39368. this.uniforms.push( uniforms[ j ].clone() );
  39369. }
  39370. }
  39371. return this;
  39372. }
  39373. /**
  39374. * Returns a new uniforms group with copied values from this instance.
  39375. *
  39376. * @return {UniformsGroup} A clone of this instance.
  39377. */
  39378. clone() {
  39379. return new this.constructor().copy( this );
  39380. }
  39381. }
  39382. /**
  39383. * An instanced version of an interleaved buffer.
  39384. *
  39385. * @augments InterleavedBuffer
  39386. */
  39387. class InstancedInterleavedBuffer extends InterleavedBuffer {
  39388. /**
  39389. * Constructs a new instanced interleaved buffer.
  39390. *
  39391. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  39392. * @param {number} stride - The number of typed-array elements per vertex.
  39393. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  39394. */
  39395. constructor( array, stride, meshPerAttribute = 1 ) {
  39396. super( array, stride );
  39397. /**
  39398. * This flag can be used for type testing.
  39399. *
  39400. * @type {boolean}
  39401. * @readonly
  39402. * @default true
  39403. */
  39404. this.isInstancedInterleavedBuffer = true;
  39405. /**
  39406. * Defines how often a value of this buffer attribute should be repeated,
  39407. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  39408. *
  39409. * @type {number}
  39410. * @default 1
  39411. */
  39412. this.meshPerAttribute = meshPerAttribute;
  39413. }
  39414. copy( source ) {
  39415. super.copy( source );
  39416. this.meshPerAttribute = source.meshPerAttribute;
  39417. return this;
  39418. }
  39419. clone( data ) {
  39420. const ib = super.clone( data );
  39421. ib.meshPerAttribute = this.meshPerAttribute;
  39422. return ib;
  39423. }
  39424. toJSON( data ) {
  39425. const json = super.toJSON( data );
  39426. json.isInstancedInterleavedBuffer = true;
  39427. json.meshPerAttribute = this.meshPerAttribute;
  39428. return json;
  39429. }
  39430. }
  39431. /**
  39432. * An alternative version of a buffer attribute with more control over the VBO.
  39433. *
  39434. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  39435. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  39436. *
  39437. * The most common use case for this class is when some kind of GPGPU calculation interferes
  39438. * or even produces the VBOs in question.
  39439. *
  39440. * Notice that this class can only be used with {@link WebGLRenderer}.
  39441. */
  39442. class GLBufferAttribute {
  39443. /**
  39444. * Constructs a new GL buffer attribute.
  39445. *
  39446. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  39447. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39448. * @param {number} itemSize - The item size.
  39449. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39450. * @param {number} count - The expected number of vertices in VBO.
  39451. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  39452. */
  39453. constructor( buffer, type, itemSize, elementSize, count, normalized = false ) {
  39454. /**
  39455. * This flag can be used for type testing.
  39456. *
  39457. * @type {boolean}
  39458. * @readonly
  39459. * @default true
  39460. */
  39461. this.isGLBufferAttribute = true;
  39462. /**
  39463. * The name of the buffer attribute.
  39464. *
  39465. * @type {string}
  39466. */
  39467. this.name = '';
  39468. /**
  39469. * The native WebGL buffer.
  39470. *
  39471. * @type {WebGLBuffer}
  39472. */
  39473. this.buffer = buffer;
  39474. /**
  39475. * The native data type.
  39476. *
  39477. * @type {number}
  39478. */
  39479. this.type = type;
  39480. /**
  39481. * The item size, see {@link BufferAttribute#itemSize}.
  39482. *
  39483. * @type {number}
  39484. */
  39485. this.itemSize = itemSize;
  39486. /**
  39487. * The corresponding size (in bytes) for the given `type` parameter.
  39488. *
  39489. * @type {number}
  39490. */
  39491. this.elementSize = elementSize;
  39492. /**
  39493. * The expected number of vertices in VBO.
  39494. *
  39495. * @type {number}
  39496. */
  39497. this.count = count;
  39498. /**
  39499. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  39500. * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`,
  39501. * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to
  39502. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  39503. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  39504. *
  39505. * @type {boolean}
  39506. */
  39507. this.normalized = normalized;
  39508. /**
  39509. * A version number, incremented every time the `needsUpdate` is set to `true`.
  39510. *
  39511. * @type {number}
  39512. */
  39513. this.version = 0;
  39514. }
  39515. /**
  39516. * Flag to indicate that this attribute has changed and should be re-sent to
  39517. * the GPU. Set this to `true` when you modify the value of the array.
  39518. *
  39519. * @type {number}
  39520. * @default false
  39521. * @param {boolean} value
  39522. */
  39523. set needsUpdate( value ) {
  39524. if ( value === true ) this.version ++;
  39525. }
  39526. /**
  39527. * Sets the given native WebGL buffer.
  39528. *
  39529. * @param {WebGLBuffer} buffer - The buffer to set.
  39530. * @return {BufferAttribute} A reference to this instance.
  39531. */
  39532. setBuffer( buffer ) {
  39533. this.buffer = buffer;
  39534. return this;
  39535. }
  39536. /**
  39537. * Sets the given native data type and element size.
  39538. *
  39539. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39540. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39541. * @return {BufferAttribute} A reference to this instance.
  39542. */
  39543. setType( type, elementSize ) {
  39544. this.type = type;
  39545. this.elementSize = elementSize;
  39546. return this;
  39547. }
  39548. /**
  39549. * Sets the item size.
  39550. *
  39551. * @param {number} itemSize - The item size.
  39552. * @return {BufferAttribute} A reference to this instance.
  39553. */
  39554. setItemSize( itemSize ) {
  39555. this.itemSize = itemSize;
  39556. return this;
  39557. }
  39558. /**
  39559. * Sets the count (the expected number of vertices in VBO).
  39560. *
  39561. * @param {number} count - The count.
  39562. * @return {BufferAttribute} A reference to this instance.
  39563. */
  39564. setCount( count ) {
  39565. this.count = count;
  39566. return this;
  39567. }
  39568. }
  39569. const _matrix = /*@__PURE__*/ new Matrix4();
  39570. /**
  39571. * This class is designed to assist with raycasting. Raycasting is used for
  39572. * mouse picking (working out what objects in the 3d space the mouse is over)
  39573. * amongst other things.
  39574. */
  39575. class Raycaster {
  39576. /**
  39577. * Constructs a new raycaster.
  39578. *
  39579. * @param {Vector3} origin - The origin vector where the ray casts from.
  39580. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39581. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  39582. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  39583. */
  39584. constructor( origin, direction, near = 0, far = Infinity ) {
  39585. /**
  39586. * The ray used for raycasting.
  39587. *
  39588. * @type {Ray}
  39589. */
  39590. this.ray = new Ray( origin, direction );
  39591. /**
  39592. * All results returned are further away than near. Near can't be negative.
  39593. *
  39594. * @type {number}
  39595. * @default 0
  39596. */
  39597. this.near = near;
  39598. /**
  39599. * All results returned are further away than near. Near can't be negative.
  39600. *
  39601. * @type {number}
  39602. * @default Infinity
  39603. */
  39604. this.far = far;
  39605. /**
  39606. * The camera to use when raycasting against view-dependent objects such as
  39607. * billboarded objects like sprites. This field can be set manually or
  39608. * is set when calling `setFromCamera()`.
  39609. *
  39610. * @type {?Camera}
  39611. * @default null
  39612. */
  39613. this.camera = null;
  39614. /**
  39615. * Allows to selectively ignore 3D objects when performing intersection tests.
  39616. * The following code example ensures that only 3D objects on layer `1` will be
  39617. * honored by raycaster.
  39618. * ```js
  39619. * raycaster.layers.set( 1 );
  39620. * object.layers.enable( 1 );
  39621. * ```
  39622. *
  39623. * @type {Layers}
  39624. */
  39625. this.layers = new Layers();
  39626. /**
  39627. * A parameter object that configures the raycasting. It has the structure:
  39628. *
  39629. * ```
  39630. * {
  39631. * Mesh: {},
  39632. * Line: { threshold: 1 },
  39633. * LOD: {},
  39634. * Points: { threshold: 1 },
  39635. * Sprite: {}
  39636. * }
  39637. * ```
  39638. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  39639. *
  39640. * @type {Object}
  39641. */
  39642. this.params = {
  39643. Mesh: {},
  39644. Line: { threshold: 1 },
  39645. LOD: {},
  39646. Points: { threshold: 1 },
  39647. Sprite: {}
  39648. };
  39649. }
  39650. /**
  39651. * Updates the ray with a new origin and direction by copying the values from the arguments.
  39652. *
  39653. * @param {Vector3} origin - The origin vector where the ray casts from.
  39654. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39655. */
  39656. set( origin, direction ) {
  39657. // direction is assumed to be normalized (for accurate distance calculations)
  39658. this.ray.set( origin, direction );
  39659. }
  39660. /**
  39661. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  39662. *
  39663. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  39664. * X and Y components should be between `-1` and `1`.
  39665. * @param {Camera} camera - The camera from which the ray should originate.
  39666. */
  39667. setFromCamera( coords, camera ) {
  39668. if ( camera.isPerspectiveCamera ) {
  39669. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  39670. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  39671. this.camera = camera;
  39672. } else if ( camera.isOrthographicCamera ) {
  39673. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  39674. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  39675. this.camera = camera;
  39676. } else {
  39677. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  39678. }
  39679. }
  39680. /**
  39681. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  39682. *
  39683. * @param {WebXRController} controller - The controller to copy the position and direction from.
  39684. * @return {Raycaster} A reference to this raycaster.
  39685. */
  39686. setFromXRController( controller ) {
  39687. _matrix.identity().extractRotation( controller.matrixWorld );
  39688. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  39689. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  39690. return this;
  39691. }
  39692. /**
  39693. * The intersection point of a raycaster intersection test.
  39694. * @typedef {Object} Raycaster~Intersection
  39695. * @property {number} distance - The distance from the ray's origin to the intersection point.
  39696. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  39697. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  39698. * @property {Vector3} point - The intersection point, in world coordinates.
  39699. * @property {Object} face - The face that has been intersected.
  39700. * @property {number} faceIndex - The face index.
  39701. * @property {Object3D} object - The 3D object that has been intersected.
  39702. * @property {Vector2} uv - U,V coordinates at point of intersection.
  39703. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  39704. * @property {Vector3} uv1 - Interpolated normal vector at point of intersection.
  39705. * @property {number} instanceId - The index number of the instance where the ray
  39706. * intersects the {@link InstancedMesh}.
  39707. */
  39708. /**
  39709. * Checks all intersection between the ray and the object with or without the
  39710. * descendants. Intersections are returned sorted by distance, closest first.
  39711. *
  39712. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  39713. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  39714. * differently to ray casting than lines or points.
  39715. *
  39716. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  39717. * to be detected; intersections of the ray passing through the back of a face will not
  39718. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  39719. * to `THREE.DoubleSide`.
  39720. *
  39721. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  39722. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39723. * Otherwise it only checks intersection with the object.
  39724. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39725. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39726. */
  39727. intersectObject( object, recursive = true, intersects = [] ) {
  39728. intersect( object, this, intersects, recursive );
  39729. intersects.sort( ascSort );
  39730. return intersects;
  39731. }
  39732. /**
  39733. * Checks all intersection between the ray and the objects with or without
  39734. * the descendants. Intersections are returned sorted by distance, closest first.
  39735. *
  39736. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  39737. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39738. * Otherwise it only checks intersection with the object.
  39739. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39740. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39741. */
  39742. intersectObjects( objects, recursive = true, intersects = [] ) {
  39743. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  39744. intersect( objects[ i ], this, intersects, recursive );
  39745. }
  39746. intersects.sort( ascSort );
  39747. return intersects;
  39748. }
  39749. }
  39750. function ascSort( a, b ) {
  39751. return a.distance - b.distance;
  39752. }
  39753. function intersect( object, raycaster, intersects, recursive ) {
  39754. let propagate = true;
  39755. if ( object.layers.test( raycaster.layers ) ) {
  39756. const result = object.raycast( raycaster, intersects );
  39757. if ( result === false ) propagate = false;
  39758. }
  39759. if ( propagate === true && recursive === true ) {
  39760. const children = object.children;
  39761. for ( let i = 0, l = children.length; i < l; i ++ ) {
  39762. intersect( children[ i ], raycaster, intersects, true );
  39763. }
  39764. }
  39765. }
  39766. /**
  39767. * This class is an alternative to {@link Clock} with a different API design and behavior.
  39768. * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
  39769. *
  39770. * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
  39771. * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
  39772. * - The class can make use of the Page Visibility API to avoid large time delta values when the app
  39773. * is inactive (e.g. tab switched or browser hidden).
  39774. *
  39775. * ```js
  39776. * const timer = new Timer();
  39777. * timer.connect( document ); // use Page Visibility API
  39778. * ```
  39779. */
  39780. class Timer {
  39781. /**
  39782. * Constructs a new timer.
  39783. */
  39784. constructor() {
  39785. this._previousTime = 0;
  39786. this._currentTime = 0;
  39787. this._startTime = performance.now();
  39788. this._delta = 0;
  39789. this._elapsed = 0;
  39790. this._timescale = 1;
  39791. this._document = null;
  39792. this._pageVisibilityHandler = null;
  39793. }
  39794. /**
  39795. * Connect the timer to the given document.Calling this method is not mandatory to
  39796. * use the timer but enables the usage of the Page Visibility API to avoid large time
  39797. * delta values.
  39798. *
  39799. * @param {Document} document - The document.
  39800. */
  39801. connect( document ) {
  39802. this._document = document;
  39803. // use Page Visibility API to avoid large time delta values
  39804. if ( document.hidden !== undefined ) {
  39805. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  39806. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  39807. }
  39808. }
  39809. /**
  39810. * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
  39811. */
  39812. disconnect() {
  39813. if ( this._pageVisibilityHandler !== null ) {
  39814. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  39815. this._pageVisibilityHandler = null;
  39816. }
  39817. this._document = null;
  39818. }
  39819. /**
  39820. * Returns the time delta in seconds.
  39821. *
  39822. * @return {number} The time delta in second.
  39823. */
  39824. getDelta() {
  39825. return this._delta / 1000;
  39826. }
  39827. /**
  39828. * Returns the elapsed time in seconds.
  39829. *
  39830. * @return {number} The elapsed time in second.
  39831. */
  39832. getElapsed() {
  39833. return this._elapsed / 1000;
  39834. }
  39835. /**
  39836. * Returns the timescale.
  39837. *
  39838. * @return {number} The timescale.
  39839. */
  39840. getTimescale() {
  39841. return this._timescale;
  39842. }
  39843. /**
  39844. * Sets the given timescale which scale the time delta computation
  39845. * in `update()`.
  39846. *
  39847. * @param {number} timescale - The timescale to set.
  39848. * @return {Timer} A reference to this timer.
  39849. */
  39850. setTimescale( timescale ) {
  39851. this._timescale = timescale;
  39852. return this;
  39853. }
  39854. /**
  39855. * Resets the time computation for the current simulation step.
  39856. *
  39857. * @return {Timer} A reference to this timer.
  39858. */
  39859. reset() {
  39860. this._currentTime = performance.now() - this._startTime;
  39861. return this;
  39862. }
  39863. /**
  39864. * Can be used to free all internal resources. Usually called when
  39865. * the timer instance isn't required anymore.
  39866. */
  39867. dispose() {
  39868. this.disconnect();
  39869. }
  39870. /**
  39871. * Updates the internal state of the timer. This method should be called
  39872. * once per simulation step and before you perform queries against the timer
  39873. * (e.g. via `getDelta()`).
  39874. *
  39875. * @param {number} timestamp - The current time in milliseconds. Can be obtained
  39876. * from the `requestAnimationFrame` callback argument. If not provided, the current
  39877. * time will be determined with `performance.now`.
  39878. * @return {Timer} A reference to this timer.
  39879. */
  39880. update( timestamp ) {
  39881. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  39882. this._delta = 0;
  39883. } else {
  39884. this._previousTime = this._currentTime;
  39885. this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime;
  39886. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  39887. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  39888. }
  39889. return this;
  39890. }
  39891. }
  39892. function handleVisibilityChange() {
  39893. if ( this._document.hidden === false ) this.reset();
  39894. }
  39895. /**
  39896. * This class can be used to represent points in 3D space as
  39897. * [Spherical coordinates]{@link https://en.wikipedia.org/wiki/Spherical_coordinate_system}.
  39898. */
  39899. class Spherical {
  39900. /**
  39901. * Constructs a new spherical.
  39902. *
  39903. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  39904. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  39905. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  39906. */
  39907. constructor( radius = 1, phi = 0, theta = 0 ) {
  39908. /**
  39909. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  39910. *
  39911. * @type {number}
  39912. * @default 1
  39913. */
  39914. this.radius = radius;
  39915. /**
  39916. * The polar angle in radians from the y (up) axis.
  39917. *
  39918. * @type {number}
  39919. * @default 0
  39920. */
  39921. this.phi = phi;
  39922. /**
  39923. * The equator/azimuthal angle in radians around the y (up) axis.
  39924. *
  39925. * @type {number}
  39926. * @default 0
  39927. */
  39928. this.theta = theta;
  39929. }
  39930. /**
  39931. * Sets the spherical components by copying the given values.
  39932. *
  39933. * @param {number} radius - The radius.
  39934. * @param {number} phi - The polar angle.
  39935. * @param {number} theta - The azimuthal angle.
  39936. * @return {Spherical} A reference to this spherical.
  39937. */
  39938. set( radius, phi, theta ) {
  39939. this.radius = radius;
  39940. this.phi = phi;
  39941. this.theta = theta;
  39942. return this;
  39943. }
  39944. /**
  39945. * Copies the values of the given spherical to this instance.
  39946. *
  39947. * @param {Spherical} other - The spherical to copy.
  39948. * @return {Spherical} A reference to this spherical.
  39949. */
  39950. copy( other ) {
  39951. this.radius = other.radius;
  39952. this.phi = other.phi;
  39953. this.theta = other.theta;
  39954. return this;
  39955. }
  39956. /**
  39957. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  39958. * `0.000001`.
  39959. *
  39960. * @return {Spherical} A reference to this spherical.
  39961. */
  39962. makeSafe() {
  39963. const EPS = 0.000001;
  39964. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  39965. return this;
  39966. }
  39967. /**
  39968. * Sets the spherical components from the given vector which is assumed to hold
  39969. * Cartesian coordinates.
  39970. *
  39971. * @param {Vector3} v - The vector to set.
  39972. * @return {Spherical} A reference to this spherical.
  39973. */
  39974. setFromVector3( v ) {
  39975. return this.setFromCartesianCoords( v.x, v.y, v.z );
  39976. }
  39977. /**
  39978. * Sets the spherical components from the given Cartesian coordinates.
  39979. *
  39980. * @param {number} x - The x value.
  39981. * @param {number} y - The y value.
  39982. * @param {number} z - The z value.
  39983. * @return {Spherical} A reference to this spherical.
  39984. */
  39985. setFromCartesianCoords( x, y, z ) {
  39986. this.radius = Math.sqrt( x * x + y * y + z * z );
  39987. if ( this.radius === 0 ) {
  39988. this.theta = 0;
  39989. this.phi = 0;
  39990. } else {
  39991. this.theta = Math.atan2( x, z );
  39992. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  39993. }
  39994. return this;
  39995. }
  39996. /**
  39997. * Returns a new spherical with copied values from this instance.
  39998. *
  39999. * @return {Spherical} A clone of this instance.
  40000. */
  40001. clone() {
  40002. return new this.constructor().copy( this );
  40003. }
  40004. }
  40005. /**
  40006. * This class can be used to represent points in 3D space as
  40007. * [Cylindrical coordinates]{@link https://en.wikipedia.org/wiki/Cylindrical_coordinate_system}.
  40008. */
  40009. class Cylindrical {
  40010. /**
  40011. * Constructs a new cylindrical.
  40012. *
  40013. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  40014. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40015. * @param {number} [y=0] - The height above the x-z plane.
  40016. */
  40017. constructor( radius = 1, theta = 0, y = 0 ) {
  40018. /**
  40019. * The distance from the origin to a point in the x-z plane.
  40020. *
  40021. * @type {number}
  40022. * @default 1
  40023. */
  40024. this.radius = radius;
  40025. /**
  40026. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40027. *
  40028. * @type {number}
  40029. * @default 0
  40030. */
  40031. this.theta = theta;
  40032. /**
  40033. * The height above the x-z plane.
  40034. *
  40035. * @type {number}
  40036. * @default 0
  40037. */
  40038. this.y = y;
  40039. }
  40040. /**
  40041. * Sets the cylindrical components by copying the given values.
  40042. *
  40043. * @param {number} radius - The radius.
  40044. * @param {number} theta - The theta angle.
  40045. * @param {number} y - The height value.
  40046. * @return {Cylindrical} A reference to this cylindrical.
  40047. */
  40048. set( radius, theta, y ) {
  40049. this.radius = radius;
  40050. this.theta = theta;
  40051. this.y = y;
  40052. return this;
  40053. }
  40054. /**
  40055. * Copies the values of the given cylindrical to this instance.
  40056. *
  40057. * @param {Cylindrical} other - The cylindrical to copy.
  40058. * @return {Cylindrical} A reference to this cylindrical.
  40059. */
  40060. copy( other ) {
  40061. this.radius = other.radius;
  40062. this.theta = other.theta;
  40063. this.y = other.y;
  40064. return this;
  40065. }
  40066. /**
  40067. * Sets the cylindrical components from the given vector which is assumed to hold
  40068. * Cartesian coordinates.
  40069. *
  40070. * @param {Vector3} v - The vector to set.
  40071. * @return {Cylindrical} A reference to this cylindrical.
  40072. */
  40073. setFromVector3( v ) {
  40074. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40075. }
  40076. /**
  40077. * Sets the cylindrical components from the given Cartesian coordinates.
  40078. *
  40079. * @param {number} x - The x value.
  40080. * @param {number} y - The x value.
  40081. * @param {number} z - The x value.
  40082. * @return {Cylindrical} A reference to this cylindrical.
  40083. */
  40084. setFromCartesianCoords( x, y, z ) {
  40085. this.radius = Math.sqrt( x * x + z * z );
  40086. this.theta = Math.atan2( x, z );
  40087. this.y = y;
  40088. return this;
  40089. }
  40090. /**
  40091. * Returns a new cylindrical with copied values from this instance.
  40092. *
  40093. * @return {Cylindrical} A clone of this instance.
  40094. */
  40095. clone() {
  40096. return new this.constructor().copy( this );
  40097. }
  40098. }
  40099. /**
  40100. * Represents a 2x2 matrix.
  40101. *
  40102. * A Note on Row-Major and Column-Major Ordering:
  40103. *
  40104. * The constructor and {@link Matrix2#set} method take arguments in
  40105. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  40106. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  40107. * This means that calling:
  40108. * ```js
  40109. * const m = new THREE.Matrix2();
  40110. * m.set( 11, 12,
  40111. * 21, 22 );
  40112. * ```
  40113. * will result in the elements array containing:
  40114. * ```js
  40115. * m.elements = [ 11, 21,
  40116. * 12, 22 ];
  40117. * ```
  40118. * and internally all calculations are performed using column-major ordering.
  40119. * However, as the actual ordering makes no difference mathematically and
  40120. * most people are used to thinking about matrices in row-major order, the
  40121. * three.js documentation shows matrices in row-major order. Just bear in
  40122. * mind that if you are reading the source code, you'll have to take the
  40123. * transpose of any matrices outlined here to make sense of the calculations.
  40124. */
  40125. class Matrix2 {
  40126. /**
  40127. * Constructs a new 2x2 matrix. The arguments are supposed to be
  40128. * in row-major order. If no arguments are provided, the constructor
  40129. * initializes the matrix as an identity matrix.
  40130. *
  40131. * @param {number} [n11] - 1-1 matrix element.
  40132. * @param {number} [n12] - 1-2 matrix element.
  40133. * @param {number} [n21] - 2-1 matrix element.
  40134. * @param {number} [n22] - 2-2 matrix element.
  40135. */
  40136. constructor( n11, n12, n21, n22 ) {
  40137. /**
  40138. * This flag can be used for type testing.
  40139. *
  40140. * @type {boolean}
  40141. * @readonly
  40142. * @default true
  40143. */
  40144. Matrix2.prototype.isMatrix2 = true;
  40145. /**
  40146. * A column-major list of matrix values.
  40147. *
  40148. * @type {Array<number>}
  40149. */
  40150. this.elements = [
  40151. 1, 0,
  40152. 0, 1,
  40153. ];
  40154. if ( n11 !== undefined ) {
  40155. this.set( n11, n12, n21, n22 );
  40156. }
  40157. }
  40158. /**
  40159. * Sets this matrix to the 2x2 identity matrix.
  40160. *
  40161. * @return {Matrix2} A reference to this matrix.
  40162. */
  40163. identity() {
  40164. this.set(
  40165. 1, 0,
  40166. 0, 1,
  40167. );
  40168. return this;
  40169. }
  40170. /**
  40171. * Sets the elements of the matrix from the given array.
  40172. *
  40173. * @param {Array<number>} array - The matrix elements in column-major order.
  40174. * @param {number} [offset=0] - Index of the first element in the array.
  40175. * @return {Matrix2} A reference to this matrix.
  40176. */
  40177. fromArray( array, offset = 0 ) {
  40178. for ( let i = 0; i < 4; i ++ ) {
  40179. this.elements[ i ] = array[ i + offset ];
  40180. }
  40181. return this;
  40182. }
  40183. /**
  40184. * Sets the elements of the matrix.The arguments are supposed to be
  40185. * in row-major order.
  40186. *
  40187. * @param {number} n11 - 1-1 matrix element.
  40188. * @param {number} n12 - 1-2 matrix element.
  40189. * @param {number} n21 - 2-1 matrix element.
  40190. * @param {number} n22 - 2-2 matrix element.
  40191. * @return {Matrix2} A reference to this matrix.
  40192. */
  40193. set( n11, n12, n21, n22 ) {
  40194. const te = this.elements;
  40195. te[ 0 ] = n11; te[ 2 ] = n12;
  40196. te[ 1 ] = n21; te[ 3 ] = n22;
  40197. return this;
  40198. }
  40199. }
  40200. const _vector$4 = /*@__PURE__*/ new Vector2();
  40201. /**
  40202. * Represents an axis-aligned bounding box (AABB) in 2D space.
  40203. */
  40204. class Box2 {
  40205. /**
  40206. * Constructs a new bounding box.
  40207. *
  40208. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  40209. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  40210. */
  40211. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  40212. /**
  40213. * This flag can be used for type testing.
  40214. *
  40215. * @type {boolean}
  40216. * @readonly
  40217. * @default true
  40218. */
  40219. this.isBox2 = true;
  40220. /**
  40221. * The lower boundary of the box.
  40222. *
  40223. * @type {Vector2}
  40224. */
  40225. this.min = min;
  40226. /**
  40227. * The upper boundary of the box.
  40228. *
  40229. * @type {Vector2}
  40230. */
  40231. this.max = max;
  40232. }
  40233. /**
  40234. * Sets the lower and upper boundaries of this box.
  40235. * Please note that this method only copies the values from the given objects.
  40236. *
  40237. * @param {Vector2} min - The lower boundary of the box.
  40238. * @param {Vector2} max - The upper boundary of the box.
  40239. * @return {Box2} A reference to this bounding box.
  40240. */
  40241. set( min, max ) {
  40242. this.min.copy( min );
  40243. this.max.copy( max );
  40244. return this;
  40245. }
  40246. /**
  40247. * Sets the upper and lower bounds of this box so it encloses the position data
  40248. * in the given array.
  40249. *
  40250. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  40251. * @return {Box2} A reference to this bounding box.
  40252. */
  40253. setFromPoints( points ) {
  40254. this.makeEmpty();
  40255. for ( let i = 0, il = points.length; i < il; i ++ ) {
  40256. this.expandByPoint( points[ i ] );
  40257. }
  40258. return this;
  40259. }
  40260. /**
  40261. * Centers this box on the given center vector and sets this box's width, height and
  40262. * depth to the given size values.
  40263. *
  40264. * @param {Vector2} center - The center of the box.
  40265. * @param {Vector2} size - The x and y dimensions of the box.
  40266. * @return {Box2} A reference to this bounding box.
  40267. */
  40268. setFromCenterAndSize( center, size ) {
  40269. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  40270. this.min.copy( center ).sub( halfSize );
  40271. this.max.copy( center ).add( halfSize );
  40272. return this;
  40273. }
  40274. /**
  40275. * Returns a new box with copied values from this instance.
  40276. *
  40277. * @return {Box2} A clone of this instance.
  40278. */
  40279. clone() {
  40280. return new this.constructor().copy( this );
  40281. }
  40282. /**
  40283. * Copies the values of the given box to this instance.
  40284. *
  40285. * @param {Box2} box - The box to copy.
  40286. * @return {Box2} A reference to this bounding box.
  40287. */
  40288. copy( box ) {
  40289. this.min.copy( box.min );
  40290. this.max.copy( box.max );
  40291. return this;
  40292. }
  40293. /**
  40294. * Makes this box empty which means in encloses a zero space in 2D.
  40295. *
  40296. * @return {Box2} A reference to this bounding box.
  40297. */
  40298. makeEmpty() {
  40299. this.min.x = this.min.y = + Infinity;
  40300. this.max.x = this.max.y = - Infinity;
  40301. return this;
  40302. }
  40303. /**
  40304. * Returns true if this box includes zero points within its bounds.
  40305. * Note that a box with equal lower and upper bounds still includes one
  40306. * point, the one both bounds share.
  40307. *
  40308. * @return {boolean} Whether this box is empty or not.
  40309. */
  40310. isEmpty() {
  40311. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  40312. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  40313. }
  40314. /**
  40315. * Returns the center point of this box.
  40316. *
  40317. * @param {Vector2} target - The target vector that is used to store the method's result.
  40318. * @return {Vector2} The center point.
  40319. */
  40320. getCenter( target ) {
  40321. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  40322. }
  40323. /**
  40324. * Returns the dimensions of this box.
  40325. *
  40326. * @param {Vector2} target - The target vector that is used to store the method's result.
  40327. * @return {Vector2} The size.
  40328. */
  40329. getSize( target ) {
  40330. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  40331. }
  40332. /**
  40333. * Expands the boundaries of this box to include the given point.
  40334. *
  40335. * @param {Vector2} point - The point that should be included by the bounding box.
  40336. * @return {Box2} A reference to this bounding box.
  40337. */
  40338. expandByPoint( point ) {
  40339. this.min.min( point );
  40340. this.max.max( point );
  40341. return this;
  40342. }
  40343. /**
  40344. * Expands this box equilaterally by the given vector. The width of this
  40345. * box will be expanded by the x component of the vector in both
  40346. * directions. The height of this box will be expanded by the y component of
  40347. * the vector in both directions.
  40348. *
  40349. * @param {Vector2} vector - The vector that should expand the bounding box.
  40350. * @return {Box2} A reference to this bounding box.
  40351. */
  40352. expandByVector( vector ) {
  40353. this.min.sub( vector );
  40354. this.max.add( vector );
  40355. return this;
  40356. }
  40357. /**
  40358. * Expands each dimension of the box by the given scalar. If negative, the
  40359. * dimensions of the box will be contracted.
  40360. *
  40361. * @param {number} scalar - The scalar value that should expand the bounding box.
  40362. * @return {Box2} A reference to this bounding box.
  40363. */
  40364. expandByScalar( scalar ) {
  40365. this.min.addScalar( - scalar );
  40366. this.max.addScalar( scalar );
  40367. return this;
  40368. }
  40369. /**
  40370. * Returns `true` if the given point lies within or on the boundaries of this box.
  40371. *
  40372. * @param {Vector2} point - The point to test.
  40373. * @return {boolean} Whether the bounding box contains the given point or not.
  40374. */
  40375. containsPoint( point ) {
  40376. return point.x >= this.min.x && point.x <= this.max.x &&
  40377. point.y >= this.min.y && point.y <= this.max.y;
  40378. }
  40379. /**
  40380. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  40381. * If this box and the given one are identical, this function also returns `true`.
  40382. *
  40383. * @param {Box2} box - The bounding box to test.
  40384. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  40385. */
  40386. containsBox( box ) {
  40387. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  40388. this.min.y <= box.min.y && box.max.y <= this.max.y;
  40389. }
  40390. /**
  40391. * Returns a point as a proportion of this box's width and height.
  40392. *
  40393. * @param {Vector2} point - A point in 2D space.
  40394. * @param {Vector2} target - The target vector that is used to store the method's result.
  40395. * @return {Vector2} A point as a proportion of this box's width and height.
  40396. */
  40397. getParameter( point, target ) {
  40398. // This can potentially have a divide by zero if the box
  40399. // has a size dimension of 0.
  40400. return target.set(
  40401. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  40402. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  40403. );
  40404. }
  40405. /**
  40406. * Returns `true` if the given bounding box intersects with this bounding box.
  40407. *
  40408. * @param {Box2} box - The bounding box to test.
  40409. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  40410. */
  40411. intersectsBox( box ) {
  40412. // using 4 splitting planes to rule out intersections
  40413. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  40414. box.max.y >= this.min.y && box.min.y <= this.max.y;
  40415. }
  40416. /**
  40417. * Clamps the given point within the bounds of this box.
  40418. *
  40419. * @param {Vector2} point - The point to clamp.
  40420. * @param {Vector2} target - The target vector that is used to store the method's result.
  40421. * @return {Vector2} The clamped point.
  40422. */
  40423. clampPoint( point, target ) {
  40424. return target.copy( point ).clamp( this.min, this.max );
  40425. }
  40426. /**
  40427. * Returns the euclidean distance from any edge of this box to the specified point. If
  40428. * the given point lies inside of this box, the distance will be `0`.
  40429. *
  40430. * @param {Vector2} point - The point to compute the distance to.
  40431. * @return {number} The euclidean distance.
  40432. */
  40433. distanceToPoint( point ) {
  40434. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  40435. }
  40436. /**
  40437. * Computes the intersection of this bounding box and the given one, setting the upper
  40438. * bound of this box to the lesser of the two boxes' upper bounds and the
  40439. * lower bound of this box to the greater of the two boxes' lower bounds. If
  40440. * there's no overlap, makes this box empty.
  40441. *
  40442. * @param {Box2} box - The bounding box to intersect with.
  40443. * @return {Box2} A reference to this bounding box.
  40444. */
  40445. intersect( box ) {
  40446. this.min.max( box.min );
  40447. this.max.min( box.max );
  40448. if ( this.isEmpty() ) this.makeEmpty();
  40449. return this;
  40450. }
  40451. /**
  40452. * Computes the union of this box and another and the given one, setting the upper
  40453. * bound of this box to the greater of the two boxes' upper bounds and the
  40454. * lower bound of this box to the lesser of the two boxes' lower bounds.
  40455. *
  40456. * @param {Box2} box - The bounding box that will be unioned with this instance.
  40457. * @return {Box2} A reference to this bounding box.
  40458. */
  40459. union( box ) {
  40460. this.min.min( box.min );
  40461. this.max.max( box.max );
  40462. return this;
  40463. }
  40464. /**
  40465. * Adds the given offset to both the upper and lower bounds of this bounding box,
  40466. * effectively moving it in 2D space.
  40467. *
  40468. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  40469. * @return {Box2} A reference to this bounding box.
  40470. */
  40471. translate( offset ) {
  40472. this.min.add( offset );
  40473. this.max.add( offset );
  40474. return this;
  40475. }
  40476. /**
  40477. * Returns `true` if this bounding box is equal with the given one.
  40478. *
  40479. * @param {Box2} box - The box to test for equality.
  40480. * @return {boolean} Whether this bounding box is equal with the given one.
  40481. */
  40482. equals( box ) {
  40483. return box.min.equals( this.min ) && box.max.equals( this.max );
  40484. }
  40485. }
  40486. const _startP = /*@__PURE__*/ new Vector3();
  40487. const _startEnd = /*@__PURE__*/ new Vector3();
  40488. const _d1 = /*@__PURE__*/ new Vector3();
  40489. const _d2 = /*@__PURE__*/ new Vector3();
  40490. const _r = /*@__PURE__*/ new Vector3();
  40491. const _c1 = /*@__PURE__*/ new Vector3();
  40492. const _c2 = /*@__PURE__*/ new Vector3();
  40493. /**
  40494. * An analytical line segment in 3D space represented by a start and end point.
  40495. */
  40496. class Line3 {
  40497. /**
  40498. * Constructs a new line segment.
  40499. *
  40500. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  40501. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  40502. */
  40503. constructor( start = new Vector3(), end = new Vector3() ) {
  40504. /**
  40505. * Start of the line segment.
  40506. *
  40507. * @type {Vector3}
  40508. */
  40509. this.start = start;
  40510. /**
  40511. * End of the line segment.
  40512. *
  40513. * @type {Vector3}
  40514. */
  40515. this.end = end;
  40516. }
  40517. /**
  40518. * Sets the start and end values by copying the given vectors.
  40519. *
  40520. * @param {Vector3} start - The start point.
  40521. * @param {Vector3} end - The end point.
  40522. * @return {Line3} A reference to this line segment.
  40523. */
  40524. set( start, end ) {
  40525. this.start.copy( start );
  40526. this.end.copy( end );
  40527. return this;
  40528. }
  40529. /**
  40530. * Copies the values of the given line segment to this instance.
  40531. *
  40532. * @param {Line3} line - The line segment to copy.
  40533. * @return {Line3} A reference to this line segment.
  40534. */
  40535. copy( line ) {
  40536. this.start.copy( line.start );
  40537. this.end.copy( line.end );
  40538. return this;
  40539. }
  40540. /**
  40541. * Returns the center of the line segment.
  40542. *
  40543. * @param {Vector3} target - The target vector that is used to store the method's result.
  40544. * @return {Vector3} The center point.
  40545. */
  40546. getCenter( target ) {
  40547. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  40548. }
  40549. /**
  40550. * Returns the delta vector of the line segment's start and end point.
  40551. *
  40552. * @param {Vector3} target - The target vector that is used to store the method's result.
  40553. * @return {Vector3} The delta vector.
  40554. */
  40555. delta( target ) {
  40556. return target.subVectors( this.end, this.start );
  40557. }
  40558. /**
  40559. * Returns the squared Euclidean distance between the line' start and end point.
  40560. *
  40561. * @return {number} The squared Euclidean distance.
  40562. */
  40563. distanceSq() {
  40564. return this.start.distanceToSquared( this.end );
  40565. }
  40566. /**
  40567. * Returns the Euclidean distance between the line' start and end point.
  40568. *
  40569. * @return {number} The Euclidean distance.
  40570. */
  40571. distance() {
  40572. return this.start.distanceTo( this.end );
  40573. }
  40574. /**
  40575. * Returns a vector at a certain position along the line segment.
  40576. *
  40577. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  40578. * @param {Vector3} target - The target vector that is used to store the method's result.
  40579. * @return {Vector3} The delta vector.
  40580. */
  40581. at( t, target ) {
  40582. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40583. }
  40584. /**
  40585. * Returns a point parameter based on the closest point as projected on the line segment.
  40586. *
  40587. * @param {Vector3} point - The point for which to return a point parameter.
  40588. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40589. * @return {number} The point parameter.
  40590. */
  40591. closestPointToPointParameter( point, clampToLine ) {
  40592. _startP.subVectors( point, this.start );
  40593. _startEnd.subVectors( this.end, this.start );
  40594. const startEnd2 = _startEnd.dot( _startEnd );
  40595. const startEnd_startP = _startEnd.dot( _startP );
  40596. let t = startEnd_startP / startEnd2;
  40597. if ( clampToLine ) {
  40598. t = clamp( t, 0, 1 );
  40599. }
  40600. return t;
  40601. }
  40602. /**
  40603. * Returns the closest point on the line for a given point.
  40604. *
  40605. * @param {Vector3} point - The point to compute the closest point on the line for.
  40606. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40607. * @param {Vector3} target - The target vector that is used to store the method's result.
  40608. * @return {Vector3} The closest point on the line.
  40609. */
  40610. closestPointToPoint( point, clampToLine, target ) {
  40611. const t = this.closestPointToPointParameter( point, clampToLine );
  40612. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40613. }
  40614. /**
  40615. * Returns the closest squared distance between this line segment and the given one.
  40616. *
  40617. * @param {Line3} line - The line segment to compute the closest squared distance to.
  40618. * @param {Vector3} [c1] - The closest point on this line segment.
  40619. * @param {Vector3} [c2] - The closest point on the given line segment.
  40620. * @return {number} The squared distance between this line segment and the given one.
  40621. */
  40622. distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) {
  40623. // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9
  40624. // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
  40625. // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
  40626. // distance between between S1(s) and S2(t)
  40627. const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length
  40628. let s, t;
  40629. const p1 = this.start;
  40630. const p2 = line.start;
  40631. const q1 = this.end;
  40632. const q2 = line.end;
  40633. _d1.subVectors( q1, p1 ); // Direction vector of segment S1
  40634. _d2.subVectors( q2, p2 ); // Direction vector of segment S2
  40635. _r.subVectors( p1, p2 );
  40636. const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative
  40637. const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative
  40638. const f = _d2.dot( _r );
  40639. // Check if either or both segments degenerate into points
  40640. if ( a <= EPSILON && e <= EPSILON ) {
  40641. // Both segments degenerate into points
  40642. c1.copy( p1 );
  40643. c2.copy( p2 );
  40644. c1.sub( c2 );
  40645. return c1.dot( c1 );
  40646. }
  40647. if ( a <= EPSILON ) {
  40648. // First segment degenerates into a point
  40649. s = 0;
  40650. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  40651. t = clamp( t, 0, 1 );
  40652. } else {
  40653. const c = _d1.dot( _r );
  40654. if ( e <= EPSILON ) {
  40655. // Second segment degenerates into a point
  40656. t = 0;
  40657. s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a
  40658. } else {
  40659. // The general nondegenerate case starts here
  40660. const b = _d1.dot( _d2 );
  40661. const denom = a * e - b * b; // Always nonnegative
  40662. // If segments not parallel, compute closest point on L1 to L2 and
  40663. // clamp to segment S1. Else pick arbitrary s (here 0)
  40664. if ( denom !== 0 ) {
  40665. s = clamp( ( b * f - c * e ) / denom, 0, 1 );
  40666. } else {
  40667. s = 0;
  40668. }
  40669. // Compute point on L2 closest to S1(s) using
  40670. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  40671. t = ( b * s + f ) / e;
  40672. // If t in [0,1] done. Else clamp t, recompute s for the new value
  40673. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  40674. // and clamp s to [0, 1]
  40675. if ( t < 0 ) {
  40676. t = 0.;
  40677. s = clamp( - c / a, 0, 1 );
  40678. } else if ( t > 1 ) {
  40679. t = 1;
  40680. s = clamp( ( b - c ) / a, 0, 1 );
  40681. }
  40682. }
  40683. }
  40684. c1.copy( p1 ).add( _d1.multiplyScalar( s ) );
  40685. c2.copy( p2 ).add( _d2.multiplyScalar( t ) );
  40686. c1.sub( c2 );
  40687. return c1.dot( c1 );
  40688. }
  40689. /**
  40690. * Applies a 4x4 transformation matrix to this line segment.
  40691. *
  40692. * @param {Matrix4} matrix - The transformation matrix.
  40693. * @return {Line3} A reference to this line segment.
  40694. */
  40695. applyMatrix4( matrix ) {
  40696. this.start.applyMatrix4( matrix );
  40697. this.end.applyMatrix4( matrix );
  40698. return this;
  40699. }
  40700. /**
  40701. * Returns `true` if this line segment is equal with the given one.
  40702. *
  40703. * @param {Line3} line - The line segment to test for equality.
  40704. * @return {boolean} Whether this line segment is equal with the given one.
  40705. */
  40706. equals( line ) {
  40707. return line.start.equals( this.start ) && line.end.equals( this.end );
  40708. }
  40709. /**
  40710. * Returns a new line segment with copied values from this instance.
  40711. *
  40712. * @return {Line3} A clone of this instance.
  40713. */
  40714. clone() {
  40715. return new this.constructor().copy( this );
  40716. }
  40717. }
  40718. const _vector$3 = /*@__PURE__*/ new Vector3();
  40719. /**
  40720. * This displays a cone shaped helper object for a {@link SpotLight}.
  40721. *
  40722. * ```js
  40723. * const spotLight = new THREE.SpotLight( 0xffffff );
  40724. * spotLight.position.set( 10, 10, 10 );
  40725. * scene.add( spotLight );
  40726. *
  40727. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  40728. * scene.add( spotLightHelper );
  40729. * ```
  40730. *
  40731. * @augments Object3D
  40732. */
  40733. class SpotLightHelper extends Object3D {
  40734. /**
  40735. * Constructs a new spot light helper.
  40736. *
  40737. * @param {HemisphereLight} light - The light to be visualized.
  40738. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40739. * the color of the light.
  40740. */
  40741. constructor( light, color ) {
  40742. super();
  40743. /**
  40744. * The light being visualized.
  40745. *
  40746. * @type {SpotLight}
  40747. */
  40748. this.light = light;
  40749. this.matrixAutoUpdate = false;
  40750. /**
  40751. * The color parameter passed in the constructor.
  40752. * If not set, the helper will take the color of the light.
  40753. *
  40754. * @type {number|Color|string}
  40755. */
  40756. this.color = color;
  40757. this.type = 'SpotLightHelper';
  40758. const geometry = new BufferGeometry();
  40759. const positions = [
  40760. 0, 0, 0, 0, 0, 1,
  40761. 0, 0, 0, 1, 0, 1,
  40762. 0, 0, 0, -1, 0, 1,
  40763. 0, 0, 0, 0, 1, 1,
  40764. 0, 0, 0, 0, -1, 1
  40765. ];
  40766. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  40767. const p1 = ( i / l ) * Math.PI * 2;
  40768. const p2 = ( j / l ) * Math.PI * 2;
  40769. positions.push(
  40770. Math.cos( p1 ), Math.sin( p1 ), 1,
  40771. Math.cos( p2 ), Math.sin( p2 ), 1
  40772. );
  40773. }
  40774. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  40775. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  40776. this.cone = new LineSegments( geometry, material );
  40777. this.add( this.cone );
  40778. this.update();
  40779. }
  40780. /**
  40781. * Frees the GPU-related resources allocated by this instance. Call this
  40782. * method whenever this instance is no longer used in your app.
  40783. */
  40784. dispose() {
  40785. this.cone.geometry.dispose();
  40786. this.cone.material.dispose();
  40787. }
  40788. /**
  40789. * Updates the helper to match the position and direction of the
  40790. * light being visualized.
  40791. */
  40792. update() {
  40793. this.light.updateWorldMatrix( true, false );
  40794. this.light.target.updateWorldMatrix( true, false );
  40795. // update the local matrix based on the parent and light target transforms
  40796. if ( this.parent ) {
  40797. this.parent.updateWorldMatrix( true );
  40798. this.matrix
  40799. .copy( this.parent.matrixWorld )
  40800. .invert()
  40801. .multiply( this.light.matrixWorld );
  40802. } else {
  40803. this.matrix.copy( this.light.matrixWorld );
  40804. }
  40805. this.matrixWorld.copy( this.light.matrixWorld );
  40806. const coneLength = this.light.distance ? this.light.distance : 1000;
  40807. const coneWidth = coneLength * Math.tan( this.light.angle );
  40808. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  40809. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  40810. this.cone.lookAt( _vector$3 );
  40811. if ( this.color !== undefined ) {
  40812. this.cone.material.color.set( this.color );
  40813. } else {
  40814. this.cone.material.color.copy( this.light.color );
  40815. }
  40816. }
  40817. }
  40818. const _vector$2 = /*@__PURE__*/ new Vector3();
  40819. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  40820. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  40821. /**
  40822. * A helper object to assist with visualizing a {@link Skeleton}.
  40823. *
  40824. * ```js
  40825. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  40826. * scene.add( helper );
  40827. * ```
  40828. *
  40829. * @augments LineSegments
  40830. */
  40831. class SkeletonHelper extends LineSegments {
  40832. /**
  40833. * Constructs a new skeleton helper.
  40834. *
  40835. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  40836. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  40837. */
  40838. constructor( object ) {
  40839. const bones = getBoneList( object );
  40840. const geometry = new BufferGeometry();
  40841. const vertices = [];
  40842. const colors = [];
  40843. for ( let i = 0; i < bones.length; i ++ ) {
  40844. const bone = bones[ i ];
  40845. if ( bone.parent && bone.parent.isBone ) {
  40846. vertices.push( 0, 0, 0 );
  40847. vertices.push( 0, 0, 0 );
  40848. colors.push( 0, 0, 0 );
  40849. colors.push( 0, 0, 0 );
  40850. }
  40851. }
  40852. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40853. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  40854. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  40855. super( geometry, material );
  40856. /**
  40857. * This flag can be used for type testing.
  40858. *
  40859. * @type {boolean}
  40860. * @readonly
  40861. * @default true
  40862. */
  40863. this.isSkeletonHelper = true;
  40864. this.type = 'SkeletonHelper';
  40865. /**
  40866. * The object being visualized.
  40867. *
  40868. * @type {Object3D}
  40869. */
  40870. this.root = object;
  40871. /**
  40872. * The list of bones that the helper visualizes.
  40873. *
  40874. * @type {Array<Bone>}
  40875. */
  40876. this.bones = bones;
  40877. this.matrix = object.matrixWorld;
  40878. this.matrixAutoUpdate = false;
  40879. // colors
  40880. const color1 = new Color( 0x0000ff );
  40881. const color2 = new Color( 0x00ff00 );
  40882. this.setColors( color1, color2 );
  40883. }
  40884. updateMatrixWorld( force ) {
  40885. const bones = this.bones;
  40886. const geometry = this.geometry;
  40887. const position = geometry.getAttribute( 'position' );
  40888. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  40889. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  40890. const bone = bones[ i ];
  40891. if ( bone.parent && bone.parent.isBone ) {
  40892. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  40893. _vector$2.setFromMatrixPosition( _boneMatrix );
  40894. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  40895. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  40896. _vector$2.setFromMatrixPosition( _boneMatrix );
  40897. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  40898. j += 2;
  40899. }
  40900. }
  40901. geometry.getAttribute( 'position' ).needsUpdate = true;
  40902. super.updateMatrixWorld( force );
  40903. }
  40904. /**
  40905. * Defines the colors of the helper.
  40906. *
  40907. * @param {Color} color1 - The first line color for each bone.
  40908. * @param {Color} color2 - The second line color for each bone.
  40909. * @return {SkeletonHelper} A reference to this helper.
  40910. */
  40911. setColors( color1, color2 ) {
  40912. const geometry = this.geometry;
  40913. const colorAttribute = geometry.getAttribute( 'color' );
  40914. for ( let i = 0; i < colorAttribute.count; i += 2 ) {
  40915. colorAttribute.setXYZ( i, color1.r, color1.g, color1.b );
  40916. colorAttribute.setXYZ( i + 1, color2.r, color2.g, color2.b );
  40917. }
  40918. colorAttribute.needsUpdate = true;
  40919. return this;
  40920. }
  40921. /**
  40922. * Frees the GPU-related resources allocated by this instance. Call this
  40923. * method whenever this instance is no longer used in your app.
  40924. */
  40925. dispose() {
  40926. this.geometry.dispose();
  40927. this.material.dispose();
  40928. }
  40929. }
  40930. function getBoneList( object ) {
  40931. const boneList = [];
  40932. if ( object.isBone === true ) {
  40933. boneList.push( object );
  40934. }
  40935. for ( let i = 0; i < object.children.length; i ++ ) {
  40936. boneList.push( ...getBoneList( object.children[ i ] ) );
  40937. }
  40938. return boneList;
  40939. }
  40940. /**
  40941. * This displays a helper object consisting of a spherical mesh for
  40942. * visualizing an instance of {@link PointLight}.
  40943. *
  40944. * ```js
  40945. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  40946. * pointLight.position.set( 10, 10, 10 );
  40947. * scene.add( pointLight );
  40948. *
  40949. * const sphereSize = 1;
  40950. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  40951. * scene.add( pointLightHelper );
  40952. * ```
  40953. *
  40954. * @augments Mesh
  40955. */
  40956. class PointLightHelper extends Mesh {
  40957. /**
  40958. * Constructs a new point light helper.
  40959. *
  40960. * @param {PointLight} light - The light to be visualized.
  40961. * @param {number} [sphereSize=1] - The size of the sphere helper.
  40962. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40963. * the color of the light.
  40964. */
  40965. constructor( light, sphereSize, color ) {
  40966. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  40967. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  40968. super( geometry, material );
  40969. /**
  40970. * The light being visualized.
  40971. *
  40972. * @type {HemisphereLight}
  40973. */
  40974. this.light = light;
  40975. /**
  40976. * The color parameter passed in the constructor.
  40977. * If not set, the helper will take the color of the light.
  40978. *
  40979. * @type {number|Color|string}
  40980. */
  40981. this.color = color;
  40982. this.type = 'PointLightHelper';
  40983. this.matrix = this.light.matrixWorld;
  40984. this.matrixAutoUpdate = false;
  40985. this.update();
  40986. /*
  40987. // TODO: delete this comment?
  40988. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  40989. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  40990. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  40991. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  40992. const d = light.distance;
  40993. if ( d === 0.0 ) {
  40994. this.lightDistance.visible = false;
  40995. } else {
  40996. this.lightDistance.scale.set( d, d, d );
  40997. }
  40998. this.add( this.lightDistance );
  40999. */
  41000. }
  41001. /**
  41002. * Frees the GPU-related resources allocated by this instance. Call this
  41003. * method whenever this instance is no longer used in your app.
  41004. */
  41005. dispose() {
  41006. this.geometry.dispose();
  41007. this.material.dispose();
  41008. }
  41009. /**
  41010. * Updates the helper to match the position of the
  41011. * light being visualized.
  41012. */
  41013. update() {
  41014. this.light.updateWorldMatrix( true, false );
  41015. if ( this.color !== undefined ) {
  41016. this.material.color.set( this.color );
  41017. } else {
  41018. this.material.color.copy( this.light.color );
  41019. }
  41020. /*
  41021. const d = this.light.distance;
  41022. if ( d === 0.0 ) {
  41023. this.lightDistance.visible = false;
  41024. } else {
  41025. this.lightDistance.visible = true;
  41026. this.lightDistance.scale.set( d, d, d );
  41027. }
  41028. */
  41029. }
  41030. }
  41031. const _vector$1 = /*@__PURE__*/ new Vector3();
  41032. const _color1 = /*@__PURE__*/ new Color();
  41033. const _color2 = /*@__PURE__*/ new Color();
  41034. /**
  41035. * Creates a visual aid consisting of a spherical mesh for a
  41036. * given {@link HemisphereLight}.
  41037. *
  41038. * ```js
  41039. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  41040. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  41041. * scene.add( helper );
  41042. * ```
  41043. *
  41044. * @augments Object3D
  41045. */
  41046. class HemisphereLightHelper extends Object3D {
  41047. /**
  41048. * Constructs a new hemisphere light helper.
  41049. *
  41050. * @param {HemisphereLight} light - The light to be visualized.
  41051. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  41052. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41053. * the color of the light.
  41054. */
  41055. constructor( light, size, color ) {
  41056. super();
  41057. /**
  41058. * The light being visualized.
  41059. *
  41060. * @type {HemisphereLight}
  41061. */
  41062. this.light = light;
  41063. this.matrix = light.matrixWorld;
  41064. this.matrixAutoUpdate = false;
  41065. /**
  41066. * The color parameter passed in the constructor.
  41067. * If not set, the helper will take the color of the light.
  41068. *
  41069. * @type {number|Color|string}
  41070. */
  41071. this.color = color;
  41072. this.type = 'HemisphereLightHelper';
  41073. const geometry = new OctahedronGeometry( size );
  41074. geometry.rotateY( Math.PI * 0.5 );
  41075. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41076. if ( this.color === undefined ) this.material.vertexColors = true;
  41077. const position = geometry.getAttribute( 'position' );
  41078. const colors = new Float32Array( position.count * 3 );
  41079. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  41080. this.add( new Mesh( geometry, this.material ) );
  41081. this.update();
  41082. }
  41083. /**
  41084. * Frees the GPU-related resources allocated by this instance. Call this
  41085. * method whenever this instance is no longer used in your app.
  41086. */
  41087. dispose() {
  41088. this.children[ 0 ].geometry.dispose();
  41089. this.children[ 0 ].material.dispose();
  41090. }
  41091. /**
  41092. * Updates the helper to match the position and direction of the
  41093. * light being visualized.
  41094. */
  41095. update() {
  41096. const mesh = this.children[ 0 ];
  41097. if ( this.color !== undefined ) {
  41098. this.material.color.set( this.color );
  41099. } else {
  41100. const colors = mesh.geometry.getAttribute( 'color' );
  41101. _color1.copy( this.light.color );
  41102. _color2.copy( this.light.groundColor );
  41103. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  41104. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  41105. colors.setXYZ( i, color.r, color.g, color.b );
  41106. }
  41107. colors.needsUpdate = true;
  41108. }
  41109. this.light.updateWorldMatrix( true, false );
  41110. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  41111. }
  41112. }
  41113. /**
  41114. * The helper is an object to define grids. Grids are two-dimensional
  41115. * arrays of lines.
  41116. *
  41117. * ```js
  41118. * const size = 10;
  41119. * const divisions = 10;
  41120. *
  41121. * const gridHelper = new THREE.GridHelper( size, divisions );
  41122. * scene.add( gridHelper );
  41123. * ```
  41124. *
  41125. * @augments LineSegments
  41126. */
  41127. class GridHelper extends LineSegments {
  41128. /**
  41129. * Constructs a new grid helper.
  41130. *
  41131. * @param {number} [size=10] - The size of the grid.
  41132. * @param {number} [divisions=10] - The number of divisions across the grid.
  41133. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  41134. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  41135. */
  41136. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  41137. color1 = new Color( color1 );
  41138. color2 = new Color( color2 );
  41139. const center = divisions / 2;
  41140. const step = size / divisions;
  41141. const halfSize = size / 2;
  41142. const vertices = [], colors = [];
  41143. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  41144. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  41145. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  41146. const color = i === center ? color1 : color2;
  41147. color.toArray( colors, j ); j += 3;
  41148. color.toArray( colors, j ); j += 3;
  41149. color.toArray( colors, j ); j += 3;
  41150. color.toArray( colors, j ); j += 3;
  41151. }
  41152. const geometry = new BufferGeometry();
  41153. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41154. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41155. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41156. super( geometry, material );
  41157. this.type = 'GridHelper';
  41158. }
  41159. /**
  41160. * Frees the GPU-related resources allocated by this instance. Call this
  41161. * method whenever this instance is no longer used in your app.
  41162. */
  41163. dispose() {
  41164. this.geometry.dispose();
  41165. this.material.dispose();
  41166. }
  41167. }
  41168. /**
  41169. * This helper is an object to define polar grids. Grids are
  41170. * two-dimensional arrays of lines.
  41171. *
  41172. * ```js
  41173. * const radius = 10;
  41174. * const sectors = 16;
  41175. * const rings = 8;
  41176. * const divisions = 64;
  41177. *
  41178. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  41179. * scene.add( helper );
  41180. * ```
  41181. *
  41182. * @augments LineSegments
  41183. */
  41184. class PolarGridHelper extends LineSegments {
  41185. /**
  41186. * Constructs a new polar grid helper.
  41187. *
  41188. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  41189. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  41190. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  41191. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  41192. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  41193. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  41194. */
  41195. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  41196. color1 = new Color( color1 );
  41197. color2 = new Color( color2 );
  41198. const vertices = [];
  41199. const colors = [];
  41200. // create the sectors
  41201. if ( sectors > 1 ) {
  41202. for ( let i = 0; i < sectors; i ++ ) {
  41203. const v = ( i / sectors ) * ( Math.PI * 2 );
  41204. const x = Math.sin( v ) * radius;
  41205. const z = Math.cos( v ) * radius;
  41206. vertices.push( 0, 0, 0 );
  41207. vertices.push( x, 0, z );
  41208. const color = ( i & 1 ) ? color1 : color2;
  41209. colors.push( color.r, color.g, color.b );
  41210. colors.push( color.r, color.g, color.b );
  41211. }
  41212. }
  41213. // create the rings
  41214. for ( let i = 0; i < rings; i ++ ) {
  41215. const color = ( i & 1 ) ? color1 : color2;
  41216. const r = radius - ( radius / rings * i );
  41217. for ( let j = 0; j < divisions; j ++ ) {
  41218. // first vertex
  41219. let v = ( j / divisions ) * ( Math.PI * 2 );
  41220. let x = Math.sin( v ) * r;
  41221. let z = Math.cos( v ) * r;
  41222. vertices.push( x, 0, z );
  41223. colors.push( color.r, color.g, color.b );
  41224. // second vertex
  41225. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  41226. x = Math.sin( v ) * r;
  41227. z = Math.cos( v ) * r;
  41228. vertices.push( x, 0, z );
  41229. colors.push( color.r, color.g, color.b );
  41230. }
  41231. }
  41232. const geometry = new BufferGeometry();
  41233. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41234. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41235. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41236. super( geometry, material );
  41237. this.type = 'PolarGridHelper';
  41238. }
  41239. /**
  41240. * Frees the GPU-related resources allocated by this instance. Call this
  41241. * method whenever this instance is no longer used in your app.
  41242. */
  41243. dispose() {
  41244. this.geometry.dispose();
  41245. this.material.dispose();
  41246. }
  41247. }
  41248. const _v1 = /*@__PURE__*/ new Vector3();
  41249. const _v2 = /*@__PURE__*/ new Vector3();
  41250. const _v3 = /*@__PURE__*/ new Vector3();
  41251. /**
  41252. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  41253. * effect on the scene. This consists of plane and a line representing the
  41254. * light's position and direction.
  41255. *
  41256. * ```js
  41257. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  41258. * scene.add( light );
  41259. *
  41260. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  41261. * scene.add( helper );
  41262. * ```
  41263. *
  41264. * @augments Object3D
  41265. */
  41266. class DirectionalLightHelper extends Object3D {
  41267. /**
  41268. * Constructs a new directional light helper.
  41269. *
  41270. * @param {DirectionalLight} light - The light to be visualized.
  41271. * @param {number} [size=1] - The dimensions of the plane.
  41272. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41273. * the color of the light.
  41274. */
  41275. constructor( light, size, color ) {
  41276. super();
  41277. /**
  41278. * The light being visualized.
  41279. *
  41280. * @type {DirectionalLight}
  41281. */
  41282. this.light = light;
  41283. this.matrix = light.matrixWorld;
  41284. this.matrixAutoUpdate = false;
  41285. /**
  41286. * The color parameter passed in the constructor.
  41287. * If not set, the helper will take the color of the light.
  41288. *
  41289. * @type {number|Color|string}
  41290. */
  41291. this.color = color;
  41292. this.type = 'DirectionalLightHelper';
  41293. if ( size === undefined ) size = 1;
  41294. let geometry = new BufferGeometry();
  41295. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  41296. - size, size, 0,
  41297. size, size, 0,
  41298. size, - size, 0,
  41299. - size, - size, 0,
  41300. - size, size, 0
  41301. ], 3 ) );
  41302. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41303. /**
  41304. * Contains the line showing the location of the directional light.
  41305. *
  41306. * @type {Line}
  41307. */
  41308. this.lightPlane = new Line( geometry, material );
  41309. this.add( this.lightPlane );
  41310. geometry = new BufferGeometry();
  41311. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  41312. /**
  41313. * Represents the target line of the directional light.
  41314. *
  41315. * @type {Line}
  41316. */
  41317. this.targetLine = new Line( geometry, material );
  41318. this.add( this.targetLine );
  41319. this.update();
  41320. }
  41321. /**
  41322. * Frees the GPU-related resources allocated by this instance. Call this
  41323. * method whenever this instance is no longer used in your app.
  41324. */
  41325. dispose() {
  41326. this.lightPlane.geometry.dispose();
  41327. this.lightPlane.material.dispose();
  41328. this.targetLine.geometry.dispose();
  41329. this.targetLine.material.dispose();
  41330. }
  41331. /**
  41332. * Updates the helper to match the position and direction of the
  41333. * light being visualized.
  41334. */
  41335. update() {
  41336. this.light.updateWorldMatrix( true, false );
  41337. this.light.target.updateWorldMatrix( true, false );
  41338. _v1.setFromMatrixPosition( this.light.matrixWorld );
  41339. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  41340. _v3.subVectors( _v2, _v1 );
  41341. this.lightPlane.lookAt( _v2 );
  41342. if ( this.color !== undefined ) {
  41343. this.lightPlane.material.color.set( this.color );
  41344. this.targetLine.material.color.set( this.color );
  41345. } else {
  41346. this.lightPlane.material.color.copy( this.light.color );
  41347. this.targetLine.material.color.copy( this.light.color );
  41348. }
  41349. this.targetLine.lookAt( _v2 );
  41350. this.targetLine.scale.z = _v3.length();
  41351. }
  41352. }
  41353. const _vector = /*@__PURE__*/ new Vector3();
  41354. const _camera = /*@__PURE__*/ new Camera();
  41355. /**
  41356. * This helps with visualizing what a camera contains in its frustum. It
  41357. * visualizes the frustum of a camera using a line segments.
  41358. *
  41359. * Based on frustum visualization in [lightgl.js shadowmap example]{@link https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html}.
  41360. *
  41361. * `CameraHelper` must be a child of the scene.
  41362. *
  41363. * ```js
  41364. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  41365. * const helper = new THREE.CameraHelper( camera );
  41366. * scene.add( helper );
  41367. * ```
  41368. *
  41369. * @augments LineSegments
  41370. */
  41371. class CameraHelper extends LineSegments {
  41372. /**
  41373. * Constructs a new arrow helper.
  41374. *
  41375. * @param {Camera} camera - The camera to visualize.
  41376. */
  41377. constructor( camera ) {
  41378. const geometry = new BufferGeometry();
  41379. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  41380. const vertices = [];
  41381. const colors = [];
  41382. const pointMap = {};
  41383. // near
  41384. addLine( 'n1', 'n2' );
  41385. addLine( 'n2', 'n4' );
  41386. addLine( 'n4', 'n3' );
  41387. addLine( 'n3', 'n1' );
  41388. // far
  41389. addLine( 'f1', 'f2' );
  41390. addLine( 'f2', 'f4' );
  41391. addLine( 'f4', 'f3' );
  41392. addLine( 'f3', 'f1' );
  41393. // sides
  41394. addLine( 'n1', 'f1' );
  41395. addLine( 'n2', 'f2' );
  41396. addLine( 'n3', 'f3' );
  41397. addLine( 'n4', 'f4' );
  41398. // cone
  41399. addLine( 'p', 'n1' );
  41400. addLine( 'p', 'n2' );
  41401. addLine( 'p', 'n3' );
  41402. addLine( 'p', 'n4' );
  41403. // up
  41404. addLine( 'u1', 'u2' );
  41405. addLine( 'u2', 'u3' );
  41406. addLine( 'u3', 'u1' );
  41407. // target
  41408. addLine( 'c', 't' );
  41409. addLine( 'p', 'c' );
  41410. // cross
  41411. addLine( 'cn1', 'cn2' );
  41412. addLine( 'cn3', 'cn4' );
  41413. addLine( 'cf1', 'cf2' );
  41414. addLine( 'cf3', 'cf4' );
  41415. function addLine( a, b ) {
  41416. addPoint( a );
  41417. addPoint( b );
  41418. }
  41419. function addPoint( id ) {
  41420. vertices.push( 0, 0, 0 );
  41421. colors.push( 0, 0, 0 );
  41422. if ( pointMap[ id ] === undefined ) {
  41423. pointMap[ id ] = [];
  41424. }
  41425. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  41426. }
  41427. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41428. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41429. super( geometry, material );
  41430. this.type = 'CameraHelper';
  41431. /**
  41432. * The camera being visualized.
  41433. *
  41434. * @type {Camera}
  41435. */
  41436. this.camera = camera;
  41437. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  41438. this.matrix = camera.matrixWorld;
  41439. this.matrixAutoUpdate = false;
  41440. /**
  41441. * This contains the points used to visualize the camera.
  41442. *
  41443. * @type {Object<string,Array<number>>}
  41444. */
  41445. this.pointMap = pointMap;
  41446. this.update();
  41447. // colors
  41448. const colorFrustum = new Color( 0xffaa00 );
  41449. const colorCone = new Color( 0xff0000 );
  41450. const colorUp = new Color( 0x00aaff );
  41451. const colorTarget = new Color( 0xffffff );
  41452. const colorCross = new Color( 0x333333 );
  41453. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  41454. }
  41455. /**
  41456. * Defines the colors of the helper.
  41457. *
  41458. * @param {Color} frustum - The frustum line color.
  41459. * @param {Color} cone - The cone line color.
  41460. * @param {Color} up - The up line color.
  41461. * @param {Color} target - The target line color.
  41462. * @param {Color} cross - The cross line color.
  41463. * @return {CameraHelper} A reference to this helper.
  41464. */
  41465. setColors( frustum, cone, up, target, cross ) {
  41466. const geometry = this.geometry;
  41467. const colorAttribute = geometry.getAttribute( 'color' );
  41468. // near
  41469. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  41470. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  41471. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  41472. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  41473. // far
  41474. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  41475. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  41476. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  41477. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  41478. // sides
  41479. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  41480. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  41481. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  41482. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  41483. // cone
  41484. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  41485. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  41486. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  41487. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  41488. // up
  41489. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  41490. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  41491. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  41492. // target
  41493. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  41494. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  41495. // cross
  41496. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  41497. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  41498. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  41499. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  41500. colorAttribute.needsUpdate = true;
  41501. return this;
  41502. }
  41503. /**
  41504. * Updates the helper based on the projection matrix of the camera.
  41505. */
  41506. update() {
  41507. const geometry = this.geometry;
  41508. const pointMap = this.pointMap;
  41509. const w = 1, h = 1;
  41510. let nearZ, farZ;
  41511. // we need just camera projection matrix inverse
  41512. // world matrix must be identity
  41513. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  41514. // Adjust z values based on coordinate system
  41515. if ( this.camera.reversedDepth === true ) {
  41516. nearZ = 1;
  41517. farZ = 0;
  41518. } else {
  41519. if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) {
  41520. nearZ = -1;
  41521. farZ = 1;
  41522. } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) {
  41523. nearZ = 0;
  41524. farZ = 1;
  41525. } else {
  41526. throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem );
  41527. }
  41528. }
  41529. // center / target
  41530. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  41531. setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ );
  41532. // near
  41533. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  41534. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  41535. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  41536. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  41537. // far
  41538. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ );
  41539. setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ );
  41540. setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ );
  41541. setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ );
  41542. // up
  41543. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  41544. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  41545. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  41546. // cross
  41547. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ );
  41548. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ );
  41549. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ );
  41550. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ );
  41551. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  41552. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  41553. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  41554. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  41555. geometry.getAttribute( 'position' ).needsUpdate = true;
  41556. }
  41557. /**
  41558. * Frees the GPU-related resources allocated by this instance. Call this
  41559. * method whenever this instance is no longer used in your app.
  41560. */
  41561. dispose() {
  41562. this.geometry.dispose();
  41563. this.material.dispose();
  41564. }
  41565. }
  41566. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  41567. _vector.set( x, y, z ).unproject( camera );
  41568. const points = pointMap[ point ];
  41569. if ( points !== undefined ) {
  41570. const position = geometry.getAttribute( 'position' );
  41571. for ( let i = 0, l = points.length; i < l; i ++ ) {
  41572. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  41573. }
  41574. }
  41575. }
  41576. const _box = /*@__PURE__*/ new Box3();
  41577. /**
  41578. * Helper object to graphically show the world-axis-aligned bounding box
  41579. * around an object. The actual bounding box is handled with {@link Box3},
  41580. * this is just a visual helper for debugging. It can be automatically
  41581. * resized with {@link BoxHelper#update} when the object it's created from
  41582. * is transformed. Note that the object must have a geometry for this to work,
  41583. * so it won't work with sprites.
  41584. *
  41585. * ```js
  41586. * const sphere = new THREE.SphereGeometry();
  41587. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  41588. * const box = new THREE.BoxHelper( object, 0xffff00 );
  41589. * scene.add( box );
  41590. * ```
  41591. *
  41592. * @augments LineSegments
  41593. */
  41594. class BoxHelper extends LineSegments {
  41595. /**
  41596. * Constructs a new box helper.
  41597. *
  41598. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  41599. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41600. */
  41601. constructor( object, color = 0xffff00 ) {
  41602. 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 ] );
  41603. const positions = new Float32Array( 8 * 3 );
  41604. const geometry = new BufferGeometry();
  41605. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41606. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  41607. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41608. /**
  41609. * The 3D object being visualized.
  41610. *
  41611. * @type {Object3D}
  41612. */
  41613. this.object = object;
  41614. this.type = 'BoxHelper';
  41615. this.matrixAutoUpdate = false;
  41616. this.update();
  41617. }
  41618. /**
  41619. * Updates the helper's geometry to match the dimensions of the object,
  41620. * including any children.
  41621. */
  41622. update() {
  41623. if ( this.object !== undefined ) {
  41624. _box.setFromObject( this.object );
  41625. }
  41626. if ( _box.isEmpty() ) return;
  41627. const min = _box.min;
  41628. const max = _box.max;
  41629. /*
  41630. 5____4
  41631. 1/___0/|
  41632. | 6__|_7
  41633. 2/___3/
  41634. 0: max.x, max.y, max.z
  41635. 1: min.x, max.y, max.z
  41636. 2: min.x, min.y, max.z
  41637. 3: max.x, min.y, max.z
  41638. 4: max.x, max.y, min.z
  41639. 5: min.x, max.y, min.z
  41640. 6: min.x, min.y, min.z
  41641. 7: max.x, min.y, min.z
  41642. */
  41643. const position = this.geometry.attributes.position;
  41644. const array = position.array;
  41645. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  41646. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  41647. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  41648. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  41649. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  41650. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  41651. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  41652. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  41653. position.needsUpdate = true;
  41654. this.geometry.computeBoundingSphere();
  41655. }
  41656. /**
  41657. * Updates the wireframe box for the passed object.
  41658. *
  41659. * @param {Object3D} object - The 3D object to create the helper for.
  41660. * @return {BoxHelper} A reference to this instance.
  41661. */
  41662. setFromObject( object ) {
  41663. this.object = object;
  41664. this.update();
  41665. return this;
  41666. }
  41667. copy( source, recursive ) {
  41668. super.copy( source, recursive );
  41669. this.object = source.object;
  41670. return this;
  41671. }
  41672. /**
  41673. * Frees the GPU-related resources allocated by this instance. Call this
  41674. * method whenever this instance is no longer used in your app.
  41675. */
  41676. dispose() {
  41677. this.geometry.dispose();
  41678. this.material.dispose();
  41679. }
  41680. }
  41681. /**
  41682. * A helper object to visualize an instance of {@link Box3}.
  41683. *
  41684. * ```js
  41685. * const box = new THREE.Box3();
  41686. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  41687. *
  41688. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  41689. * scene.add( helper )
  41690. * ```
  41691. *
  41692. * @augments LineSegments
  41693. */
  41694. class Box3Helper extends LineSegments {
  41695. /**
  41696. * Constructs a new box3 helper.
  41697. *
  41698. * @param {Box3} box - The box to visualize.
  41699. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41700. */
  41701. constructor( box, color = 0xffff00 ) {
  41702. 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 ] );
  41703. 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 ];
  41704. const geometry = new BufferGeometry();
  41705. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41706. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41707. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41708. /**
  41709. * The box being visualized.
  41710. *
  41711. * @type {Box3}
  41712. */
  41713. this.box = box;
  41714. this.type = 'Box3Helper';
  41715. this.geometry.computeBoundingSphere();
  41716. }
  41717. updateMatrixWorld( force ) {
  41718. const box = this.box;
  41719. if ( box.isEmpty() ) return;
  41720. box.getCenter( this.position );
  41721. box.getSize( this.scale );
  41722. this.scale.multiplyScalar( 0.5 );
  41723. super.updateMatrixWorld( force );
  41724. }
  41725. /**
  41726. * Frees the GPU-related resources allocated by this instance. Call this
  41727. * method whenever this instance is no longer used in your app.
  41728. */
  41729. dispose() {
  41730. this.geometry.dispose();
  41731. this.material.dispose();
  41732. }
  41733. }
  41734. /**
  41735. * A helper object to visualize an instance of {@link Plane}.
  41736. *
  41737. * ```js
  41738. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  41739. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  41740. * scene.add( helper );
  41741. * ```
  41742. *
  41743. * @augments Line
  41744. */
  41745. class PlaneHelper extends Line {
  41746. /**
  41747. * Constructs a new plane helper.
  41748. *
  41749. * @param {Plane} plane - The plane to be visualized.
  41750. * @param {number} [size=1] - The side length of plane helper.
  41751. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  41752. */
  41753. constructor( plane, size = 1, hex = 0xffff00 ) {
  41754. const color = hex;
  41755. 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 ];
  41756. const geometry = new BufferGeometry();
  41757. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41758. geometry.computeBoundingSphere();
  41759. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41760. this.type = 'PlaneHelper';
  41761. /**
  41762. * The plane being visualized.
  41763. *
  41764. * @type {Plane}
  41765. */
  41766. this.plane = plane;
  41767. /**
  41768. * The side length of plane helper.
  41769. *
  41770. * @type {number}
  41771. * @default 1
  41772. */
  41773. this.size = size;
  41774. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  41775. const geometry2 = new BufferGeometry();
  41776. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  41777. geometry2.computeBoundingSphere();
  41778. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  41779. }
  41780. updateMatrixWorld( force ) {
  41781. this.position.set( 0, 0, 0 );
  41782. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  41783. this.lookAt( this.plane.normal );
  41784. this.translateZ( - this.plane.constant );
  41785. super.updateMatrixWorld( force );
  41786. }
  41787. /**
  41788. * Updates the helper to match the position and direction of the
  41789. * light being visualized.
  41790. */
  41791. dispose() {
  41792. this.geometry.dispose();
  41793. this.material.dispose();
  41794. this.children[ 0 ].geometry.dispose();
  41795. this.children[ 0 ].material.dispose();
  41796. }
  41797. }
  41798. const _axis = /*@__PURE__*/ new Vector3();
  41799. let _lineGeometry, _coneGeometry;
  41800. /**
  41801. * An 3D arrow object for visualizing directions.
  41802. *
  41803. * ```js
  41804. * const dir = new THREE.Vector3( 1, 2, 0 );
  41805. *
  41806. * //normalize the direction vector (convert to vector of length 1)
  41807. * dir.normalize();
  41808. *
  41809. * const origin = new THREE.Vector3( 0, 0, 0 );
  41810. * const length = 1;
  41811. * const hex = 0xffff00;
  41812. *
  41813. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  41814. * scene.add( arrowHelper );
  41815. * ```
  41816. *
  41817. * @augments Object3D
  41818. */
  41819. class ArrowHelper extends Object3D {
  41820. /**
  41821. * Constructs a new arrow helper.
  41822. *
  41823. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  41824. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  41825. * @param {number} [length=1] - Length of the arrow in world units.
  41826. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  41827. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  41828. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  41829. */
  41830. 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 ) {
  41831. super();
  41832. this.type = 'ArrowHelper';
  41833. if ( _lineGeometry === undefined ) {
  41834. _lineGeometry = new BufferGeometry();
  41835. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  41836. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  41837. _coneGeometry.translate( 0, -0.5, 0 );
  41838. }
  41839. this.position.copy( origin );
  41840. /**
  41841. * The line part of the arrow helper.
  41842. *
  41843. * @type {Line}
  41844. */
  41845. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41846. this.line.matrixAutoUpdate = false;
  41847. this.add( this.line );
  41848. /**
  41849. * The cone part of the arrow helper.
  41850. *
  41851. * @type {Mesh}
  41852. */
  41853. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  41854. this.cone.matrixAutoUpdate = false;
  41855. this.add( this.cone );
  41856. this.setDirection( dir );
  41857. this.setLength( length, headLength, headWidth );
  41858. }
  41859. /**
  41860. * Sets the direction of the helper.
  41861. *
  41862. * @param {Vector3} dir - The normalized direction vector.
  41863. */
  41864. setDirection( dir ) {
  41865. // dir is assumed to be normalized
  41866. if ( dir.y > 0.99999 ) {
  41867. this.quaternion.set( 0, 0, 0, 1 );
  41868. } else if ( dir.y < -0.99999 ) {
  41869. this.quaternion.set( 1, 0, 0, 0 );
  41870. } else {
  41871. _axis.set( dir.z, 0, - dir.x ).normalize();
  41872. const radians = Math.acos( dir.y );
  41873. this.quaternion.setFromAxisAngle( _axis, radians );
  41874. }
  41875. }
  41876. /**
  41877. * Sets the length of the helper.
  41878. *
  41879. * @param {number} length - Length of the arrow in world units.
  41880. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  41881. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  41882. */
  41883. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  41884. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  41885. this.line.updateMatrix();
  41886. this.cone.scale.set( headWidth, headLength, headWidth );
  41887. this.cone.position.y = length;
  41888. this.cone.updateMatrix();
  41889. }
  41890. /**
  41891. * Sets the color of the helper.
  41892. *
  41893. * @param {number|Color|string} color - The color to set.
  41894. */
  41895. setColor( color ) {
  41896. this.line.material.color.set( color );
  41897. this.cone.material.color.set( color );
  41898. }
  41899. copy( source ) {
  41900. super.copy( source, false );
  41901. this.line.copy( source.line );
  41902. this.cone.copy( source.cone );
  41903. return this;
  41904. }
  41905. /**
  41906. * Frees the GPU-related resources allocated by this instance. Call this
  41907. * method whenever this instance is no longer used in your app.
  41908. */
  41909. dispose() {
  41910. this.line.geometry.dispose();
  41911. this.line.material.dispose();
  41912. this.cone.geometry.dispose();
  41913. this.cone.material.dispose();
  41914. }
  41915. }
  41916. /**
  41917. * An axis object to visualize the 3 axes in a simple way.
  41918. * The X axis is red. The Y axis is green. The Z axis is blue.
  41919. *
  41920. * ```js
  41921. * const axesHelper = new THREE.AxesHelper( 5 );
  41922. * scene.add( axesHelper );
  41923. * ```
  41924. *
  41925. * @augments LineSegments
  41926. */
  41927. class AxesHelper extends LineSegments {
  41928. /**
  41929. * Constructs a new axes helper.
  41930. *
  41931. * @param {number} [size=1] - Size of the lines representing the axes.
  41932. */
  41933. constructor( size = 1 ) {
  41934. const vertices = [
  41935. 0, 0, 0, size, 0, 0,
  41936. 0, 0, 0, 0, size, 0,
  41937. 0, 0, 0, 0, 0, size
  41938. ];
  41939. const colors = [
  41940. 1, 0, 0, 1, 0.6, 0,
  41941. 0, 1, 0, 0.6, 1, 0,
  41942. 0, 0, 1, 0, 0.6, 1
  41943. ];
  41944. const geometry = new BufferGeometry();
  41945. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41946. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41947. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41948. super( geometry, material );
  41949. this.type = 'AxesHelper';
  41950. }
  41951. /**
  41952. * Defines the colors of the axes helper.
  41953. *
  41954. * @param {number|Color|string} xAxisColor - The color for the x axis.
  41955. * @param {number|Color|string} yAxisColor - The color for the y axis.
  41956. * @param {number|Color|string} zAxisColor - The color for the z axis.
  41957. * @return {AxesHelper} A reference to this axes helper.
  41958. */
  41959. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  41960. const color = new Color();
  41961. const array = this.geometry.attributes.color.array;
  41962. color.set( xAxisColor );
  41963. color.toArray( array, 0 );
  41964. color.toArray( array, 3 );
  41965. color.set( yAxisColor );
  41966. color.toArray( array, 6 );
  41967. color.toArray( array, 9 );
  41968. color.set( zAxisColor );
  41969. color.toArray( array, 12 );
  41970. color.toArray( array, 15 );
  41971. this.geometry.attributes.color.needsUpdate = true;
  41972. return this;
  41973. }
  41974. /**
  41975. * Frees the GPU-related resources allocated by this instance. Call this
  41976. * method whenever this instance is no longer used in your app.
  41977. */
  41978. dispose() {
  41979. this.geometry.dispose();
  41980. this.material.dispose();
  41981. }
  41982. }
  41983. /**
  41984. * This class is used to convert a series of paths to an array of
  41985. * shapes. It is specifically used in context of fonts and SVG.
  41986. */
  41987. class ShapePath {
  41988. /**
  41989. * Constructs a new shape path.
  41990. */
  41991. constructor() {
  41992. this.type = 'ShapePath';
  41993. /**
  41994. * The color of the shape.
  41995. *
  41996. * @type {Color}
  41997. */
  41998. this.color = new Color();
  41999. /**
  42000. * The paths that have been generated for this shape.
  42001. *
  42002. * @type {Array<Path>}
  42003. * @default null
  42004. */
  42005. this.subPaths = [];
  42006. /**
  42007. * The current path that is being generated.
  42008. *
  42009. * @type {?Path}
  42010. * @default null
  42011. */
  42012. this.currentPath = null;
  42013. }
  42014. /**
  42015. * Creates a new path and moves it current point to the given one.
  42016. *
  42017. * @param {number} x - The x coordinate.
  42018. * @param {number} y - The y coordinate.
  42019. * @return {ShapePath} A reference to this shape path.
  42020. */
  42021. moveTo( x, y ) {
  42022. this.currentPath = new Path();
  42023. this.subPaths.push( this.currentPath );
  42024. this.currentPath.moveTo( x, y );
  42025. return this;
  42026. }
  42027. /**
  42028. * Adds an instance of {@link LineCurve} to the path by connecting
  42029. * the current point with the given one.
  42030. *
  42031. * @param {number} x - The x coordinate of the end point.
  42032. * @param {number} y - The y coordinate of the end point.
  42033. * @return {ShapePath} A reference to this shape path.
  42034. */
  42035. lineTo( x, y ) {
  42036. this.currentPath.lineTo( x, y );
  42037. return this;
  42038. }
  42039. /**
  42040. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  42041. * the current point with the given one.
  42042. *
  42043. * @param {number} aCPx - The x coordinate of the control point.
  42044. * @param {number} aCPy - The y coordinate of the control point.
  42045. * @param {number} aX - The x coordinate of the end point.
  42046. * @param {number} aY - The y coordinate of the end point.
  42047. * @return {ShapePath} A reference to this shape path.
  42048. */
  42049. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  42050. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  42051. return this;
  42052. }
  42053. /**
  42054. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  42055. * the current point with the given one.
  42056. *
  42057. * @param {number} aCP1x - The x coordinate of the first control point.
  42058. * @param {number} aCP1y - The y coordinate of the first control point.
  42059. * @param {number} aCP2x - The x coordinate of the second control point.
  42060. * @param {number} aCP2y - The y coordinate of the second control point.
  42061. * @param {number} aX - The x coordinate of the end point.
  42062. * @param {number} aY - The y coordinate of the end point.
  42063. * @return {ShapePath} A reference to this shape path.
  42064. */
  42065. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  42066. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  42067. return this;
  42068. }
  42069. /**
  42070. * Adds an instance of {@link SplineCurve} to the path by connecting
  42071. * the current point with the given list of points.
  42072. *
  42073. * @param {Array<Vector2>} pts - An array of points in 2D space.
  42074. * @return {ShapePath} A reference to this shape path.
  42075. */
  42076. splineThru( pts ) {
  42077. this.currentPath.splineThru( pts );
  42078. return this;
  42079. }
  42080. /**
  42081. * Converts the paths into an array of shapes.
  42082. *
  42083. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  42084. * If this flag is set to `true`, then those are flipped.
  42085. * @return {Array<Shape>} An array of shapes.
  42086. */
  42087. toShapes( isCCW ) {
  42088. function toShapesNoHoles( inSubpaths ) {
  42089. const shapes = [];
  42090. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  42091. const tmpPath = inSubpaths[ i ];
  42092. const tmpShape = new Shape();
  42093. tmpShape.curves = tmpPath.curves;
  42094. shapes.push( tmpShape );
  42095. }
  42096. return shapes;
  42097. }
  42098. function isPointInsidePolygon( inPt, inPolygon ) {
  42099. const polyLen = inPolygon.length;
  42100. // inPt on polygon contour => immediate success or
  42101. // toggling of inside/outside at every single! intersection point of an edge
  42102. // with the horizontal line through inPt, left of inPt
  42103. // not counting lowerY endpoints of edges and whole edges on that line
  42104. let inside = false;
  42105. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  42106. let edgeLowPt = inPolygon[ p ];
  42107. let edgeHighPt = inPolygon[ q ];
  42108. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  42109. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  42110. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  42111. // not parallel
  42112. if ( edgeDy < 0 ) {
  42113. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  42114. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  42115. }
  42116. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  42117. if ( inPt.y === edgeLowPt.y ) {
  42118. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  42119. // continue; // no intersection or edgeLowPt => doesn't count !!!
  42120. } else {
  42121. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  42122. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  42123. if ( perpEdge < 0 ) continue;
  42124. inside = ! inside; // true intersection left of inPt
  42125. }
  42126. } else {
  42127. // parallel or collinear
  42128. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  42129. // edge lies on the same horizontal line as inPt
  42130. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  42131. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  42132. // continue;
  42133. }
  42134. }
  42135. return inside;
  42136. }
  42137. const isClockWise = ShapeUtils.isClockWise;
  42138. const subPaths = this.subPaths;
  42139. if ( subPaths.length === 0 ) return [];
  42140. let solid, tmpPath, tmpShape;
  42141. const shapes = [];
  42142. if ( subPaths.length === 1 ) {
  42143. tmpPath = subPaths[ 0 ];
  42144. tmpShape = new Shape();
  42145. tmpShape.curves = tmpPath.curves;
  42146. shapes.push( tmpShape );
  42147. return shapes;
  42148. }
  42149. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  42150. holesFirst = isCCW ? ! holesFirst : holesFirst;
  42151. // console.log("Holes first", holesFirst);
  42152. const betterShapeHoles = [];
  42153. const newShapes = [];
  42154. let newShapeHoles = [];
  42155. let mainIdx = 0;
  42156. let tmpPoints;
  42157. newShapes[ mainIdx ] = undefined;
  42158. newShapeHoles[ mainIdx ] = [];
  42159. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  42160. tmpPath = subPaths[ i ];
  42161. tmpPoints = tmpPath.getPoints();
  42162. solid = isClockWise( tmpPoints );
  42163. solid = isCCW ? ! solid : solid;
  42164. if ( solid ) {
  42165. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  42166. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  42167. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  42168. if ( holesFirst ) mainIdx ++;
  42169. newShapeHoles[ mainIdx ] = [];
  42170. //console.log('cw', i);
  42171. } else {
  42172. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  42173. //console.log('ccw', i);
  42174. }
  42175. }
  42176. // only Holes? -> probably all Shapes with wrong orientation
  42177. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  42178. if ( newShapes.length > 1 ) {
  42179. let ambiguous = false;
  42180. let toChange = 0;
  42181. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42182. betterShapeHoles[ sIdx ] = [];
  42183. }
  42184. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42185. const sho = newShapeHoles[ sIdx ];
  42186. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  42187. const ho = sho[ hIdx ];
  42188. let hole_unassigned = true;
  42189. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  42190. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  42191. if ( sIdx !== s2Idx ) toChange ++;
  42192. if ( hole_unassigned ) {
  42193. hole_unassigned = false;
  42194. betterShapeHoles[ s2Idx ].push( ho );
  42195. } else {
  42196. ambiguous = true;
  42197. }
  42198. }
  42199. }
  42200. if ( hole_unassigned ) {
  42201. betterShapeHoles[ sIdx ].push( ho );
  42202. }
  42203. }
  42204. }
  42205. if ( toChange > 0 && ambiguous === false ) {
  42206. newShapeHoles = betterShapeHoles;
  42207. }
  42208. }
  42209. let tmpHoles;
  42210. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  42211. tmpShape = newShapes[ i ].s;
  42212. shapes.push( tmpShape );
  42213. tmpHoles = newShapeHoles[ i ];
  42214. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  42215. tmpShape.holes.push( tmpHoles[ j ].h );
  42216. }
  42217. }
  42218. //console.log("shape", shapes);
  42219. return shapes;
  42220. }
  42221. }
  42222. /**
  42223. * Abstract base class for controls.
  42224. *
  42225. * @abstract
  42226. * @augments EventDispatcher
  42227. */
  42228. class Controls extends EventDispatcher {
  42229. /**
  42230. * Constructs a new controls instance.
  42231. *
  42232. * @param {Object3D} object - The object that is managed by the controls.
  42233. * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
  42234. */
  42235. constructor( object, domElement = null ) {
  42236. super();
  42237. /**
  42238. * The object that is managed by the controls.
  42239. *
  42240. * @type {Object3D}
  42241. */
  42242. this.object = object;
  42243. /**
  42244. * The HTML element used for event listeners.
  42245. *
  42246. * @type {?HTMLDOMElement}
  42247. * @default null
  42248. */
  42249. this.domElement = domElement;
  42250. /**
  42251. * Whether the controls responds to user input or not.
  42252. *
  42253. * @type {boolean}
  42254. * @default true
  42255. */
  42256. this.enabled = true;
  42257. /**
  42258. * The internal state of the controls.
  42259. *
  42260. * @type {number}
  42261. * @default -1
  42262. */
  42263. this.state = -1;
  42264. /**
  42265. * This object defines the keyboard input of the controls.
  42266. *
  42267. * @type {Object}
  42268. */
  42269. this.keys = {};
  42270. /**
  42271. * This object defines what type of actions are assigned to the available mouse buttons.
  42272. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  42273. *
  42274. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  42275. */
  42276. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  42277. /**
  42278. * This object defines what type of actions are assigned to what kind of touch interaction.
  42279. * It depends on the control implementation what kind of touch interaction and actions are supported.
  42280. *
  42281. * @type {{ONE: ?number, TWO: ?number}}
  42282. */
  42283. this.touches = { ONE: null, TWO: null };
  42284. }
  42285. /**
  42286. * Connects the controls to the DOM. This method has so called "side effects" since
  42287. * it adds the module's event listeners to the DOM.
  42288. *
  42289. * @param {HTMLDOMElement} element - The DOM element to connect to.
  42290. */
  42291. connect( element ) {
  42292. if ( element === undefined ) {
  42293. console.warn( 'THREE.Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  42294. return;
  42295. }
  42296. if ( this.domElement !== null ) this.disconnect();
  42297. this.domElement = element;
  42298. }
  42299. /**
  42300. * Disconnects the controls from the DOM.
  42301. */
  42302. disconnect() {}
  42303. /**
  42304. * Call this method if you no longer want use to the controls. It frees all internal
  42305. * resources and removes all event listeners.
  42306. */
  42307. dispose() {}
  42308. /**
  42309. * Controls should implement this method if they have to update their internal state
  42310. * per simulation step.
  42311. *
  42312. * @param {number} [delta] - The time delta in seconds.
  42313. */
  42314. update( /* delta */ ) {}
  42315. }
  42316. /**
  42317. * Scales the texture as large as possible within its surface without cropping
  42318. * or stretching the texture. The method preserves the original aspect ratio of
  42319. * the texture. Akin to CSS `object-fit: contain`
  42320. *
  42321. * @param {Texture} texture - The texture.
  42322. * @param {number} aspect - The texture's aspect ratio.
  42323. * @return {Texture} The updated texture.
  42324. */
  42325. function contain( texture, aspect ) {
  42326. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42327. if ( imageAspect > aspect ) {
  42328. texture.repeat.x = 1;
  42329. texture.repeat.y = imageAspect / aspect;
  42330. texture.offset.x = 0;
  42331. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42332. } else {
  42333. texture.repeat.x = aspect / imageAspect;
  42334. texture.repeat.y = 1;
  42335. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42336. texture.offset.y = 0;
  42337. }
  42338. return texture;
  42339. }
  42340. /**
  42341. * Scales the texture to the smallest possible size to fill the surface, leaving
  42342. * no empty space. The method preserves the original aspect ratio of the texture.
  42343. * Akin to CSS `object-fit: cover`.
  42344. *
  42345. * @param {Texture} texture - The texture.
  42346. * @param {number} aspect - The texture's aspect ratio.
  42347. * @return {Texture} The updated texture.
  42348. */
  42349. function cover( texture, aspect ) {
  42350. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42351. if ( imageAspect > aspect ) {
  42352. texture.repeat.x = aspect / imageAspect;
  42353. texture.repeat.y = 1;
  42354. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42355. texture.offset.y = 0;
  42356. } else {
  42357. texture.repeat.x = 1;
  42358. texture.repeat.y = imageAspect / aspect;
  42359. texture.offset.x = 0;
  42360. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42361. }
  42362. return texture;
  42363. }
  42364. /**
  42365. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42366. *
  42367. * @param {Texture} texture - The texture.
  42368. * @return {Texture} The updated texture.
  42369. */
  42370. function fill( texture ) {
  42371. texture.repeat.x = 1;
  42372. texture.repeat.y = 1;
  42373. texture.offset.x = 0;
  42374. texture.offset.y = 0;
  42375. return texture;
  42376. }
  42377. /**
  42378. * Determines how many bytes must be used to represent the texture.
  42379. *
  42380. * @param {number} width - The width of the texture.
  42381. * @param {number} height - The height of the texture.
  42382. * @param {number} format - The texture's format.
  42383. * @param {number} type - The texture's type.
  42384. * @return {number} The byte length.
  42385. */
  42386. function getByteLength( width, height, format, type ) {
  42387. const typeByteLength = getTextureTypeByteLength( type );
  42388. switch ( format ) {
  42389. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  42390. case AlphaFormat:
  42391. return width * height;
  42392. case RedFormat:
  42393. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42394. case RedIntegerFormat:
  42395. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42396. case RGFormat:
  42397. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42398. case RGIntegerFormat:
  42399. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42400. case RGBFormat:
  42401. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42402. case RGBAFormat:
  42403. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42404. case RGBAIntegerFormat:
  42405. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42406. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  42407. case RGB_S3TC_DXT1_Format:
  42408. case RGBA_S3TC_DXT1_Format:
  42409. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42410. case RGBA_S3TC_DXT3_Format:
  42411. case RGBA_S3TC_DXT5_Format:
  42412. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42413. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  42414. case RGB_PVRTC_2BPPV1_Format:
  42415. case RGBA_PVRTC_2BPPV1_Format:
  42416. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  42417. case RGB_PVRTC_4BPPV1_Format:
  42418. case RGBA_PVRTC_4BPPV1_Format:
  42419. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  42420. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  42421. case RGB_ETC1_Format:
  42422. case RGB_ETC2_Format:
  42423. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42424. case RGBA_ETC2_EAC_Format:
  42425. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42426. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  42427. case RGBA_ASTC_4x4_Format:
  42428. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42429. case RGBA_ASTC_5x4_Format:
  42430. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42431. case RGBA_ASTC_5x5_Format:
  42432. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42433. case RGBA_ASTC_6x5_Format:
  42434. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42435. case RGBA_ASTC_6x6_Format:
  42436. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42437. case RGBA_ASTC_8x5_Format:
  42438. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42439. case RGBA_ASTC_8x6_Format:
  42440. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42441. case RGBA_ASTC_8x8_Format:
  42442. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42443. case RGBA_ASTC_10x5_Format:
  42444. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42445. case RGBA_ASTC_10x6_Format:
  42446. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42447. case RGBA_ASTC_10x8_Format:
  42448. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42449. case RGBA_ASTC_10x10_Format:
  42450. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42451. case RGBA_ASTC_12x10_Format:
  42452. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42453. case RGBA_ASTC_12x12_Format:
  42454. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  42455. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  42456. case RGBA_BPTC_Format:
  42457. case RGB_BPTC_SIGNED_Format:
  42458. case RGB_BPTC_UNSIGNED_Format:
  42459. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42460. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  42461. case RED_RGTC1_Format:
  42462. case SIGNED_RED_RGTC1_Format:
  42463. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  42464. case RED_GREEN_RGTC2_Format:
  42465. case SIGNED_RED_GREEN_RGTC2_Format:
  42466. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42467. }
  42468. throw new Error(
  42469. `Unable to determine texture byte length for ${format} format.`,
  42470. );
  42471. }
  42472. function getTextureTypeByteLength( type ) {
  42473. switch ( type ) {
  42474. case UnsignedByteType:
  42475. case ByteType:
  42476. return { byteLength: 1, components: 1 };
  42477. case UnsignedShortType:
  42478. case ShortType:
  42479. case HalfFloatType:
  42480. return { byteLength: 2, components: 1 };
  42481. case UnsignedShort4444Type:
  42482. case UnsignedShort5551Type:
  42483. return { byteLength: 2, components: 4 };
  42484. case UnsignedIntType:
  42485. case IntType:
  42486. case FloatType:
  42487. return { byteLength: 4, components: 1 };
  42488. case UnsignedInt5999Type:
  42489. case UnsignedInt101111Type:
  42490. return { byteLength: 4, components: 3 };
  42491. }
  42492. throw new Error( `Unknown texture type ${type}.` );
  42493. }
  42494. /**
  42495. * A class containing utility functions for textures.
  42496. *
  42497. * @hideconstructor
  42498. */
  42499. class TextureUtils {
  42500. /**
  42501. * Scales the texture as large as possible within its surface without cropping
  42502. * or stretching the texture. The method preserves the original aspect ratio of
  42503. * the texture. Akin to CSS `object-fit: contain`
  42504. *
  42505. * @param {Texture} texture - The texture.
  42506. * @param {number} aspect - The texture's aspect ratio.
  42507. * @return {Texture} The updated texture.
  42508. */
  42509. static contain( texture, aspect ) {
  42510. return contain( texture, aspect );
  42511. }
  42512. /**
  42513. * Scales the texture to the smallest possible size to fill the surface, leaving
  42514. * no empty space. The method preserves the original aspect ratio of the texture.
  42515. * Akin to CSS `object-fit: cover`.
  42516. *
  42517. * @param {Texture} texture - The texture.
  42518. * @param {number} aspect - The texture's aspect ratio.
  42519. * @return {Texture} The updated texture.
  42520. */
  42521. static cover( texture, aspect ) {
  42522. return cover( texture, aspect );
  42523. }
  42524. /**
  42525. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42526. *
  42527. * @param {Texture} texture - The texture.
  42528. * @return {Texture} The updated texture.
  42529. */
  42530. static fill( texture ) {
  42531. return fill( texture );
  42532. }
  42533. /**
  42534. * Determines how many bytes must be used to represent the texture.
  42535. *
  42536. * @param {number} width - The width of the texture.
  42537. * @param {number} height - The height of the texture.
  42538. * @param {number} format - The texture's format.
  42539. * @param {number} type - The texture's type.
  42540. * @return {number} The byte length.
  42541. */
  42542. static getByteLength( width, height, format, type ) {
  42543. return getByteLength( width, height, format, type );
  42544. }
  42545. }
  42546. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  42547. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  42548. revision: REVISION,
  42549. } } ) );
  42550. }
  42551. if ( typeof window !== 'undefined' ) {
  42552. if ( window.__THREE__ ) {
  42553. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  42554. } else {
  42555. window.__THREE__ = REVISION;
  42556. }
  42557. }
  42558. function WebGLAnimation() {
  42559. let context = null;
  42560. let isAnimating = false;
  42561. let animationLoop = null;
  42562. let requestId = null;
  42563. function onAnimationFrame( time, frame ) {
  42564. animationLoop( time, frame );
  42565. requestId = context.requestAnimationFrame( onAnimationFrame );
  42566. }
  42567. return {
  42568. start: function () {
  42569. if ( isAnimating === true ) return;
  42570. if ( animationLoop === null ) return;
  42571. requestId = context.requestAnimationFrame( onAnimationFrame );
  42572. isAnimating = true;
  42573. },
  42574. stop: function () {
  42575. context.cancelAnimationFrame( requestId );
  42576. isAnimating = false;
  42577. },
  42578. setAnimationLoop: function ( callback ) {
  42579. animationLoop = callback;
  42580. },
  42581. setContext: function ( value ) {
  42582. context = value;
  42583. }
  42584. };
  42585. }
  42586. function WebGLAttributes( gl ) {
  42587. const buffers = new WeakMap();
  42588. function createBuffer( attribute, bufferType ) {
  42589. const array = attribute.array;
  42590. const usage = attribute.usage;
  42591. const size = array.byteLength;
  42592. const buffer = gl.createBuffer();
  42593. gl.bindBuffer( bufferType, buffer );
  42594. gl.bufferData( bufferType, array, usage );
  42595. attribute.onUploadCallback();
  42596. let type;
  42597. if ( array instanceof Float32Array ) {
  42598. type = gl.FLOAT;
  42599. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  42600. type = gl.HALF_FLOAT;
  42601. } else if ( array instanceof Uint16Array ) {
  42602. if ( attribute.isFloat16BufferAttribute ) {
  42603. type = gl.HALF_FLOAT;
  42604. } else {
  42605. type = gl.UNSIGNED_SHORT;
  42606. }
  42607. } else if ( array instanceof Int16Array ) {
  42608. type = gl.SHORT;
  42609. } else if ( array instanceof Uint32Array ) {
  42610. type = gl.UNSIGNED_INT;
  42611. } else if ( array instanceof Int32Array ) {
  42612. type = gl.INT;
  42613. } else if ( array instanceof Int8Array ) {
  42614. type = gl.BYTE;
  42615. } else if ( array instanceof Uint8Array ) {
  42616. type = gl.UNSIGNED_BYTE;
  42617. } else if ( array instanceof Uint8ClampedArray ) {
  42618. type = gl.UNSIGNED_BYTE;
  42619. } else {
  42620. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  42621. }
  42622. return {
  42623. buffer: buffer,
  42624. type: type,
  42625. bytesPerElement: array.BYTES_PER_ELEMENT,
  42626. version: attribute.version,
  42627. size: size
  42628. };
  42629. }
  42630. function updateBuffer( buffer, attribute, bufferType ) {
  42631. const array = attribute.array;
  42632. const updateRanges = attribute.updateRanges;
  42633. gl.bindBuffer( bufferType, buffer );
  42634. if ( updateRanges.length === 0 ) {
  42635. // Not using update ranges
  42636. gl.bufferSubData( bufferType, 0, array );
  42637. } else {
  42638. // Before applying update ranges, we merge any adjacent / overlapping
  42639. // ranges to reduce load on `gl.bufferSubData`. Empirically, this has led
  42640. // to performance improvements for applications which make heavy use of
  42641. // update ranges. Likely due to GPU command overhead.
  42642. //
  42643. // Note that to reduce garbage collection between frames, we merge the
  42644. // update ranges in-place. This is safe because this method will clear the
  42645. // update ranges once updated.
  42646. updateRanges.sort( ( a, b ) => a.start - b.start );
  42647. // To merge the update ranges in-place, we work from left to right in the
  42648. // existing updateRanges array, merging ranges. This may result in a final
  42649. // array which is smaller than the original. This index tracks the last
  42650. // index representing a merged range, any data after this index can be
  42651. // trimmed once the merge algorithm is completed.
  42652. let mergeIndex = 0;
  42653. for ( let i = 1; i < updateRanges.length; i ++ ) {
  42654. const previousRange = updateRanges[ mergeIndex ];
  42655. const range = updateRanges[ i ];
  42656. // We add one here to merge adjacent ranges. This is safe because ranges
  42657. // operate over positive integers.
  42658. if ( range.start <= previousRange.start + previousRange.count + 1 ) {
  42659. previousRange.count = Math.max(
  42660. previousRange.count,
  42661. range.start + range.count - previousRange.start
  42662. );
  42663. } else {
  42664. ++ mergeIndex;
  42665. updateRanges[ mergeIndex ] = range;
  42666. }
  42667. }
  42668. // Trim the array to only contain the merged ranges.
  42669. updateRanges.length = mergeIndex + 1;
  42670. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  42671. const range = updateRanges[ i ];
  42672. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  42673. array, range.start, range.count );
  42674. }
  42675. attribute.clearUpdateRanges();
  42676. }
  42677. attribute.onUploadCallback();
  42678. }
  42679. //
  42680. function get( attribute ) {
  42681. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42682. return buffers.get( attribute );
  42683. }
  42684. function remove( attribute ) {
  42685. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42686. const data = buffers.get( attribute );
  42687. if ( data ) {
  42688. gl.deleteBuffer( data.buffer );
  42689. buffers.delete( attribute );
  42690. }
  42691. }
  42692. function update( attribute, bufferType ) {
  42693. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42694. if ( attribute.isGLBufferAttribute ) {
  42695. const cached = buffers.get( attribute );
  42696. if ( ! cached || cached.version < attribute.version ) {
  42697. buffers.set( attribute, {
  42698. buffer: attribute.buffer,
  42699. type: attribute.type,
  42700. bytesPerElement: attribute.elementSize,
  42701. version: attribute.version
  42702. } );
  42703. }
  42704. return;
  42705. }
  42706. const data = buffers.get( attribute );
  42707. if ( data === undefined ) {
  42708. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  42709. } else if ( data.version < attribute.version ) {
  42710. if ( data.size !== attribute.array.byteLength ) {
  42711. 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.' );
  42712. }
  42713. updateBuffer( data.buffer, attribute, bufferType );
  42714. data.version = attribute.version;
  42715. }
  42716. }
  42717. return {
  42718. get: get,
  42719. remove: remove,
  42720. update: update
  42721. };
  42722. }
  42723. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  42724. 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";
  42725. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  42726. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  42727. 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";
  42728. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  42729. 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";
  42730. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  42731. 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";
  42732. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif";
  42733. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  42734. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  42735. 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";
  42736. 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";
  42737. 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";
  42738. 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";
  42739. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  42740. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  42741. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  42742. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  42743. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  42744. 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";
  42745. 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";
  42746. 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";
  42747. 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";
  42748. 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";
  42749. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  42750. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  42751. 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";
  42752. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  42753. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  42754. 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}";
  42755. 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";
  42756. 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";
  42757. 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";
  42758. 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";
  42759. 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";
  42760. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  42761. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  42762. 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";
  42763. 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";
  42764. 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}";
  42765. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  42766. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  42767. 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";
  42768. 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";
  42769. 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";
  42770. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  42771. 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";
  42772. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  42773. 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";
  42774. 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";
  42775. 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}";
  42776. 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";
  42777. 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";
  42778. 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";
  42779. 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";
  42780. var logdepthbuf_pars_fragment = "#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  42781. var logdepthbuf_pars_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  42782. var logdepthbuf_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif";
  42783. 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";
  42784. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  42785. 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";
  42786. 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";
  42787. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  42788. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  42789. 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";
  42790. 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";
  42791. 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";
  42792. 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";
  42793. 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";
  42794. 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;";
  42795. 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";
  42796. 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";
  42797. 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";
  42798. 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";
  42799. 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";
  42800. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  42801. 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";
  42802. 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";
  42803. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  42804. 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 );";
  42805. 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}";
  42806. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  42807. 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;";
  42808. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  42809. 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";
  42810. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  42811. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  42812. 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";
  42813. 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";
  42814. 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";
  42815. 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}";
  42816. 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";
  42817. 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";
  42818. 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";
  42819. 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";
  42820. 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";
  42821. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  42822. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  42823. 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; }";
  42824. 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";
  42825. 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";
  42826. 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";
  42827. 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";
  42828. 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";
  42829. 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";
  42830. 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}";
  42831. 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}";
  42832. 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}";
  42833. 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}";
  42834. 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}";
  42835. 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}";
  42836. 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}";
  42837. 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}";
  42838. 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}";
  42839. 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}";
  42840. 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}";
  42841. 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}";
  42842. 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}";
  42843. 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}";
  42844. 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}";
  42845. 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}";
  42846. 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}";
  42847. 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}";
  42848. 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}";
  42849. 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}";
  42850. 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}";
  42851. 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}";
  42852. 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}";
  42853. 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}";
  42854. 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}";
  42855. 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}";
  42856. 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}";
  42857. 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}";
  42858. 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}";
  42859. 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}";
  42860. 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}";
  42861. 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}";
  42862. 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}";
  42863. 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}";
  42864. const ShaderChunk = {
  42865. alphahash_fragment: alphahash_fragment,
  42866. alphahash_pars_fragment: alphahash_pars_fragment,
  42867. alphamap_fragment: alphamap_fragment,
  42868. alphamap_pars_fragment: alphamap_pars_fragment,
  42869. alphatest_fragment: alphatest_fragment,
  42870. alphatest_pars_fragment: alphatest_pars_fragment,
  42871. aomap_fragment: aomap_fragment,
  42872. aomap_pars_fragment: aomap_pars_fragment,
  42873. batching_pars_vertex: batching_pars_vertex,
  42874. batching_vertex: batching_vertex,
  42875. begin_vertex: begin_vertex,
  42876. beginnormal_vertex: beginnormal_vertex,
  42877. bsdfs: bsdfs,
  42878. iridescence_fragment: iridescence_fragment,
  42879. bumpmap_pars_fragment: bumpmap_pars_fragment,
  42880. clipping_planes_fragment: clipping_planes_fragment,
  42881. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  42882. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  42883. clipping_planes_vertex: clipping_planes_vertex,
  42884. color_fragment: color_fragment,
  42885. color_pars_fragment: color_pars_fragment,
  42886. color_pars_vertex: color_pars_vertex,
  42887. color_vertex: color_vertex,
  42888. common: common,
  42889. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  42890. defaultnormal_vertex: defaultnormal_vertex,
  42891. displacementmap_pars_vertex: displacementmap_pars_vertex,
  42892. displacementmap_vertex: displacementmap_vertex,
  42893. emissivemap_fragment: emissivemap_fragment,
  42894. emissivemap_pars_fragment: emissivemap_pars_fragment,
  42895. colorspace_fragment: colorspace_fragment,
  42896. colorspace_pars_fragment: colorspace_pars_fragment,
  42897. envmap_fragment: envmap_fragment,
  42898. envmap_common_pars_fragment: envmap_common_pars_fragment,
  42899. envmap_pars_fragment: envmap_pars_fragment,
  42900. envmap_pars_vertex: envmap_pars_vertex,
  42901. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  42902. envmap_vertex: envmap_vertex,
  42903. fog_vertex: fog_vertex,
  42904. fog_pars_vertex: fog_pars_vertex,
  42905. fog_fragment: fog_fragment,
  42906. fog_pars_fragment: fog_pars_fragment,
  42907. gradientmap_pars_fragment: gradientmap_pars_fragment,
  42908. lightmap_pars_fragment: lightmap_pars_fragment,
  42909. lights_lambert_fragment: lights_lambert_fragment,
  42910. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  42911. lights_pars_begin: lights_pars_begin,
  42912. lights_toon_fragment: lights_toon_fragment,
  42913. lights_toon_pars_fragment: lights_toon_pars_fragment,
  42914. lights_phong_fragment: lights_phong_fragment,
  42915. lights_phong_pars_fragment: lights_phong_pars_fragment,
  42916. lights_physical_fragment: lights_physical_fragment,
  42917. lights_physical_pars_fragment: lights_physical_pars_fragment,
  42918. lights_fragment_begin: lights_fragment_begin,
  42919. lights_fragment_maps: lights_fragment_maps,
  42920. lights_fragment_end: lights_fragment_end,
  42921. logdepthbuf_fragment: logdepthbuf_fragment,
  42922. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  42923. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  42924. logdepthbuf_vertex: logdepthbuf_vertex,
  42925. map_fragment: map_fragment,
  42926. map_pars_fragment: map_pars_fragment,
  42927. map_particle_fragment: map_particle_fragment,
  42928. map_particle_pars_fragment: map_particle_pars_fragment,
  42929. metalnessmap_fragment: metalnessmap_fragment,
  42930. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  42931. morphinstance_vertex: morphinstance_vertex,
  42932. morphcolor_vertex: morphcolor_vertex,
  42933. morphnormal_vertex: morphnormal_vertex,
  42934. morphtarget_pars_vertex: morphtarget_pars_vertex,
  42935. morphtarget_vertex: morphtarget_vertex,
  42936. normal_fragment_begin: normal_fragment_begin,
  42937. normal_fragment_maps: normal_fragment_maps,
  42938. normal_pars_fragment: normal_pars_fragment,
  42939. normal_pars_vertex: normal_pars_vertex,
  42940. normal_vertex: normal_vertex,
  42941. normalmap_pars_fragment: normalmap_pars_fragment,
  42942. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  42943. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  42944. clearcoat_pars_fragment: clearcoat_pars_fragment,
  42945. iridescence_pars_fragment: iridescence_pars_fragment,
  42946. opaque_fragment: opaque_fragment,
  42947. packing: packing,
  42948. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  42949. project_vertex: project_vertex,
  42950. dithering_fragment: dithering_fragment,
  42951. dithering_pars_fragment: dithering_pars_fragment,
  42952. roughnessmap_fragment: roughnessmap_fragment,
  42953. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  42954. shadowmap_pars_fragment: shadowmap_pars_fragment,
  42955. shadowmap_pars_vertex: shadowmap_pars_vertex,
  42956. shadowmap_vertex: shadowmap_vertex,
  42957. shadowmask_pars_fragment: shadowmask_pars_fragment,
  42958. skinbase_vertex: skinbase_vertex,
  42959. skinning_pars_vertex: skinning_pars_vertex,
  42960. skinning_vertex: skinning_vertex,
  42961. skinnormal_vertex: skinnormal_vertex,
  42962. specularmap_fragment: specularmap_fragment,
  42963. specularmap_pars_fragment: specularmap_pars_fragment,
  42964. tonemapping_fragment: tonemapping_fragment,
  42965. tonemapping_pars_fragment: tonemapping_pars_fragment,
  42966. transmission_fragment: transmission_fragment,
  42967. transmission_pars_fragment: transmission_pars_fragment,
  42968. uv_pars_fragment: uv_pars_fragment,
  42969. uv_pars_vertex: uv_pars_vertex,
  42970. uv_vertex: uv_vertex,
  42971. worldpos_vertex: worldpos_vertex,
  42972. background_vert: vertex$h,
  42973. background_frag: fragment$h,
  42974. backgroundCube_vert: vertex$g,
  42975. backgroundCube_frag: fragment$g,
  42976. cube_vert: vertex$f,
  42977. cube_frag: fragment$f,
  42978. depth_vert: vertex$e,
  42979. depth_frag: fragment$e,
  42980. distanceRGBA_vert: vertex$d,
  42981. distanceRGBA_frag: fragment$d,
  42982. equirect_vert: vertex$c,
  42983. equirect_frag: fragment$c,
  42984. linedashed_vert: vertex$b,
  42985. linedashed_frag: fragment$b,
  42986. meshbasic_vert: vertex$a,
  42987. meshbasic_frag: fragment$a,
  42988. meshlambert_vert: vertex$9,
  42989. meshlambert_frag: fragment$9,
  42990. meshmatcap_vert: vertex$8,
  42991. meshmatcap_frag: fragment$8,
  42992. meshnormal_vert: vertex$7,
  42993. meshnormal_frag: fragment$7,
  42994. meshphong_vert: vertex$6,
  42995. meshphong_frag: fragment$6,
  42996. meshphysical_vert: vertex$5,
  42997. meshphysical_frag: fragment$5,
  42998. meshtoon_vert: vertex$4,
  42999. meshtoon_frag: fragment$4,
  43000. points_vert: vertex$3,
  43001. points_frag: fragment$3,
  43002. shadow_vert: vertex$2,
  43003. shadow_frag: fragment$2,
  43004. sprite_vert: vertex$1,
  43005. sprite_frag: fragment$1
  43006. };
  43007. // Uniforms library for shared webgl shaders
  43008. const UniformsLib = {
  43009. common: {
  43010. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43011. opacity: { value: 1.0 },
  43012. map: { value: null },
  43013. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43014. alphaMap: { value: null },
  43015. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43016. alphaTest: { value: 0 }
  43017. },
  43018. specularmap: {
  43019. specularMap: { value: null },
  43020. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43021. },
  43022. envmap: {
  43023. envMap: { value: null },
  43024. envMapRotation: { value: /*@__PURE__*/ new Matrix3() },
  43025. flipEnvMap: { value: -1 },
  43026. reflectivity: { value: 1.0 }, // basic, lambert, phong
  43027. ior: { value: 1.5 }, // physical
  43028. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  43029. },
  43030. aomap: {
  43031. aoMap: { value: null },
  43032. aoMapIntensity: { value: 1 },
  43033. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43034. },
  43035. lightmap: {
  43036. lightMap: { value: null },
  43037. lightMapIntensity: { value: 1 },
  43038. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43039. },
  43040. bumpmap: {
  43041. bumpMap: { value: null },
  43042. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43043. bumpScale: { value: 1 }
  43044. },
  43045. normalmap: {
  43046. normalMap: { value: null },
  43047. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43048. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  43049. },
  43050. displacementmap: {
  43051. displacementMap: { value: null },
  43052. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43053. displacementScale: { value: 1 },
  43054. displacementBias: { value: 0 }
  43055. },
  43056. emissivemap: {
  43057. emissiveMap: { value: null },
  43058. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43059. },
  43060. metalnessmap: {
  43061. metalnessMap: { value: null },
  43062. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43063. },
  43064. roughnessmap: {
  43065. roughnessMap: { value: null },
  43066. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43067. },
  43068. gradientmap: {
  43069. gradientMap: { value: null }
  43070. },
  43071. fog: {
  43072. fogDensity: { value: 0.00025 },
  43073. fogNear: { value: 1 },
  43074. fogFar: { value: 2000 },
  43075. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  43076. },
  43077. lights: {
  43078. ambientLightColor: { value: [] },
  43079. lightProbe: { value: [] },
  43080. directionalLights: { value: [], properties: {
  43081. direction: {},
  43082. color: {}
  43083. } },
  43084. directionalLightShadows: { value: [], properties: {
  43085. shadowIntensity: 1,
  43086. shadowBias: {},
  43087. shadowNormalBias: {},
  43088. shadowRadius: {},
  43089. shadowMapSize: {}
  43090. } },
  43091. directionalShadowMap: { value: [] },
  43092. directionalShadowMatrix: { value: [] },
  43093. spotLights: { value: [], properties: {
  43094. color: {},
  43095. position: {},
  43096. direction: {},
  43097. distance: {},
  43098. coneCos: {},
  43099. penumbraCos: {},
  43100. decay: {}
  43101. } },
  43102. spotLightShadows: { value: [], properties: {
  43103. shadowIntensity: 1,
  43104. shadowBias: {},
  43105. shadowNormalBias: {},
  43106. shadowRadius: {},
  43107. shadowMapSize: {}
  43108. } },
  43109. spotLightMap: { value: [] },
  43110. spotShadowMap: { value: [] },
  43111. spotLightMatrix: { value: [] },
  43112. pointLights: { value: [], properties: {
  43113. color: {},
  43114. position: {},
  43115. decay: {},
  43116. distance: {}
  43117. } },
  43118. pointLightShadows: { value: [], properties: {
  43119. shadowIntensity: 1,
  43120. shadowBias: {},
  43121. shadowNormalBias: {},
  43122. shadowRadius: {},
  43123. shadowMapSize: {},
  43124. shadowCameraNear: {},
  43125. shadowCameraFar: {}
  43126. } },
  43127. pointShadowMap: { value: [] },
  43128. pointShadowMatrix: { value: [] },
  43129. hemisphereLights: { value: [], properties: {
  43130. direction: {},
  43131. skyColor: {},
  43132. groundColor: {}
  43133. } },
  43134. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  43135. rectAreaLights: { value: [], properties: {
  43136. color: {},
  43137. position: {},
  43138. width: {},
  43139. height: {}
  43140. } },
  43141. ltc_1: { value: null },
  43142. ltc_2: { value: null }
  43143. },
  43144. points: {
  43145. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43146. opacity: { value: 1.0 },
  43147. size: { value: 1.0 },
  43148. scale: { value: 1.0 },
  43149. map: { value: null },
  43150. alphaMap: { value: null },
  43151. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43152. alphaTest: { value: 0 },
  43153. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  43154. },
  43155. sprite: {
  43156. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43157. opacity: { value: 1.0 },
  43158. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  43159. rotation: { value: 0.0 },
  43160. map: { value: null },
  43161. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43162. alphaMap: { value: null },
  43163. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43164. alphaTest: { value: 0 }
  43165. }
  43166. };
  43167. const ShaderLib = {
  43168. basic: {
  43169. uniforms: /*@__PURE__*/ mergeUniforms( [
  43170. UniformsLib.common,
  43171. UniformsLib.specularmap,
  43172. UniformsLib.envmap,
  43173. UniformsLib.aomap,
  43174. UniformsLib.lightmap,
  43175. UniformsLib.fog
  43176. ] ),
  43177. vertexShader: ShaderChunk.meshbasic_vert,
  43178. fragmentShader: ShaderChunk.meshbasic_frag
  43179. },
  43180. lambert: {
  43181. uniforms: /*@__PURE__*/ mergeUniforms( [
  43182. UniformsLib.common,
  43183. UniformsLib.specularmap,
  43184. UniformsLib.envmap,
  43185. UniformsLib.aomap,
  43186. UniformsLib.lightmap,
  43187. UniformsLib.emissivemap,
  43188. UniformsLib.bumpmap,
  43189. UniformsLib.normalmap,
  43190. UniformsLib.displacementmap,
  43191. UniformsLib.fog,
  43192. UniformsLib.lights,
  43193. {
  43194. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  43195. }
  43196. ] ),
  43197. vertexShader: ShaderChunk.meshlambert_vert,
  43198. fragmentShader: ShaderChunk.meshlambert_frag
  43199. },
  43200. phong: {
  43201. uniforms: /*@__PURE__*/ mergeUniforms( [
  43202. UniformsLib.common,
  43203. UniformsLib.specularmap,
  43204. UniformsLib.envmap,
  43205. UniformsLib.aomap,
  43206. UniformsLib.lightmap,
  43207. UniformsLib.emissivemap,
  43208. UniformsLib.bumpmap,
  43209. UniformsLib.normalmap,
  43210. UniformsLib.displacementmap,
  43211. UniformsLib.fog,
  43212. UniformsLib.lights,
  43213. {
  43214. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43215. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  43216. shininess: { value: 30 }
  43217. }
  43218. ] ),
  43219. vertexShader: ShaderChunk.meshphong_vert,
  43220. fragmentShader: ShaderChunk.meshphong_frag
  43221. },
  43222. standard: {
  43223. uniforms: /*@__PURE__*/ mergeUniforms( [
  43224. UniformsLib.common,
  43225. UniformsLib.envmap,
  43226. UniformsLib.aomap,
  43227. UniformsLib.lightmap,
  43228. UniformsLib.emissivemap,
  43229. UniformsLib.bumpmap,
  43230. UniformsLib.normalmap,
  43231. UniformsLib.displacementmap,
  43232. UniformsLib.roughnessmap,
  43233. UniformsLib.metalnessmap,
  43234. UniformsLib.fog,
  43235. UniformsLib.lights,
  43236. {
  43237. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43238. roughness: { value: 1.0 },
  43239. metalness: { value: 0.0 },
  43240. envMapIntensity: { value: 1 }
  43241. }
  43242. ] ),
  43243. vertexShader: ShaderChunk.meshphysical_vert,
  43244. fragmentShader: ShaderChunk.meshphysical_frag
  43245. },
  43246. toon: {
  43247. uniforms: /*@__PURE__*/ mergeUniforms( [
  43248. UniformsLib.common,
  43249. UniformsLib.aomap,
  43250. UniformsLib.lightmap,
  43251. UniformsLib.emissivemap,
  43252. UniformsLib.bumpmap,
  43253. UniformsLib.normalmap,
  43254. UniformsLib.displacementmap,
  43255. UniformsLib.gradientmap,
  43256. UniformsLib.fog,
  43257. UniformsLib.lights,
  43258. {
  43259. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  43260. }
  43261. ] ),
  43262. vertexShader: ShaderChunk.meshtoon_vert,
  43263. fragmentShader: ShaderChunk.meshtoon_frag
  43264. },
  43265. matcap: {
  43266. uniforms: /*@__PURE__*/ mergeUniforms( [
  43267. UniformsLib.common,
  43268. UniformsLib.bumpmap,
  43269. UniformsLib.normalmap,
  43270. UniformsLib.displacementmap,
  43271. UniformsLib.fog,
  43272. {
  43273. matcap: { value: null }
  43274. }
  43275. ] ),
  43276. vertexShader: ShaderChunk.meshmatcap_vert,
  43277. fragmentShader: ShaderChunk.meshmatcap_frag
  43278. },
  43279. points: {
  43280. uniforms: /*@__PURE__*/ mergeUniforms( [
  43281. UniformsLib.points,
  43282. UniformsLib.fog
  43283. ] ),
  43284. vertexShader: ShaderChunk.points_vert,
  43285. fragmentShader: ShaderChunk.points_frag
  43286. },
  43287. dashed: {
  43288. uniforms: /*@__PURE__*/ mergeUniforms( [
  43289. UniformsLib.common,
  43290. UniformsLib.fog,
  43291. {
  43292. scale: { value: 1 },
  43293. dashSize: { value: 1 },
  43294. totalSize: { value: 2 }
  43295. }
  43296. ] ),
  43297. vertexShader: ShaderChunk.linedashed_vert,
  43298. fragmentShader: ShaderChunk.linedashed_frag
  43299. },
  43300. depth: {
  43301. uniforms: /*@__PURE__*/ mergeUniforms( [
  43302. UniformsLib.common,
  43303. UniformsLib.displacementmap
  43304. ] ),
  43305. vertexShader: ShaderChunk.depth_vert,
  43306. fragmentShader: ShaderChunk.depth_frag
  43307. },
  43308. normal: {
  43309. uniforms: /*@__PURE__*/ mergeUniforms( [
  43310. UniformsLib.common,
  43311. UniformsLib.bumpmap,
  43312. UniformsLib.normalmap,
  43313. UniformsLib.displacementmap,
  43314. {
  43315. opacity: { value: 1.0 }
  43316. }
  43317. ] ),
  43318. vertexShader: ShaderChunk.meshnormal_vert,
  43319. fragmentShader: ShaderChunk.meshnormal_frag
  43320. },
  43321. sprite: {
  43322. uniforms: /*@__PURE__*/ mergeUniforms( [
  43323. UniformsLib.sprite,
  43324. UniformsLib.fog
  43325. ] ),
  43326. vertexShader: ShaderChunk.sprite_vert,
  43327. fragmentShader: ShaderChunk.sprite_frag
  43328. },
  43329. background: {
  43330. uniforms: {
  43331. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  43332. t2D: { value: null },
  43333. backgroundIntensity: { value: 1 }
  43334. },
  43335. vertexShader: ShaderChunk.background_vert,
  43336. fragmentShader: ShaderChunk.background_frag
  43337. },
  43338. backgroundCube: {
  43339. uniforms: {
  43340. envMap: { value: null },
  43341. flipEnvMap: { value: -1 },
  43342. backgroundBlurriness: { value: 0 },
  43343. backgroundIntensity: { value: 1 },
  43344. backgroundRotation: { value: /*@__PURE__*/ new Matrix3() }
  43345. },
  43346. vertexShader: ShaderChunk.backgroundCube_vert,
  43347. fragmentShader: ShaderChunk.backgroundCube_frag
  43348. },
  43349. cube: {
  43350. uniforms: {
  43351. tCube: { value: null },
  43352. tFlip: { value: -1 },
  43353. opacity: { value: 1.0 }
  43354. },
  43355. vertexShader: ShaderChunk.cube_vert,
  43356. fragmentShader: ShaderChunk.cube_frag
  43357. },
  43358. equirect: {
  43359. uniforms: {
  43360. tEquirect: { value: null },
  43361. },
  43362. vertexShader: ShaderChunk.equirect_vert,
  43363. fragmentShader: ShaderChunk.equirect_frag
  43364. },
  43365. distanceRGBA: {
  43366. uniforms: /*@__PURE__*/ mergeUniforms( [
  43367. UniformsLib.common,
  43368. UniformsLib.displacementmap,
  43369. {
  43370. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  43371. nearDistance: { value: 1 },
  43372. farDistance: { value: 1000 }
  43373. }
  43374. ] ),
  43375. vertexShader: ShaderChunk.distanceRGBA_vert,
  43376. fragmentShader: ShaderChunk.distanceRGBA_frag
  43377. },
  43378. shadow: {
  43379. uniforms: /*@__PURE__*/ mergeUniforms( [
  43380. UniformsLib.lights,
  43381. UniformsLib.fog,
  43382. {
  43383. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  43384. opacity: { value: 1.0 }
  43385. },
  43386. ] ),
  43387. vertexShader: ShaderChunk.shadow_vert,
  43388. fragmentShader: ShaderChunk.shadow_frag
  43389. }
  43390. };
  43391. ShaderLib.physical = {
  43392. uniforms: /*@__PURE__*/ mergeUniforms( [
  43393. ShaderLib.standard.uniforms,
  43394. {
  43395. clearcoat: { value: 0 },
  43396. clearcoatMap: { value: null },
  43397. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43398. clearcoatNormalMap: { value: null },
  43399. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43400. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  43401. clearcoatRoughness: { value: 0 },
  43402. clearcoatRoughnessMap: { value: null },
  43403. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43404. dispersion: { value: 0 },
  43405. iridescence: { value: 0 },
  43406. iridescenceMap: { value: null },
  43407. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43408. iridescenceIOR: { value: 1.3 },
  43409. iridescenceThicknessMinimum: { value: 100 },
  43410. iridescenceThicknessMaximum: { value: 400 },
  43411. iridescenceThicknessMap: { value: null },
  43412. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43413. sheen: { value: 0 },
  43414. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43415. sheenColorMap: { value: null },
  43416. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43417. sheenRoughness: { value: 1 },
  43418. sheenRoughnessMap: { value: null },
  43419. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43420. transmission: { value: 0 },
  43421. transmissionMap: { value: null },
  43422. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43423. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  43424. transmissionSamplerMap: { value: null },
  43425. thickness: { value: 0 },
  43426. thicknessMap: { value: null },
  43427. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43428. attenuationDistance: { value: 0 },
  43429. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43430. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  43431. specularColorMap: { value: null },
  43432. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43433. specularIntensity: { value: 1 },
  43434. specularIntensityMap: { value: null },
  43435. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43436. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  43437. anisotropyMap: { value: null },
  43438. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43439. }
  43440. ] ),
  43441. vertexShader: ShaderChunk.meshphysical_vert,
  43442. fragmentShader: ShaderChunk.meshphysical_frag
  43443. };
  43444. const _rgb = { r: 0, b: 0, g: 0 };
  43445. const _e1$1 = /*@__PURE__*/ new Euler();
  43446. const _m1$1 = /*@__PURE__*/ new Matrix4();
  43447. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  43448. const clearColor = new Color( 0x000000 );
  43449. let clearAlpha = alpha === true ? 0 : 1;
  43450. let planeMesh;
  43451. let boxMesh;
  43452. let currentBackground = null;
  43453. let currentBackgroundVersion = 0;
  43454. let currentTonemapping = null;
  43455. function getBackground( scene ) {
  43456. let background = scene.isScene === true ? scene.background : null;
  43457. if ( background && background.isTexture ) {
  43458. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  43459. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  43460. }
  43461. return background;
  43462. }
  43463. function render( scene ) {
  43464. let forceClear = false;
  43465. const background = getBackground( scene );
  43466. if ( background === null ) {
  43467. setClear( clearColor, clearAlpha );
  43468. } else if ( background && background.isColor ) {
  43469. setClear( background, 1 );
  43470. forceClear = true;
  43471. }
  43472. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  43473. if ( environmentBlendMode === 'additive' ) {
  43474. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  43475. } else if ( environmentBlendMode === 'alpha-blend' ) {
  43476. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  43477. }
  43478. if ( renderer.autoClear || forceClear ) {
  43479. // buffers might not be writable which is required to ensure a correct clear
  43480. state.buffers.depth.setTest( true );
  43481. state.buffers.depth.setMask( true );
  43482. state.buffers.color.setMask( true );
  43483. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  43484. }
  43485. }
  43486. function addToRenderList( renderList, scene ) {
  43487. const background = getBackground( scene );
  43488. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  43489. if ( boxMesh === undefined ) {
  43490. boxMesh = new Mesh(
  43491. new BoxGeometry( 1, 1, 1 ),
  43492. new ShaderMaterial( {
  43493. name: 'BackgroundCubeMaterial',
  43494. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  43495. vertexShader: ShaderLib.backgroundCube.vertexShader,
  43496. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  43497. side: BackSide,
  43498. depthTest: false,
  43499. depthWrite: false,
  43500. fog: false,
  43501. allowOverride: false
  43502. } )
  43503. );
  43504. boxMesh.geometry.deleteAttribute( 'normal' );
  43505. boxMesh.geometry.deleteAttribute( 'uv' );
  43506. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  43507. this.matrixWorld.copyPosition( camera.matrixWorld );
  43508. };
  43509. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  43510. Object.defineProperty( boxMesh.material, 'envMap', {
  43511. get: function () {
  43512. return this.uniforms.envMap.value;
  43513. }
  43514. } );
  43515. objects.update( boxMesh );
  43516. }
  43517. _e1$1.copy( scene.backgroundRotation );
  43518. // accommodate left-handed frame
  43519. _e1$1.x *= -1; _e1$1.y *= -1; _e1$1.z *= -1;
  43520. if ( background.isCubeTexture && background.isRenderTargetTexture === false ) {
  43521. // environment maps which are not cube render targets or PMREMs follow a different convention
  43522. _e1$1.y *= -1;
  43523. _e1$1.z *= -1;
  43524. }
  43525. boxMesh.material.uniforms.envMap.value = background;
  43526. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? -1 : 1;
  43527. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  43528. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  43529. boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) );
  43530. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  43531. if ( currentBackground !== background ||
  43532. currentBackgroundVersion !== background.version ||
  43533. currentTonemapping !== renderer.toneMapping ) {
  43534. boxMesh.material.needsUpdate = true;
  43535. currentBackground = background;
  43536. currentBackgroundVersion = background.version;
  43537. currentTonemapping = renderer.toneMapping;
  43538. }
  43539. boxMesh.layers.enableAll();
  43540. // push to the pre-sorted opaque render list
  43541. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  43542. } else if ( background && background.isTexture ) {
  43543. if ( planeMesh === undefined ) {
  43544. planeMesh = new Mesh(
  43545. new PlaneGeometry( 2, 2 ),
  43546. new ShaderMaterial( {
  43547. name: 'BackgroundMaterial',
  43548. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  43549. vertexShader: ShaderLib.background.vertexShader,
  43550. fragmentShader: ShaderLib.background.fragmentShader,
  43551. side: FrontSide,
  43552. depthTest: false,
  43553. depthWrite: false,
  43554. fog: false,
  43555. allowOverride: false
  43556. } )
  43557. );
  43558. planeMesh.geometry.deleteAttribute( 'normal' );
  43559. // add "map" material property so the renderer can evaluate it like for built-in materials
  43560. Object.defineProperty( planeMesh.material, 'map', {
  43561. get: function () {
  43562. return this.uniforms.t2D.value;
  43563. }
  43564. } );
  43565. objects.update( planeMesh );
  43566. }
  43567. planeMesh.material.uniforms.t2D.value = background;
  43568. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  43569. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  43570. if ( background.matrixAutoUpdate === true ) {
  43571. background.updateMatrix();
  43572. }
  43573. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  43574. if ( currentBackground !== background ||
  43575. currentBackgroundVersion !== background.version ||
  43576. currentTonemapping !== renderer.toneMapping ) {
  43577. planeMesh.material.needsUpdate = true;
  43578. currentBackground = background;
  43579. currentBackgroundVersion = background.version;
  43580. currentTonemapping = renderer.toneMapping;
  43581. }
  43582. planeMesh.layers.enableAll();
  43583. // push to the pre-sorted opaque render list
  43584. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  43585. }
  43586. }
  43587. function setClear( color, alpha ) {
  43588. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  43589. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  43590. }
  43591. function dispose() {
  43592. if ( boxMesh !== undefined ) {
  43593. boxMesh.geometry.dispose();
  43594. boxMesh.material.dispose();
  43595. boxMesh = undefined;
  43596. }
  43597. if ( planeMesh !== undefined ) {
  43598. planeMesh.geometry.dispose();
  43599. planeMesh.material.dispose();
  43600. planeMesh = undefined;
  43601. }
  43602. }
  43603. return {
  43604. getClearColor: function () {
  43605. return clearColor;
  43606. },
  43607. setClearColor: function ( color, alpha = 1 ) {
  43608. clearColor.set( color );
  43609. clearAlpha = alpha;
  43610. setClear( clearColor, clearAlpha );
  43611. },
  43612. getClearAlpha: function () {
  43613. return clearAlpha;
  43614. },
  43615. setClearAlpha: function ( alpha ) {
  43616. clearAlpha = alpha;
  43617. setClear( clearColor, clearAlpha );
  43618. },
  43619. render: render,
  43620. addToRenderList: addToRenderList,
  43621. dispose: dispose
  43622. };
  43623. }
  43624. function WebGLBindingStates( gl, attributes ) {
  43625. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  43626. const bindingStates = {};
  43627. const defaultState = createBindingState( null );
  43628. let currentState = defaultState;
  43629. let forceUpdate = false;
  43630. function setup( object, material, program, geometry, index ) {
  43631. let updateBuffers = false;
  43632. const state = getBindingState( geometry, program, material );
  43633. if ( currentState !== state ) {
  43634. currentState = state;
  43635. bindVertexArrayObject( currentState.object );
  43636. }
  43637. updateBuffers = needsUpdate( object, geometry, program, index );
  43638. if ( updateBuffers ) saveCache( object, geometry, program, index );
  43639. if ( index !== null ) {
  43640. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  43641. }
  43642. if ( updateBuffers || forceUpdate ) {
  43643. forceUpdate = false;
  43644. setupVertexAttributes( object, material, program, geometry );
  43645. if ( index !== null ) {
  43646. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  43647. }
  43648. }
  43649. }
  43650. function createVertexArrayObject() {
  43651. return gl.createVertexArray();
  43652. }
  43653. function bindVertexArrayObject( vao ) {
  43654. return gl.bindVertexArray( vao );
  43655. }
  43656. function deleteVertexArrayObject( vao ) {
  43657. return gl.deleteVertexArray( vao );
  43658. }
  43659. function getBindingState( geometry, program, material ) {
  43660. const wireframe = ( material.wireframe === true );
  43661. let programMap = bindingStates[ geometry.id ];
  43662. if ( programMap === undefined ) {
  43663. programMap = {};
  43664. bindingStates[ geometry.id ] = programMap;
  43665. }
  43666. let stateMap = programMap[ program.id ];
  43667. if ( stateMap === undefined ) {
  43668. stateMap = {};
  43669. programMap[ program.id ] = stateMap;
  43670. }
  43671. let state = stateMap[ wireframe ];
  43672. if ( state === undefined ) {
  43673. state = createBindingState( createVertexArrayObject() );
  43674. stateMap[ wireframe ] = state;
  43675. }
  43676. return state;
  43677. }
  43678. function createBindingState( vao ) {
  43679. const newAttributes = [];
  43680. const enabledAttributes = [];
  43681. const attributeDivisors = [];
  43682. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  43683. newAttributes[ i ] = 0;
  43684. enabledAttributes[ i ] = 0;
  43685. attributeDivisors[ i ] = 0;
  43686. }
  43687. return {
  43688. // for backward compatibility on non-VAO support browser
  43689. geometry: null,
  43690. program: null,
  43691. wireframe: false,
  43692. newAttributes: newAttributes,
  43693. enabledAttributes: enabledAttributes,
  43694. attributeDivisors: attributeDivisors,
  43695. object: vao,
  43696. attributes: {},
  43697. index: null
  43698. };
  43699. }
  43700. function needsUpdate( object, geometry, program, index ) {
  43701. const cachedAttributes = currentState.attributes;
  43702. const geometryAttributes = geometry.attributes;
  43703. let attributesNum = 0;
  43704. const programAttributes = program.getAttributes();
  43705. for ( const name in programAttributes ) {
  43706. const programAttribute = programAttributes[ name ];
  43707. if ( programAttribute.location >= 0 ) {
  43708. const cachedAttribute = cachedAttributes[ name ];
  43709. let geometryAttribute = geometryAttributes[ name ];
  43710. if ( geometryAttribute === undefined ) {
  43711. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  43712. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  43713. }
  43714. if ( cachedAttribute === undefined ) return true;
  43715. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  43716. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  43717. attributesNum ++;
  43718. }
  43719. }
  43720. if ( currentState.attributesNum !== attributesNum ) return true;
  43721. if ( currentState.index !== index ) return true;
  43722. return false;
  43723. }
  43724. function saveCache( object, geometry, program, index ) {
  43725. const cache = {};
  43726. const attributes = geometry.attributes;
  43727. let attributesNum = 0;
  43728. const programAttributes = program.getAttributes();
  43729. for ( const name in programAttributes ) {
  43730. const programAttribute = programAttributes[ name ];
  43731. if ( programAttribute.location >= 0 ) {
  43732. let attribute = attributes[ name ];
  43733. if ( attribute === undefined ) {
  43734. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  43735. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  43736. }
  43737. const data = {};
  43738. data.attribute = attribute;
  43739. if ( attribute && attribute.data ) {
  43740. data.data = attribute.data;
  43741. }
  43742. cache[ name ] = data;
  43743. attributesNum ++;
  43744. }
  43745. }
  43746. currentState.attributes = cache;
  43747. currentState.attributesNum = attributesNum;
  43748. currentState.index = index;
  43749. }
  43750. function initAttributes() {
  43751. const newAttributes = currentState.newAttributes;
  43752. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  43753. newAttributes[ i ] = 0;
  43754. }
  43755. }
  43756. function enableAttribute( attribute ) {
  43757. enableAttributeAndDivisor( attribute, 0 );
  43758. }
  43759. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  43760. const newAttributes = currentState.newAttributes;
  43761. const enabledAttributes = currentState.enabledAttributes;
  43762. const attributeDivisors = currentState.attributeDivisors;
  43763. newAttributes[ attribute ] = 1;
  43764. if ( enabledAttributes[ attribute ] === 0 ) {
  43765. gl.enableVertexAttribArray( attribute );
  43766. enabledAttributes[ attribute ] = 1;
  43767. }
  43768. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  43769. gl.vertexAttribDivisor( attribute, meshPerAttribute );
  43770. attributeDivisors[ attribute ] = meshPerAttribute;
  43771. }
  43772. }
  43773. function disableUnusedAttributes() {
  43774. const newAttributes = currentState.newAttributes;
  43775. const enabledAttributes = currentState.enabledAttributes;
  43776. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  43777. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  43778. gl.disableVertexAttribArray( i );
  43779. enabledAttributes[ i ] = 0;
  43780. }
  43781. }
  43782. }
  43783. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  43784. if ( integer === true ) {
  43785. gl.vertexAttribIPointer( index, size, type, stride, offset );
  43786. } else {
  43787. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  43788. }
  43789. }
  43790. function setupVertexAttributes( object, material, program, geometry ) {
  43791. initAttributes();
  43792. const geometryAttributes = geometry.attributes;
  43793. const programAttributes = program.getAttributes();
  43794. const materialDefaultAttributeValues = material.defaultAttributeValues;
  43795. for ( const name in programAttributes ) {
  43796. const programAttribute = programAttributes[ name ];
  43797. if ( programAttribute.location >= 0 ) {
  43798. let geometryAttribute = geometryAttributes[ name ];
  43799. if ( geometryAttribute === undefined ) {
  43800. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  43801. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  43802. }
  43803. if ( geometryAttribute !== undefined ) {
  43804. const normalized = geometryAttribute.normalized;
  43805. const size = geometryAttribute.itemSize;
  43806. const attribute = attributes.get( geometryAttribute );
  43807. // TODO Attribute may not be available on context restore
  43808. if ( attribute === undefined ) continue;
  43809. const buffer = attribute.buffer;
  43810. const type = attribute.type;
  43811. const bytesPerElement = attribute.bytesPerElement;
  43812. // check for integer attributes
  43813. const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType );
  43814. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  43815. const data = geometryAttribute.data;
  43816. const stride = data.stride;
  43817. const offset = geometryAttribute.offset;
  43818. if ( data.isInstancedInterleavedBuffer ) {
  43819. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43820. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  43821. }
  43822. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  43823. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  43824. }
  43825. } else {
  43826. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43827. enableAttribute( programAttribute.location + i );
  43828. }
  43829. }
  43830. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  43831. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43832. vertexAttribPointer(
  43833. programAttribute.location + i,
  43834. size / programAttribute.locationSize,
  43835. type,
  43836. normalized,
  43837. stride * bytesPerElement,
  43838. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  43839. integer
  43840. );
  43841. }
  43842. } else {
  43843. if ( geometryAttribute.isInstancedBufferAttribute ) {
  43844. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43845. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  43846. }
  43847. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  43848. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  43849. }
  43850. } else {
  43851. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43852. enableAttribute( programAttribute.location + i );
  43853. }
  43854. }
  43855. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  43856. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43857. vertexAttribPointer(
  43858. programAttribute.location + i,
  43859. size / programAttribute.locationSize,
  43860. type,
  43861. normalized,
  43862. size * bytesPerElement,
  43863. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  43864. integer
  43865. );
  43866. }
  43867. }
  43868. } else if ( materialDefaultAttributeValues !== undefined ) {
  43869. const value = materialDefaultAttributeValues[ name ];
  43870. if ( value !== undefined ) {
  43871. switch ( value.length ) {
  43872. case 2:
  43873. gl.vertexAttrib2fv( programAttribute.location, value );
  43874. break;
  43875. case 3:
  43876. gl.vertexAttrib3fv( programAttribute.location, value );
  43877. break;
  43878. case 4:
  43879. gl.vertexAttrib4fv( programAttribute.location, value );
  43880. break;
  43881. default:
  43882. gl.vertexAttrib1fv( programAttribute.location, value );
  43883. }
  43884. }
  43885. }
  43886. }
  43887. }
  43888. disableUnusedAttributes();
  43889. }
  43890. function dispose() {
  43891. reset();
  43892. for ( const geometryId in bindingStates ) {
  43893. const programMap = bindingStates[ geometryId ];
  43894. for ( const programId in programMap ) {
  43895. const stateMap = programMap[ programId ];
  43896. for ( const wireframe in stateMap ) {
  43897. deleteVertexArrayObject( stateMap[ wireframe ].object );
  43898. delete stateMap[ wireframe ];
  43899. }
  43900. delete programMap[ programId ];
  43901. }
  43902. delete bindingStates[ geometryId ];
  43903. }
  43904. }
  43905. function releaseStatesOfGeometry( geometry ) {
  43906. if ( bindingStates[ geometry.id ] === undefined ) return;
  43907. const programMap = bindingStates[ geometry.id ];
  43908. for ( const programId in programMap ) {
  43909. const stateMap = programMap[ programId ];
  43910. for ( const wireframe in stateMap ) {
  43911. deleteVertexArrayObject( stateMap[ wireframe ].object );
  43912. delete stateMap[ wireframe ];
  43913. }
  43914. delete programMap[ programId ];
  43915. }
  43916. delete bindingStates[ geometry.id ];
  43917. }
  43918. function releaseStatesOfProgram( program ) {
  43919. for ( const geometryId in bindingStates ) {
  43920. const programMap = bindingStates[ geometryId ];
  43921. if ( programMap[ program.id ] === undefined ) continue;
  43922. const stateMap = programMap[ program.id ];
  43923. for ( const wireframe in stateMap ) {
  43924. deleteVertexArrayObject( stateMap[ wireframe ].object );
  43925. delete stateMap[ wireframe ];
  43926. }
  43927. delete programMap[ program.id ];
  43928. }
  43929. }
  43930. function reset() {
  43931. resetDefaultState();
  43932. forceUpdate = true;
  43933. if ( currentState === defaultState ) return;
  43934. currentState = defaultState;
  43935. bindVertexArrayObject( currentState.object );
  43936. }
  43937. // for backward-compatibility
  43938. function resetDefaultState() {
  43939. defaultState.geometry = null;
  43940. defaultState.program = null;
  43941. defaultState.wireframe = false;
  43942. }
  43943. return {
  43944. setup: setup,
  43945. reset: reset,
  43946. resetDefaultState: resetDefaultState,
  43947. dispose: dispose,
  43948. releaseStatesOfGeometry: releaseStatesOfGeometry,
  43949. releaseStatesOfProgram: releaseStatesOfProgram,
  43950. initAttributes: initAttributes,
  43951. enableAttribute: enableAttribute,
  43952. disableUnusedAttributes: disableUnusedAttributes
  43953. };
  43954. }
  43955. function WebGLBufferRenderer( gl, extensions, info ) {
  43956. let mode;
  43957. function setMode( value ) {
  43958. mode = value;
  43959. }
  43960. function render( start, count ) {
  43961. gl.drawArrays( mode, start, count );
  43962. info.update( count, mode, 1 );
  43963. }
  43964. function renderInstances( start, count, primcount ) {
  43965. if ( primcount === 0 ) return;
  43966. gl.drawArraysInstanced( mode, start, count, primcount );
  43967. info.update( count, mode, primcount );
  43968. }
  43969. function renderMultiDraw( starts, counts, drawCount ) {
  43970. if ( drawCount === 0 ) return;
  43971. const extension = extensions.get( 'WEBGL_multi_draw' );
  43972. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  43973. let elementCount = 0;
  43974. for ( let i = 0; i < drawCount; i ++ ) {
  43975. elementCount += counts[ i ];
  43976. }
  43977. info.update( elementCount, mode, 1 );
  43978. }
  43979. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  43980. if ( drawCount === 0 ) return;
  43981. const extension = extensions.get( 'WEBGL_multi_draw' );
  43982. if ( extension === null ) {
  43983. for ( let i = 0; i < starts.length; i ++ ) {
  43984. renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  43985. }
  43986. } else {
  43987. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  43988. let elementCount = 0;
  43989. for ( let i = 0; i < drawCount; i ++ ) {
  43990. elementCount += counts[ i ] * primcount[ i ];
  43991. }
  43992. info.update( elementCount, mode, 1 );
  43993. }
  43994. }
  43995. //
  43996. this.setMode = setMode;
  43997. this.render = render;
  43998. this.renderInstances = renderInstances;
  43999. this.renderMultiDraw = renderMultiDraw;
  44000. this.renderMultiDrawInstances = renderMultiDrawInstances;
  44001. }
  44002. function WebGLCapabilities( gl, extensions, parameters, utils ) {
  44003. let maxAnisotropy;
  44004. function getMaxAnisotropy() {
  44005. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  44006. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  44007. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  44008. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  44009. } else {
  44010. maxAnisotropy = 0;
  44011. }
  44012. return maxAnisotropy;
  44013. }
  44014. function textureFormatReadable( textureFormat ) {
  44015. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  44016. return false;
  44017. }
  44018. return true;
  44019. }
  44020. function textureTypeReadable( textureType ) {
  44021. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) );
  44022. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  44023. textureType !== FloatType && ! halfFloatSupportedByExt ) {
  44024. return false;
  44025. }
  44026. return true;
  44027. }
  44028. function getMaxPrecision( precision ) {
  44029. if ( precision === 'highp' ) {
  44030. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  44031. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  44032. return 'highp';
  44033. }
  44034. precision = 'mediump';
  44035. }
  44036. if ( precision === 'mediump' ) {
  44037. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  44038. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  44039. return 'mediump';
  44040. }
  44041. }
  44042. return 'lowp';
  44043. }
  44044. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  44045. const maxPrecision = getMaxPrecision( precision );
  44046. if ( maxPrecision !== precision ) {
  44047. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  44048. precision = maxPrecision;
  44049. }
  44050. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  44051. const reversedDepthBuffer = parameters.reversedDepthBuffer === true && extensions.has( 'EXT_clip_control' );
  44052. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  44053. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  44054. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  44055. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  44056. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  44057. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  44058. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  44059. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  44060. const vertexTextures = maxVertexTextures > 0;
  44061. const maxSamples = gl.getParameter( gl.MAX_SAMPLES );
  44062. return {
  44063. isWebGL2: true, // keeping this for backwards compatibility
  44064. getMaxAnisotropy: getMaxAnisotropy,
  44065. getMaxPrecision: getMaxPrecision,
  44066. textureFormatReadable: textureFormatReadable,
  44067. textureTypeReadable: textureTypeReadable,
  44068. precision: precision,
  44069. logarithmicDepthBuffer: logarithmicDepthBuffer,
  44070. reversedDepthBuffer: reversedDepthBuffer,
  44071. maxTextures: maxTextures,
  44072. maxVertexTextures: maxVertexTextures,
  44073. maxTextureSize: maxTextureSize,
  44074. maxCubemapSize: maxCubemapSize,
  44075. maxAttributes: maxAttributes,
  44076. maxVertexUniforms: maxVertexUniforms,
  44077. maxVaryings: maxVaryings,
  44078. maxFragmentUniforms: maxFragmentUniforms,
  44079. vertexTextures: vertexTextures,
  44080. maxSamples: maxSamples
  44081. };
  44082. }
  44083. function WebGLClipping( properties ) {
  44084. const scope = this;
  44085. let globalState = null,
  44086. numGlobalPlanes = 0,
  44087. localClippingEnabled = false,
  44088. renderingShadows = false;
  44089. const plane = new Plane(),
  44090. viewNormalMatrix = new Matrix3(),
  44091. uniform = { value: null, needsUpdate: false };
  44092. this.uniform = uniform;
  44093. this.numPlanes = 0;
  44094. this.numIntersection = 0;
  44095. this.init = function ( planes, enableLocalClipping ) {
  44096. const enabled =
  44097. planes.length !== 0 ||
  44098. enableLocalClipping ||
  44099. // enable state of previous frame - the clipping code has to
  44100. // run another frame in order to reset the state:
  44101. numGlobalPlanes !== 0 ||
  44102. localClippingEnabled;
  44103. localClippingEnabled = enableLocalClipping;
  44104. numGlobalPlanes = planes.length;
  44105. return enabled;
  44106. };
  44107. this.beginShadows = function () {
  44108. renderingShadows = true;
  44109. projectPlanes( null );
  44110. };
  44111. this.endShadows = function () {
  44112. renderingShadows = false;
  44113. };
  44114. this.setGlobalState = function ( planes, camera ) {
  44115. globalState = projectPlanes( planes, camera, 0 );
  44116. };
  44117. this.setState = function ( material, camera, useCache ) {
  44118. const planes = material.clippingPlanes,
  44119. clipIntersection = material.clipIntersection,
  44120. clipShadows = material.clipShadows;
  44121. const materialProperties = properties.get( material );
  44122. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  44123. // there's no local clipping
  44124. if ( renderingShadows ) {
  44125. // there's no global clipping
  44126. projectPlanes( null );
  44127. } else {
  44128. resetGlobalState();
  44129. }
  44130. } else {
  44131. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  44132. lGlobal = nGlobal * 4;
  44133. let dstArray = materialProperties.clippingState || null;
  44134. uniform.value = dstArray; // ensure unique state
  44135. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  44136. for ( let i = 0; i !== lGlobal; ++ i ) {
  44137. dstArray[ i ] = globalState[ i ];
  44138. }
  44139. materialProperties.clippingState = dstArray;
  44140. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  44141. this.numPlanes += nGlobal;
  44142. }
  44143. };
  44144. function resetGlobalState() {
  44145. if ( uniform.value !== globalState ) {
  44146. uniform.value = globalState;
  44147. uniform.needsUpdate = numGlobalPlanes > 0;
  44148. }
  44149. scope.numPlanes = numGlobalPlanes;
  44150. scope.numIntersection = 0;
  44151. }
  44152. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  44153. const nPlanes = planes !== null ? planes.length : 0;
  44154. let dstArray = null;
  44155. if ( nPlanes !== 0 ) {
  44156. dstArray = uniform.value;
  44157. if ( skipTransform !== true || dstArray === null ) {
  44158. const flatSize = dstOffset + nPlanes * 4,
  44159. viewMatrix = camera.matrixWorldInverse;
  44160. viewNormalMatrix.getNormalMatrix( viewMatrix );
  44161. if ( dstArray === null || dstArray.length < flatSize ) {
  44162. dstArray = new Float32Array( flatSize );
  44163. }
  44164. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  44165. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  44166. plane.normal.toArray( dstArray, i4 );
  44167. dstArray[ i4 + 3 ] = plane.constant;
  44168. }
  44169. }
  44170. uniform.value = dstArray;
  44171. uniform.needsUpdate = true;
  44172. }
  44173. scope.numPlanes = nPlanes;
  44174. scope.numIntersection = 0;
  44175. return dstArray;
  44176. }
  44177. }
  44178. function WebGLCubeMaps( renderer ) {
  44179. let cubemaps = new WeakMap();
  44180. function mapTextureMapping( texture, mapping ) {
  44181. if ( mapping === EquirectangularReflectionMapping ) {
  44182. texture.mapping = CubeReflectionMapping;
  44183. } else if ( mapping === EquirectangularRefractionMapping ) {
  44184. texture.mapping = CubeRefractionMapping;
  44185. }
  44186. return texture;
  44187. }
  44188. function get( texture ) {
  44189. if ( texture && texture.isTexture ) {
  44190. const mapping = texture.mapping;
  44191. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  44192. if ( cubemaps.has( texture ) ) {
  44193. const cubemap = cubemaps.get( texture ).texture;
  44194. return mapTextureMapping( cubemap, texture.mapping );
  44195. } else {
  44196. const image = texture.image;
  44197. if ( image && image.height > 0 ) {
  44198. const renderTarget = new WebGLCubeRenderTarget( image.height );
  44199. renderTarget.fromEquirectangularTexture( renderer, texture );
  44200. cubemaps.set( texture, renderTarget );
  44201. texture.addEventListener( 'dispose', onTextureDispose );
  44202. return mapTextureMapping( renderTarget.texture, texture.mapping );
  44203. } else {
  44204. // image not yet ready. try the conversion next frame
  44205. return null;
  44206. }
  44207. }
  44208. }
  44209. }
  44210. return texture;
  44211. }
  44212. function onTextureDispose( event ) {
  44213. const texture = event.target;
  44214. texture.removeEventListener( 'dispose', onTextureDispose );
  44215. const cubemap = cubemaps.get( texture );
  44216. if ( cubemap !== undefined ) {
  44217. cubemaps.delete( texture );
  44218. cubemap.dispose();
  44219. }
  44220. }
  44221. function dispose() {
  44222. cubemaps = new WeakMap();
  44223. }
  44224. return {
  44225. get: get,
  44226. dispose: dispose
  44227. };
  44228. }
  44229. const LOD_MIN = 4;
  44230. // The standard deviations (radians) associated with the extra mips. These are
  44231. // chosen to approximate a Trowbridge-Reitz distribution function times the
  44232. // geometric shadowing function. These sigma values squared must match the
  44233. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  44234. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  44235. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  44236. // samples and exit early, but not recompile the shader.
  44237. const MAX_SAMPLES = 20;
  44238. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  44239. const _clearColor = /*@__PURE__*/ new Color();
  44240. let _oldTarget = null;
  44241. let _oldActiveCubeFace = 0;
  44242. let _oldActiveMipmapLevel = 0;
  44243. let _oldXrEnabled = false;
  44244. // Golden Ratio
  44245. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  44246. const INV_PHI = 1 / PHI;
  44247. // Vertices of a dodecahedron (except the opposites, which represent the
  44248. // same axis), used as axis directions evenly spread on a sphere.
  44249. const _axisDirections = [
  44250. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  44251. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  44252. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  44253. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  44254. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  44255. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  44256. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  44257. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  44258. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  44259. /*@__PURE__*/ new Vector3( 1, 1, 1 ) ];
  44260. const _origin = /*@__PURE__*/ new Vector3();
  44261. /**
  44262. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  44263. * (PMREM) from a cubeMap environment texture. This allows different levels of
  44264. * blur to be quickly accessed based on material roughness. It is packed into a
  44265. * special CubeUV format that allows us to perform custom interpolation so that
  44266. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  44267. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  44268. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  44269. * higher roughness levels. In this way we maintain resolution to smoothly
  44270. * interpolate diffuse lighting while limiting sampling computation.
  44271. *
  44272. * Paper: Fast, Accurate Image-Based Lighting:
  44273. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  44274. */
  44275. class PMREMGenerator {
  44276. /**
  44277. * Constructs a new PMREM generator.
  44278. *
  44279. * @param {WebGLRenderer} renderer - The renderer.
  44280. */
  44281. constructor( renderer ) {
  44282. this._renderer = renderer;
  44283. this._pingPongRenderTarget = null;
  44284. this._lodMax = 0;
  44285. this._cubeSize = 0;
  44286. this._lodPlanes = [];
  44287. this._sizeLods = [];
  44288. this._sigmas = [];
  44289. this._blurMaterial = null;
  44290. this._cubemapMaterial = null;
  44291. this._equirectMaterial = null;
  44292. this._compileMaterial( this._blurMaterial );
  44293. }
  44294. /**
  44295. * Generates a PMREM from a supplied Scene, which can be faster than using an
  44296. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  44297. * in radians to be applied to the scene before PMREM generation. Optional near
  44298. * and far planes ensure the scene is rendered in its entirety.
  44299. *
  44300. * @param {Scene} scene - The scene to be captured.
  44301. * @param {number} [sigma=0] - The blur radius in radians.
  44302. * @param {number} [near=0.1] - The near plane distance.
  44303. * @param {number} [far=100] - The far plane distance.
  44304. * @param {Object} [options={}] - The configuration options.
  44305. * @param {number} [options.size=256] - The texture size of the PMREM.
  44306. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  44307. * @return {WebGLRenderTarget} The resulting PMREM.
  44308. */
  44309. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  44310. const {
  44311. size = 256,
  44312. position = _origin,
  44313. } = options;
  44314. _oldTarget = this._renderer.getRenderTarget();
  44315. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  44316. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  44317. _oldXrEnabled = this._renderer.xr.enabled;
  44318. this._renderer.xr.enabled = false;
  44319. this._setSize( size );
  44320. const cubeUVRenderTarget = this._allocateTargets();
  44321. cubeUVRenderTarget.depthBuffer = true;
  44322. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  44323. if ( sigma > 0 ) {
  44324. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  44325. }
  44326. this._applyPMREM( cubeUVRenderTarget );
  44327. this._cleanup( cubeUVRenderTarget );
  44328. return cubeUVRenderTarget;
  44329. }
  44330. /**
  44331. * Generates a PMREM from an equirectangular texture, which can be either LDR
  44332. * or HDR. The ideal input image size is 1k (1024 x 512),
  44333. * as this matches best with the 256 x 256 cubemap output.
  44334. *
  44335. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  44336. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  44337. * @return {WebGLRenderTarget} The resulting PMREM.
  44338. */
  44339. fromEquirectangular( equirectangular, renderTarget = null ) {
  44340. return this._fromTexture( equirectangular, renderTarget );
  44341. }
  44342. /**
  44343. * Generates a PMREM from an cubemap texture, which can be either LDR
  44344. * or HDR. The ideal input cube size is 256 x 256,
  44345. * as this matches best with the 256 x 256 cubemap output.
  44346. *
  44347. * @param {Texture} cubemap - The cubemap texture to be converted.
  44348. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  44349. * @return {WebGLRenderTarget} The resulting PMREM.
  44350. */
  44351. fromCubemap( cubemap, renderTarget = null ) {
  44352. return this._fromTexture( cubemap, renderTarget );
  44353. }
  44354. /**
  44355. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  44356. * your texture's network fetch for increased concurrency.
  44357. */
  44358. compileCubemapShader() {
  44359. if ( this._cubemapMaterial === null ) {
  44360. this._cubemapMaterial = _getCubemapMaterial();
  44361. this._compileMaterial( this._cubemapMaterial );
  44362. }
  44363. }
  44364. /**
  44365. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  44366. * your texture's network fetch for increased concurrency.
  44367. */
  44368. compileEquirectangularShader() {
  44369. if ( this._equirectMaterial === null ) {
  44370. this._equirectMaterial = _getEquirectMaterial();
  44371. this._compileMaterial( this._equirectMaterial );
  44372. }
  44373. }
  44374. /**
  44375. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  44376. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  44377. * one of them will cause any others to also become unusable.
  44378. */
  44379. dispose() {
  44380. this._dispose();
  44381. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  44382. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  44383. }
  44384. // private interface
  44385. _setSize( cubeSize ) {
  44386. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  44387. this._cubeSize = Math.pow( 2, this._lodMax );
  44388. }
  44389. _dispose() {
  44390. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  44391. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  44392. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  44393. this._lodPlanes[ i ].dispose();
  44394. }
  44395. }
  44396. _cleanup( outputTarget ) {
  44397. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  44398. this._renderer.xr.enabled = _oldXrEnabled;
  44399. outputTarget.scissorTest = false;
  44400. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  44401. }
  44402. _fromTexture( texture, renderTarget ) {
  44403. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  44404. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  44405. } else { // Equirectangular
  44406. this._setSize( texture.image.width / 4 );
  44407. }
  44408. _oldTarget = this._renderer.getRenderTarget();
  44409. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  44410. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  44411. _oldXrEnabled = this._renderer.xr.enabled;
  44412. this._renderer.xr.enabled = false;
  44413. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  44414. this._textureToCubeUV( texture, cubeUVRenderTarget );
  44415. this._applyPMREM( cubeUVRenderTarget );
  44416. this._cleanup( cubeUVRenderTarget );
  44417. return cubeUVRenderTarget;
  44418. }
  44419. _allocateTargets() {
  44420. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  44421. const height = 4 * this._cubeSize;
  44422. const params = {
  44423. magFilter: LinearFilter,
  44424. minFilter: LinearFilter,
  44425. generateMipmaps: false,
  44426. type: HalfFloatType,
  44427. format: RGBAFormat,
  44428. colorSpace: LinearSRGBColorSpace,
  44429. depthBuffer: false
  44430. };
  44431. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  44432. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  44433. if ( this._pingPongRenderTarget !== null ) {
  44434. this._dispose();
  44435. }
  44436. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  44437. const { _lodMax } = this;
  44438. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  44439. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  44440. }
  44441. return cubeUVRenderTarget;
  44442. }
  44443. _compileMaterial( material ) {
  44444. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  44445. this._renderer.compile( tmpMesh, _flatCamera );
  44446. }
  44447. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  44448. const fov = 90;
  44449. const aspect = 1;
  44450. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  44451. const upSign = [ 1, -1, 1, 1, 1, 1 ];
  44452. const forwardSign = [ 1, 1, 1, -1, -1, -1 ];
  44453. const renderer = this._renderer;
  44454. const originalAutoClear = renderer.autoClear;
  44455. const toneMapping = renderer.toneMapping;
  44456. renderer.getClearColor( _clearColor );
  44457. renderer.toneMapping = NoToneMapping;
  44458. renderer.autoClear = false;
  44459. // https://github.com/mrdoob/three.js/issues/31413#issuecomment-3095966812
  44460. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  44461. if ( reversedDepthBuffer ) {
  44462. renderer.setRenderTarget( cubeUVRenderTarget );
  44463. renderer.clearDepth();
  44464. renderer.setRenderTarget( null );
  44465. }
  44466. const backgroundMaterial = new MeshBasicMaterial( {
  44467. name: 'PMREM.Background',
  44468. side: BackSide,
  44469. depthWrite: false,
  44470. depthTest: false,
  44471. } );
  44472. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  44473. let useSolidColor = false;
  44474. const background = scene.background;
  44475. if ( background ) {
  44476. if ( background.isColor ) {
  44477. backgroundMaterial.color.copy( background );
  44478. scene.background = null;
  44479. useSolidColor = true;
  44480. }
  44481. } else {
  44482. backgroundMaterial.color.copy( _clearColor );
  44483. useSolidColor = true;
  44484. }
  44485. for ( let i = 0; i < 6; i ++ ) {
  44486. const col = i % 3;
  44487. if ( col === 0 ) {
  44488. cubeCamera.up.set( 0, upSign[ i ], 0 );
  44489. cubeCamera.position.set( position.x, position.y, position.z );
  44490. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  44491. } else if ( col === 1 ) {
  44492. cubeCamera.up.set( 0, 0, upSign[ i ] );
  44493. cubeCamera.position.set( position.x, position.y, position.z );
  44494. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  44495. } else {
  44496. cubeCamera.up.set( 0, upSign[ i ], 0 );
  44497. cubeCamera.position.set( position.x, position.y, position.z );
  44498. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  44499. }
  44500. const size = this._cubeSize;
  44501. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  44502. renderer.setRenderTarget( cubeUVRenderTarget );
  44503. if ( useSolidColor ) {
  44504. renderer.render( backgroundBox, cubeCamera );
  44505. }
  44506. renderer.render( scene, cubeCamera );
  44507. }
  44508. backgroundBox.geometry.dispose();
  44509. backgroundBox.material.dispose();
  44510. renderer.toneMapping = toneMapping;
  44511. renderer.autoClear = originalAutoClear;
  44512. scene.background = background;
  44513. }
  44514. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  44515. const renderer = this._renderer;
  44516. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  44517. if ( isCubeTexture ) {
  44518. if ( this._cubemapMaterial === null ) {
  44519. this._cubemapMaterial = _getCubemapMaterial();
  44520. }
  44521. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? -1 : 1;
  44522. } else {
  44523. if ( this._equirectMaterial === null ) {
  44524. this._equirectMaterial = _getEquirectMaterial();
  44525. }
  44526. }
  44527. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  44528. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  44529. const uniforms = material.uniforms;
  44530. uniforms[ 'envMap' ].value = texture;
  44531. const size = this._cubeSize;
  44532. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  44533. renderer.setRenderTarget( cubeUVRenderTarget );
  44534. renderer.render( mesh, _flatCamera );
  44535. }
  44536. _applyPMREM( cubeUVRenderTarget ) {
  44537. const renderer = this._renderer;
  44538. const autoClear = renderer.autoClear;
  44539. renderer.autoClear = false;
  44540. const n = this._lodPlanes.length;
  44541. for ( let i = 1; i < n; i ++ ) {
  44542. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  44543. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  44544. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  44545. }
  44546. renderer.autoClear = autoClear;
  44547. }
  44548. /**
  44549. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  44550. * vertically and horizontally, but this breaks down on a cube. Here we apply
  44551. * the blur latitudinally (around the poles), and then longitudinally (towards
  44552. * the poles) to approximate the orthogonally-separable blur. It is least
  44553. * accurate at the poles, but still does a decent job.
  44554. *
  44555. * @private
  44556. * @param {WebGLRenderTarget} cubeUVRenderTarget
  44557. * @param {number} lodIn
  44558. * @param {number} lodOut
  44559. * @param {number} sigma
  44560. * @param {Vector3} [poleAxis]
  44561. */
  44562. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  44563. const pingPongRenderTarget = this._pingPongRenderTarget;
  44564. this._halfBlur(
  44565. cubeUVRenderTarget,
  44566. pingPongRenderTarget,
  44567. lodIn,
  44568. lodOut,
  44569. sigma,
  44570. 'latitudinal',
  44571. poleAxis );
  44572. this._halfBlur(
  44573. pingPongRenderTarget,
  44574. cubeUVRenderTarget,
  44575. lodOut,
  44576. lodOut,
  44577. sigma,
  44578. 'longitudinal',
  44579. poleAxis );
  44580. }
  44581. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  44582. const renderer = this._renderer;
  44583. const blurMaterial = this._blurMaterial;
  44584. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  44585. console.error(
  44586. 'blur direction must be either latitudinal or longitudinal!' );
  44587. }
  44588. // Number of standard deviations at which to cut off the discrete approximation.
  44589. const STANDARD_DEVIATIONS = 3;
  44590. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  44591. const blurUniforms = blurMaterial.uniforms;
  44592. const pixels = this._sizeLods[ lodIn ] - 1;
  44593. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  44594. const sigmaPixels = sigmaRadians / radiansPerPixel;
  44595. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  44596. if ( samples > MAX_SAMPLES ) {
  44597. console.warn( `sigmaRadians, ${
  44598. sigmaRadians}, is too large and will clip, as it requested ${
  44599. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  44600. }
  44601. const weights = [];
  44602. let sum = 0;
  44603. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  44604. const x = i / sigmaPixels;
  44605. const weight = Math.exp( - x * x / 2 );
  44606. weights.push( weight );
  44607. if ( i === 0 ) {
  44608. sum += weight;
  44609. } else if ( i < samples ) {
  44610. sum += 2 * weight;
  44611. }
  44612. }
  44613. for ( let i = 0; i < weights.length; i ++ ) {
  44614. weights[ i ] = weights[ i ] / sum;
  44615. }
  44616. blurUniforms[ 'envMap' ].value = targetIn.texture;
  44617. blurUniforms[ 'samples' ].value = samples;
  44618. blurUniforms[ 'weights' ].value = weights;
  44619. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  44620. if ( poleAxis ) {
  44621. blurUniforms[ 'poleAxis' ].value = poleAxis;
  44622. }
  44623. const { _lodMax } = this;
  44624. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  44625. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  44626. const outputSize = this._sizeLods[ lodOut ];
  44627. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  44628. const y = 4 * ( this._cubeSize - outputSize );
  44629. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  44630. renderer.setRenderTarget( targetOut );
  44631. renderer.render( blurMesh, _flatCamera );
  44632. }
  44633. }
  44634. function _createPlanes( lodMax ) {
  44635. const lodPlanes = [];
  44636. const sizeLods = [];
  44637. const sigmas = [];
  44638. let lod = lodMax;
  44639. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  44640. for ( let i = 0; i < totalLods; i ++ ) {
  44641. const sizeLod = Math.pow( 2, lod );
  44642. sizeLods.push( sizeLod );
  44643. let sigma = 1.0 / sizeLod;
  44644. if ( i > lodMax - LOD_MIN ) {
  44645. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  44646. } else if ( i === 0 ) {
  44647. sigma = 0;
  44648. }
  44649. sigmas.push( sigma );
  44650. const texelSize = 1.0 / ( sizeLod - 2 );
  44651. const min = - texelSize;
  44652. const max = 1 + texelSize;
  44653. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  44654. const cubeFaces = 6;
  44655. const vertices = 6;
  44656. const positionSize = 3;
  44657. const uvSize = 2;
  44658. const faceIndexSize = 1;
  44659. const position = new Float32Array( positionSize * vertices * cubeFaces );
  44660. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  44661. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  44662. for ( let face = 0; face < cubeFaces; face ++ ) {
  44663. const x = ( face % 3 ) * 2 / 3 - 1;
  44664. const y = face > 2 ? 0 : -1;
  44665. const coordinates = [
  44666. x, y, 0,
  44667. x + 2 / 3, y, 0,
  44668. x + 2 / 3, y + 1, 0,
  44669. x, y, 0,
  44670. x + 2 / 3, y + 1, 0,
  44671. x, y + 1, 0
  44672. ];
  44673. position.set( coordinates, positionSize * vertices * face );
  44674. uv.set( uv1, uvSize * vertices * face );
  44675. const fill = [ face, face, face, face, face, face ];
  44676. faceIndex.set( fill, faceIndexSize * vertices * face );
  44677. }
  44678. const planes = new BufferGeometry();
  44679. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  44680. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  44681. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  44682. lodPlanes.push( planes );
  44683. if ( lod > LOD_MIN ) {
  44684. lod --;
  44685. }
  44686. }
  44687. return { lodPlanes, sizeLods, sigmas };
  44688. }
  44689. function _createRenderTarget( width, height, params ) {
  44690. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  44691. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  44692. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  44693. cubeUVRenderTarget.scissorTest = true;
  44694. return cubeUVRenderTarget;
  44695. }
  44696. function _setViewport( target, x, y, width, height ) {
  44697. target.viewport.set( x, y, width, height );
  44698. target.scissor.set( x, y, width, height );
  44699. }
  44700. function _getBlurShader( lodMax, width, height ) {
  44701. const weights = new Float32Array( MAX_SAMPLES );
  44702. const poleAxis = new Vector3( 0, 1, 0 );
  44703. const shaderMaterial = new ShaderMaterial( {
  44704. name: 'SphericalGaussianBlur',
  44705. defines: {
  44706. 'n': MAX_SAMPLES,
  44707. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  44708. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  44709. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  44710. },
  44711. uniforms: {
  44712. 'envMap': { value: null },
  44713. 'samples': { value: 1 },
  44714. 'weights': { value: weights },
  44715. 'latitudinal': { value: false },
  44716. 'dTheta': { value: 0 },
  44717. 'mipInt': { value: 0 },
  44718. 'poleAxis': { value: poleAxis }
  44719. },
  44720. vertexShader: _getCommonVertexShader(),
  44721. fragmentShader: /* glsl */`
  44722. precision mediump float;
  44723. precision mediump int;
  44724. varying vec3 vOutputDirection;
  44725. uniform sampler2D envMap;
  44726. uniform int samples;
  44727. uniform float weights[ n ];
  44728. uniform bool latitudinal;
  44729. uniform float dTheta;
  44730. uniform float mipInt;
  44731. uniform vec3 poleAxis;
  44732. #define ENVMAP_TYPE_CUBE_UV
  44733. #include <cube_uv_reflection_fragment>
  44734. vec3 getSample( float theta, vec3 axis ) {
  44735. float cosTheta = cos( theta );
  44736. // Rodrigues' axis-angle rotation
  44737. vec3 sampleDirection = vOutputDirection * cosTheta
  44738. + cross( axis, vOutputDirection ) * sin( theta )
  44739. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  44740. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  44741. }
  44742. void main() {
  44743. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  44744. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  44745. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  44746. }
  44747. axis = normalize( axis );
  44748. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  44749. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  44750. for ( int i = 1; i < n; i++ ) {
  44751. if ( i >= samples ) {
  44752. break;
  44753. }
  44754. float theta = dTheta * float( i );
  44755. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  44756. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  44757. }
  44758. }
  44759. `,
  44760. blending: NoBlending,
  44761. depthTest: false,
  44762. depthWrite: false
  44763. } );
  44764. return shaderMaterial;
  44765. }
  44766. function _getEquirectMaterial() {
  44767. return new ShaderMaterial( {
  44768. name: 'EquirectangularToCubeUV',
  44769. uniforms: {
  44770. 'envMap': { value: null }
  44771. },
  44772. vertexShader: _getCommonVertexShader(),
  44773. fragmentShader: /* glsl */`
  44774. precision mediump float;
  44775. precision mediump int;
  44776. varying vec3 vOutputDirection;
  44777. uniform sampler2D envMap;
  44778. #include <common>
  44779. void main() {
  44780. vec3 outputDirection = normalize( vOutputDirection );
  44781. vec2 uv = equirectUv( outputDirection );
  44782. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  44783. }
  44784. `,
  44785. blending: NoBlending,
  44786. depthTest: false,
  44787. depthWrite: false
  44788. } );
  44789. }
  44790. function _getCubemapMaterial() {
  44791. return new ShaderMaterial( {
  44792. name: 'CubemapToCubeUV',
  44793. uniforms: {
  44794. 'envMap': { value: null },
  44795. 'flipEnvMap': { value: -1 }
  44796. },
  44797. vertexShader: _getCommonVertexShader(),
  44798. fragmentShader: /* glsl */`
  44799. precision mediump float;
  44800. precision mediump int;
  44801. uniform float flipEnvMap;
  44802. varying vec3 vOutputDirection;
  44803. uniform samplerCube envMap;
  44804. void main() {
  44805. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  44806. }
  44807. `,
  44808. blending: NoBlending,
  44809. depthTest: false,
  44810. depthWrite: false
  44811. } );
  44812. }
  44813. function _getCommonVertexShader() {
  44814. return /* glsl */`
  44815. precision mediump float;
  44816. precision mediump int;
  44817. attribute float faceIndex;
  44818. varying vec3 vOutputDirection;
  44819. // RH coordinate system; PMREM face-indexing convention
  44820. vec3 getDirection( vec2 uv, float face ) {
  44821. uv = 2.0 * uv - 1.0;
  44822. vec3 direction = vec3( uv, 1.0 );
  44823. if ( face == 0.0 ) {
  44824. direction = direction.zyx; // ( 1, v, u ) pos x
  44825. } else if ( face == 1.0 ) {
  44826. direction = direction.xzy;
  44827. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  44828. } else if ( face == 2.0 ) {
  44829. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  44830. } else if ( face == 3.0 ) {
  44831. direction = direction.zyx;
  44832. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  44833. } else if ( face == 4.0 ) {
  44834. direction = direction.xzy;
  44835. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  44836. } else if ( face == 5.0 ) {
  44837. direction.z *= -1.0; // ( u, v, -1 ) neg z
  44838. }
  44839. return direction;
  44840. }
  44841. void main() {
  44842. vOutputDirection = getDirection( uv, faceIndex );
  44843. gl_Position = vec4( position, 1.0 );
  44844. }
  44845. `;
  44846. }
  44847. function WebGLCubeUVMaps( renderer ) {
  44848. let cubeUVmaps = new WeakMap();
  44849. let pmremGenerator = null;
  44850. function get( texture ) {
  44851. if ( texture && texture.isTexture ) {
  44852. const mapping = texture.mapping;
  44853. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  44854. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  44855. // equirect/cube map to cubeUV conversion
  44856. if ( isEquirectMap || isCubeMap ) {
  44857. let renderTarget = cubeUVmaps.get( texture );
  44858. const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0;
  44859. if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) {
  44860. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  44861. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  44862. renderTarget.texture.pmremVersion = texture.pmremVersion;
  44863. cubeUVmaps.set( texture, renderTarget );
  44864. return renderTarget.texture;
  44865. } else {
  44866. if ( renderTarget !== undefined ) {
  44867. return renderTarget.texture;
  44868. } else {
  44869. const image = texture.image;
  44870. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  44871. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  44872. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  44873. renderTarget.texture.pmremVersion = texture.pmremVersion;
  44874. cubeUVmaps.set( texture, renderTarget );
  44875. texture.addEventListener( 'dispose', onTextureDispose );
  44876. return renderTarget.texture;
  44877. } else {
  44878. // image not yet ready. try the conversion next frame
  44879. return null;
  44880. }
  44881. }
  44882. }
  44883. }
  44884. }
  44885. return texture;
  44886. }
  44887. function isCubeTextureComplete( image ) {
  44888. let count = 0;
  44889. const length = 6;
  44890. for ( let i = 0; i < length; i ++ ) {
  44891. if ( image[ i ] !== undefined ) count ++;
  44892. }
  44893. return count === length;
  44894. }
  44895. function onTextureDispose( event ) {
  44896. const texture = event.target;
  44897. texture.removeEventListener( 'dispose', onTextureDispose );
  44898. const cubemapUV = cubeUVmaps.get( texture );
  44899. if ( cubemapUV !== undefined ) {
  44900. cubeUVmaps.delete( texture );
  44901. cubemapUV.dispose();
  44902. }
  44903. }
  44904. function dispose() {
  44905. cubeUVmaps = new WeakMap();
  44906. if ( pmremGenerator !== null ) {
  44907. pmremGenerator.dispose();
  44908. pmremGenerator = null;
  44909. }
  44910. }
  44911. return {
  44912. get: get,
  44913. dispose: dispose
  44914. };
  44915. }
  44916. function WebGLExtensions( gl ) {
  44917. const extensions = {};
  44918. function getExtension( name ) {
  44919. if ( extensions[ name ] !== undefined ) {
  44920. return extensions[ name ];
  44921. }
  44922. let extension;
  44923. switch ( name ) {
  44924. case 'WEBGL_depth_texture':
  44925. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  44926. break;
  44927. case 'EXT_texture_filter_anisotropic':
  44928. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  44929. break;
  44930. case 'WEBGL_compressed_texture_s3tc':
  44931. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  44932. break;
  44933. case 'WEBGL_compressed_texture_pvrtc':
  44934. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  44935. break;
  44936. default:
  44937. extension = gl.getExtension( name );
  44938. }
  44939. extensions[ name ] = extension;
  44940. return extension;
  44941. }
  44942. return {
  44943. has: function ( name ) {
  44944. return getExtension( name ) !== null;
  44945. },
  44946. init: function () {
  44947. getExtension( 'EXT_color_buffer_float' );
  44948. getExtension( 'WEBGL_clip_cull_distance' );
  44949. getExtension( 'OES_texture_float_linear' );
  44950. getExtension( 'EXT_color_buffer_half_float' );
  44951. getExtension( 'WEBGL_multisampled_render_to_texture' );
  44952. getExtension( 'WEBGL_render_shared_exponent' );
  44953. },
  44954. get: function ( name ) {
  44955. const extension = getExtension( name );
  44956. if ( extension === null ) {
  44957. warnOnce( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  44958. }
  44959. return extension;
  44960. }
  44961. };
  44962. }
  44963. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  44964. const geometries = {};
  44965. const wireframeAttributes = new WeakMap();
  44966. function onGeometryDispose( event ) {
  44967. const geometry = event.target;
  44968. if ( geometry.index !== null ) {
  44969. attributes.remove( geometry.index );
  44970. }
  44971. for ( const name in geometry.attributes ) {
  44972. attributes.remove( geometry.attributes[ name ] );
  44973. }
  44974. geometry.removeEventListener( 'dispose', onGeometryDispose );
  44975. delete geometries[ geometry.id ];
  44976. const attribute = wireframeAttributes.get( geometry );
  44977. if ( attribute ) {
  44978. attributes.remove( attribute );
  44979. wireframeAttributes.delete( geometry );
  44980. }
  44981. bindingStates.releaseStatesOfGeometry( geometry );
  44982. if ( geometry.isInstancedBufferGeometry === true ) {
  44983. delete geometry._maxInstanceCount;
  44984. }
  44985. //
  44986. info.memory.geometries --;
  44987. }
  44988. function get( object, geometry ) {
  44989. if ( geometries[ geometry.id ] === true ) return geometry;
  44990. geometry.addEventListener( 'dispose', onGeometryDispose );
  44991. geometries[ geometry.id ] = true;
  44992. info.memory.geometries ++;
  44993. return geometry;
  44994. }
  44995. function update( geometry ) {
  44996. const geometryAttributes = geometry.attributes;
  44997. // Updating index buffer in VAO now. See WebGLBindingStates.
  44998. for ( const name in geometryAttributes ) {
  44999. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  45000. }
  45001. }
  45002. function updateWireframeAttribute( geometry ) {
  45003. const indices = [];
  45004. const geometryIndex = geometry.index;
  45005. const geometryPosition = geometry.attributes.position;
  45006. let version = 0;
  45007. if ( geometryIndex !== null ) {
  45008. const array = geometryIndex.array;
  45009. version = geometryIndex.version;
  45010. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  45011. const a = array[ i + 0 ];
  45012. const b = array[ i + 1 ];
  45013. const c = array[ i + 2 ];
  45014. indices.push( a, b, b, c, c, a );
  45015. }
  45016. } else if ( geometryPosition !== undefined ) {
  45017. const array = geometryPosition.array;
  45018. version = geometryPosition.version;
  45019. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  45020. const a = i + 0;
  45021. const b = i + 1;
  45022. const c = i + 2;
  45023. indices.push( a, b, b, c, c, a );
  45024. }
  45025. } else {
  45026. return;
  45027. }
  45028. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  45029. attribute.version = version;
  45030. // Updating index buffer in VAO now. See WebGLBindingStates
  45031. //
  45032. const previousAttribute = wireframeAttributes.get( geometry );
  45033. if ( previousAttribute ) attributes.remove( previousAttribute );
  45034. //
  45035. wireframeAttributes.set( geometry, attribute );
  45036. }
  45037. function getWireframeAttribute( geometry ) {
  45038. const currentAttribute = wireframeAttributes.get( geometry );
  45039. if ( currentAttribute ) {
  45040. const geometryIndex = geometry.index;
  45041. if ( geometryIndex !== null ) {
  45042. // if the attribute is obsolete, create a new one
  45043. if ( currentAttribute.version < geometryIndex.version ) {
  45044. updateWireframeAttribute( geometry );
  45045. }
  45046. }
  45047. } else {
  45048. updateWireframeAttribute( geometry );
  45049. }
  45050. return wireframeAttributes.get( geometry );
  45051. }
  45052. return {
  45053. get: get,
  45054. update: update,
  45055. getWireframeAttribute: getWireframeAttribute
  45056. };
  45057. }
  45058. function WebGLIndexedBufferRenderer( gl, extensions, info ) {
  45059. let mode;
  45060. function setMode( value ) {
  45061. mode = value;
  45062. }
  45063. let type, bytesPerElement;
  45064. function setIndex( value ) {
  45065. type = value.type;
  45066. bytesPerElement = value.bytesPerElement;
  45067. }
  45068. function render( start, count ) {
  45069. gl.drawElements( mode, count, type, start * bytesPerElement );
  45070. info.update( count, mode, 1 );
  45071. }
  45072. function renderInstances( start, count, primcount ) {
  45073. if ( primcount === 0 ) return;
  45074. gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount );
  45075. info.update( count, mode, primcount );
  45076. }
  45077. function renderMultiDraw( starts, counts, drawCount ) {
  45078. if ( drawCount === 0 ) return;
  45079. const extension = extensions.get( 'WEBGL_multi_draw' );
  45080. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  45081. let elementCount = 0;
  45082. for ( let i = 0; i < drawCount; i ++ ) {
  45083. elementCount += counts[ i ];
  45084. }
  45085. info.update( elementCount, mode, 1 );
  45086. }
  45087. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  45088. if ( drawCount === 0 ) return;
  45089. const extension = extensions.get( 'WEBGL_multi_draw' );
  45090. if ( extension === null ) {
  45091. for ( let i = 0; i < starts.length; i ++ ) {
  45092. renderInstances( starts[ i ] / bytesPerElement, counts[ i ], primcount[ i ] );
  45093. }
  45094. } else {
  45095. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, type, starts, 0, primcount, 0, drawCount );
  45096. let elementCount = 0;
  45097. for ( let i = 0; i < drawCount; i ++ ) {
  45098. elementCount += counts[ i ] * primcount[ i ];
  45099. }
  45100. info.update( elementCount, mode, 1 );
  45101. }
  45102. }
  45103. //
  45104. this.setMode = setMode;
  45105. this.setIndex = setIndex;
  45106. this.render = render;
  45107. this.renderInstances = renderInstances;
  45108. this.renderMultiDraw = renderMultiDraw;
  45109. this.renderMultiDrawInstances = renderMultiDrawInstances;
  45110. }
  45111. function WebGLInfo( gl ) {
  45112. const memory = {
  45113. geometries: 0,
  45114. textures: 0
  45115. };
  45116. const render = {
  45117. frame: 0,
  45118. calls: 0,
  45119. triangles: 0,
  45120. points: 0,
  45121. lines: 0
  45122. };
  45123. function update( count, mode, instanceCount ) {
  45124. render.calls ++;
  45125. switch ( mode ) {
  45126. case gl.TRIANGLES:
  45127. render.triangles += instanceCount * ( count / 3 );
  45128. break;
  45129. case gl.LINES:
  45130. render.lines += instanceCount * ( count / 2 );
  45131. break;
  45132. case gl.LINE_STRIP:
  45133. render.lines += instanceCount * ( count - 1 );
  45134. break;
  45135. case gl.LINE_LOOP:
  45136. render.lines += instanceCount * count;
  45137. break;
  45138. case gl.POINTS:
  45139. render.points += instanceCount * count;
  45140. break;
  45141. default:
  45142. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  45143. break;
  45144. }
  45145. }
  45146. function reset() {
  45147. render.calls = 0;
  45148. render.triangles = 0;
  45149. render.points = 0;
  45150. render.lines = 0;
  45151. }
  45152. return {
  45153. memory: memory,
  45154. render: render,
  45155. programs: null,
  45156. autoReset: true,
  45157. reset: reset,
  45158. update: update
  45159. };
  45160. }
  45161. function WebGLMorphtargets( gl, capabilities, textures ) {
  45162. const morphTextures = new WeakMap();
  45163. const morph = new Vector4();
  45164. function update( object, geometry, program ) {
  45165. const objectInfluences = object.morphTargetInfluences;
  45166. // the following encodes morph targets into an array of data textures. Each layer represents a single morph target.
  45167. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  45168. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  45169. let entry = morphTextures.get( geometry );
  45170. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  45171. if ( entry !== undefined ) entry.texture.dispose();
  45172. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  45173. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  45174. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  45175. const morphTargets = geometry.morphAttributes.position || [];
  45176. const morphNormals = geometry.morphAttributes.normal || [];
  45177. const morphColors = geometry.morphAttributes.color || [];
  45178. let vertexDataCount = 0;
  45179. if ( hasMorphPosition === true ) vertexDataCount = 1;
  45180. if ( hasMorphNormals === true ) vertexDataCount = 2;
  45181. if ( hasMorphColors === true ) vertexDataCount = 3;
  45182. let width = geometry.attributes.position.count * vertexDataCount;
  45183. let height = 1;
  45184. if ( width > capabilities.maxTextureSize ) {
  45185. height = Math.ceil( width / capabilities.maxTextureSize );
  45186. width = capabilities.maxTextureSize;
  45187. }
  45188. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  45189. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  45190. texture.type = FloatType;
  45191. texture.needsUpdate = true;
  45192. // fill buffer
  45193. const vertexDataStride = vertexDataCount * 4;
  45194. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  45195. const morphTarget = morphTargets[ i ];
  45196. const morphNormal = morphNormals[ i ];
  45197. const morphColor = morphColors[ i ];
  45198. const offset = width * height * 4 * i;
  45199. for ( let j = 0; j < morphTarget.count; j ++ ) {
  45200. const stride = j * vertexDataStride;
  45201. if ( hasMorphPosition === true ) {
  45202. morph.fromBufferAttribute( morphTarget, j );
  45203. buffer[ offset + stride + 0 ] = morph.x;
  45204. buffer[ offset + stride + 1 ] = morph.y;
  45205. buffer[ offset + stride + 2 ] = morph.z;
  45206. buffer[ offset + stride + 3 ] = 0;
  45207. }
  45208. if ( hasMorphNormals === true ) {
  45209. morph.fromBufferAttribute( morphNormal, j );
  45210. buffer[ offset + stride + 4 ] = morph.x;
  45211. buffer[ offset + stride + 5 ] = morph.y;
  45212. buffer[ offset + stride + 6 ] = morph.z;
  45213. buffer[ offset + stride + 7 ] = 0;
  45214. }
  45215. if ( hasMorphColors === true ) {
  45216. morph.fromBufferAttribute( morphColor, j );
  45217. buffer[ offset + stride + 8 ] = morph.x;
  45218. buffer[ offset + stride + 9 ] = morph.y;
  45219. buffer[ offset + stride + 10 ] = morph.z;
  45220. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  45221. }
  45222. }
  45223. }
  45224. entry = {
  45225. count: morphTargetsCount,
  45226. texture: texture,
  45227. size: new Vector2( width, height )
  45228. };
  45229. morphTextures.set( geometry, entry );
  45230. function disposeTexture() {
  45231. texture.dispose();
  45232. morphTextures.delete( geometry );
  45233. geometry.removeEventListener( 'dispose', disposeTexture );
  45234. }
  45235. geometry.addEventListener( 'dispose', disposeTexture );
  45236. }
  45237. //
  45238. if ( object.isInstancedMesh === true && object.morphTexture !== null ) {
  45239. program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures );
  45240. } else {
  45241. let morphInfluencesSum = 0;
  45242. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  45243. morphInfluencesSum += objectInfluences[ i ];
  45244. }
  45245. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  45246. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  45247. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  45248. }
  45249. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  45250. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  45251. }
  45252. return {
  45253. update: update
  45254. };
  45255. }
  45256. function WebGLObjects( gl, geometries, attributes, info ) {
  45257. let updateMap = new WeakMap();
  45258. function update( object ) {
  45259. const frame = info.render.frame;
  45260. const geometry = object.geometry;
  45261. const buffergeometry = geometries.get( object, geometry );
  45262. // Update once per frame
  45263. if ( updateMap.get( buffergeometry ) !== frame ) {
  45264. geometries.update( buffergeometry );
  45265. updateMap.set( buffergeometry, frame );
  45266. }
  45267. if ( object.isInstancedMesh ) {
  45268. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  45269. object.addEventListener( 'dispose', onInstancedMeshDispose );
  45270. }
  45271. if ( updateMap.get( object ) !== frame ) {
  45272. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  45273. if ( object.instanceColor !== null ) {
  45274. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  45275. }
  45276. updateMap.set( object, frame );
  45277. }
  45278. }
  45279. if ( object.isSkinnedMesh ) {
  45280. const skeleton = object.skeleton;
  45281. if ( updateMap.get( skeleton ) !== frame ) {
  45282. skeleton.update();
  45283. updateMap.set( skeleton, frame );
  45284. }
  45285. }
  45286. return buffergeometry;
  45287. }
  45288. function dispose() {
  45289. updateMap = new WeakMap();
  45290. }
  45291. function onInstancedMeshDispose( event ) {
  45292. const instancedMesh = event.target;
  45293. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  45294. attributes.remove( instancedMesh.instanceMatrix );
  45295. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  45296. }
  45297. return {
  45298. update: update,
  45299. dispose: dispose
  45300. };
  45301. }
  45302. /**
  45303. * Uniforms of a program.
  45304. * Those form a tree structure with a special top-level container for the root,
  45305. * which you get by calling 'new WebGLUniforms( gl, program )'.
  45306. *
  45307. *
  45308. * Properties of inner nodes including the top-level container:
  45309. *
  45310. * .seq - array of nested uniforms
  45311. * .map - nested uniforms by name
  45312. *
  45313. *
  45314. * Methods of all nodes except the top-level container:
  45315. *
  45316. * .setValue( gl, value, [textures] )
  45317. *
  45318. * uploads a uniform value(s)
  45319. * the 'textures' parameter is needed for sampler uniforms
  45320. *
  45321. *
  45322. * Static methods of the top-level container (textures factorizations):
  45323. *
  45324. * .upload( gl, seq, values, textures )
  45325. *
  45326. * sets uniforms in 'seq' to 'values[id].value'
  45327. *
  45328. * .seqWithValue( seq, values ) : filteredSeq
  45329. *
  45330. * filters 'seq' entries with corresponding entry in values
  45331. *
  45332. *
  45333. * Methods of the top-level container (textures factorizations):
  45334. *
  45335. * .setValue( gl, name, value, textures )
  45336. *
  45337. * sets uniform with name 'name' to 'value'
  45338. *
  45339. * .setOptional( gl, obj, prop )
  45340. *
  45341. * like .set for an optional property of the object
  45342. *
  45343. */
  45344. const emptyTexture = /*@__PURE__*/ new Texture();
  45345. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  45346. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  45347. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  45348. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  45349. // --- Utilities ---
  45350. // Array Caches (provide typed arrays for temporary by size)
  45351. const arrayCacheF32 = [];
  45352. const arrayCacheI32 = [];
  45353. // Float32Array caches used for uploading Matrix uniforms
  45354. const mat4array = new Float32Array( 16 );
  45355. const mat3array = new Float32Array( 9 );
  45356. const mat2array = new Float32Array( 4 );
  45357. // Flattening for arrays of vectors and matrices
  45358. function flatten( array, nBlocks, blockSize ) {
  45359. const firstElem = array[ 0 ];
  45360. if ( firstElem <= 0 || firstElem > 0 ) return array;
  45361. // unoptimized: ! isNaN( firstElem )
  45362. // see http://jacksondunstan.com/articles/983
  45363. const n = nBlocks * blockSize;
  45364. let r = arrayCacheF32[ n ];
  45365. if ( r === undefined ) {
  45366. r = new Float32Array( n );
  45367. arrayCacheF32[ n ] = r;
  45368. }
  45369. if ( nBlocks !== 0 ) {
  45370. firstElem.toArray( r, 0 );
  45371. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  45372. offset += blockSize;
  45373. array[ i ].toArray( r, offset );
  45374. }
  45375. }
  45376. return r;
  45377. }
  45378. function arraysEqual( a, b ) {
  45379. if ( a.length !== b.length ) return false;
  45380. for ( let i = 0, l = a.length; i < l; i ++ ) {
  45381. if ( a[ i ] !== b[ i ] ) return false;
  45382. }
  45383. return true;
  45384. }
  45385. function copyArray( a, b ) {
  45386. for ( let i = 0, l = b.length; i < l; i ++ ) {
  45387. a[ i ] = b[ i ];
  45388. }
  45389. }
  45390. // Texture unit allocation
  45391. function allocTexUnits( textures, n ) {
  45392. let r = arrayCacheI32[ n ];
  45393. if ( r === undefined ) {
  45394. r = new Int32Array( n );
  45395. arrayCacheI32[ n ] = r;
  45396. }
  45397. for ( let i = 0; i !== n; ++ i ) {
  45398. r[ i ] = textures.allocateTextureUnit();
  45399. }
  45400. return r;
  45401. }
  45402. // --- Setters ---
  45403. // Note: Defining these methods externally, because they come in a bunch
  45404. // and this way their names minify.
  45405. // Single scalar
  45406. function setValueV1f( gl, v ) {
  45407. const cache = this.cache;
  45408. if ( cache[ 0 ] === v ) return;
  45409. gl.uniform1f( this.addr, v );
  45410. cache[ 0 ] = v;
  45411. }
  45412. // Single float vector (from flat array or THREE.VectorN)
  45413. function setValueV2f( gl, v ) {
  45414. const cache = this.cache;
  45415. if ( v.x !== undefined ) {
  45416. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  45417. gl.uniform2f( this.addr, v.x, v.y );
  45418. cache[ 0 ] = v.x;
  45419. cache[ 1 ] = v.y;
  45420. }
  45421. } else {
  45422. if ( arraysEqual( cache, v ) ) return;
  45423. gl.uniform2fv( this.addr, v );
  45424. copyArray( cache, v );
  45425. }
  45426. }
  45427. function setValueV3f( gl, v ) {
  45428. const cache = this.cache;
  45429. if ( v.x !== undefined ) {
  45430. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  45431. gl.uniform3f( this.addr, v.x, v.y, v.z );
  45432. cache[ 0 ] = v.x;
  45433. cache[ 1 ] = v.y;
  45434. cache[ 2 ] = v.z;
  45435. }
  45436. } else if ( v.r !== undefined ) {
  45437. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  45438. gl.uniform3f( this.addr, v.r, v.g, v.b );
  45439. cache[ 0 ] = v.r;
  45440. cache[ 1 ] = v.g;
  45441. cache[ 2 ] = v.b;
  45442. }
  45443. } else {
  45444. if ( arraysEqual( cache, v ) ) return;
  45445. gl.uniform3fv( this.addr, v );
  45446. copyArray( cache, v );
  45447. }
  45448. }
  45449. function setValueV4f( gl, v ) {
  45450. const cache = this.cache;
  45451. if ( v.x !== undefined ) {
  45452. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  45453. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  45454. cache[ 0 ] = v.x;
  45455. cache[ 1 ] = v.y;
  45456. cache[ 2 ] = v.z;
  45457. cache[ 3 ] = v.w;
  45458. }
  45459. } else {
  45460. if ( arraysEqual( cache, v ) ) return;
  45461. gl.uniform4fv( this.addr, v );
  45462. copyArray( cache, v );
  45463. }
  45464. }
  45465. // Single matrix (from flat array or THREE.MatrixN)
  45466. function setValueM2( gl, v ) {
  45467. const cache = this.cache;
  45468. const elements = v.elements;
  45469. if ( elements === undefined ) {
  45470. if ( arraysEqual( cache, v ) ) return;
  45471. gl.uniformMatrix2fv( this.addr, false, v );
  45472. copyArray( cache, v );
  45473. } else {
  45474. if ( arraysEqual( cache, elements ) ) return;
  45475. mat2array.set( elements );
  45476. gl.uniformMatrix2fv( this.addr, false, mat2array );
  45477. copyArray( cache, elements );
  45478. }
  45479. }
  45480. function setValueM3( gl, v ) {
  45481. const cache = this.cache;
  45482. const elements = v.elements;
  45483. if ( elements === undefined ) {
  45484. if ( arraysEqual( cache, v ) ) return;
  45485. gl.uniformMatrix3fv( this.addr, false, v );
  45486. copyArray( cache, v );
  45487. } else {
  45488. if ( arraysEqual( cache, elements ) ) return;
  45489. mat3array.set( elements );
  45490. gl.uniformMatrix3fv( this.addr, false, mat3array );
  45491. copyArray( cache, elements );
  45492. }
  45493. }
  45494. function setValueM4( gl, v ) {
  45495. const cache = this.cache;
  45496. const elements = v.elements;
  45497. if ( elements === undefined ) {
  45498. if ( arraysEqual( cache, v ) ) return;
  45499. gl.uniformMatrix4fv( this.addr, false, v );
  45500. copyArray( cache, v );
  45501. } else {
  45502. if ( arraysEqual( cache, elements ) ) return;
  45503. mat4array.set( elements );
  45504. gl.uniformMatrix4fv( this.addr, false, mat4array );
  45505. copyArray( cache, elements );
  45506. }
  45507. }
  45508. // Single integer / boolean
  45509. function setValueV1i( gl, v ) {
  45510. const cache = this.cache;
  45511. if ( cache[ 0 ] === v ) return;
  45512. gl.uniform1i( this.addr, v );
  45513. cache[ 0 ] = v;
  45514. }
  45515. // Single integer / boolean vector (from flat array or THREE.VectorN)
  45516. function setValueV2i( gl, v ) {
  45517. const cache = this.cache;
  45518. if ( v.x !== undefined ) {
  45519. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  45520. gl.uniform2i( this.addr, v.x, v.y );
  45521. cache[ 0 ] = v.x;
  45522. cache[ 1 ] = v.y;
  45523. }
  45524. } else {
  45525. if ( arraysEqual( cache, v ) ) return;
  45526. gl.uniform2iv( this.addr, v );
  45527. copyArray( cache, v );
  45528. }
  45529. }
  45530. function setValueV3i( gl, v ) {
  45531. const cache = this.cache;
  45532. if ( v.x !== undefined ) {
  45533. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  45534. gl.uniform3i( this.addr, v.x, v.y, v.z );
  45535. cache[ 0 ] = v.x;
  45536. cache[ 1 ] = v.y;
  45537. cache[ 2 ] = v.z;
  45538. }
  45539. } else {
  45540. if ( arraysEqual( cache, v ) ) return;
  45541. gl.uniform3iv( this.addr, v );
  45542. copyArray( cache, v );
  45543. }
  45544. }
  45545. function setValueV4i( gl, v ) {
  45546. const cache = this.cache;
  45547. if ( v.x !== undefined ) {
  45548. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  45549. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  45550. cache[ 0 ] = v.x;
  45551. cache[ 1 ] = v.y;
  45552. cache[ 2 ] = v.z;
  45553. cache[ 3 ] = v.w;
  45554. }
  45555. } else {
  45556. if ( arraysEqual( cache, v ) ) return;
  45557. gl.uniform4iv( this.addr, v );
  45558. copyArray( cache, v );
  45559. }
  45560. }
  45561. // Single unsigned integer
  45562. function setValueV1ui( gl, v ) {
  45563. const cache = this.cache;
  45564. if ( cache[ 0 ] === v ) return;
  45565. gl.uniform1ui( this.addr, v );
  45566. cache[ 0 ] = v;
  45567. }
  45568. // Single unsigned integer vector (from flat array or THREE.VectorN)
  45569. function setValueV2ui( gl, v ) {
  45570. const cache = this.cache;
  45571. if ( v.x !== undefined ) {
  45572. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  45573. gl.uniform2ui( this.addr, v.x, v.y );
  45574. cache[ 0 ] = v.x;
  45575. cache[ 1 ] = v.y;
  45576. }
  45577. } else {
  45578. if ( arraysEqual( cache, v ) ) return;
  45579. gl.uniform2uiv( this.addr, v );
  45580. copyArray( cache, v );
  45581. }
  45582. }
  45583. function setValueV3ui( gl, v ) {
  45584. const cache = this.cache;
  45585. if ( v.x !== undefined ) {
  45586. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  45587. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  45588. cache[ 0 ] = v.x;
  45589. cache[ 1 ] = v.y;
  45590. cache[ 2 ] = v.z;
  45591. }
  45592. } else {
  45593. if ( arraysEqual( cache, v ) ) return;
  45594. gl.uniform3uiv( this.addr, v );
  45595. copyArray( cache, v );
  45596. }
  45597. }
  45598. function setValueV4ui( gl, v ) {
  45599. const cache = this.cache;
  45600. if ( v.x !== undefined ) {
  45601. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  45602. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  45603. cache[ 0 ] = v.x;
  45604. cache[ 1 ] = v.y;
  45605. cache[ 2 ] = v.z;
  45606. cache[ 3 ] = v.w;
  45607. }
  45608. } else {
  45609. if ( arraysEqual( cache, v ) ) return;
  45610. gl.uniform4uiv( this.addr, v );
  45611. copyArray( cache, v );
  45612. }
  45613. }
  45614. // Single texture (2D / Cube)
  45615. function setValueT1( gl, v, textures ) {
  45616. const cache = this.cache;
  45617. const unit = textures.allocateTextureUnit();
  45618. if ( cache[ 0 ] !== unit ) {
  45619. gl.uniform1i( this.addr, unit );
  45620. cache[ 0 ] = unit;
  45621. }
  45622. let emptyTexture2D;
  45623. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  45624. emptyShadowTexture.compareFunction = LessEqualCompare; // #28670
  45625. emptyTexture2D = emptyShadowTexture;
  45626. } else {
  45627. emptyTexture2D = emptyTexture;
  45628. }
  45629. textures.setTexture2D( v || emptyTexture2D, unit );
  45630. }
  45631. function setValueT3D1( gl, v, textures ) {
  45632. const cache = this.cache;
  45633. const unit = textures.allocateTextureUnit();
  45634. if ( cache[ 0 ] !== unit ) {
  45635. gl.uniform1i( this.addr, unit );
  45636. cache[ 0 ] = unit;
  45637. }
  45638. textures.setTexture3D( v || empty3dTexture, unit );
  45639. }
  45640. function setValueT6( gl, v, textures ) {
  45641. const cache = this.cache;
  45642. const unit = textures.allocateTextureUnit();
  45643. if ( cache[ 0 ] !== unit ) {
  45644. gl.uniform1i( this.addr, unit );
  45645. cache[ 0 ] = unit;
  45646. }
  45647. textures.setTextureCube( v || emptyCubeTexture, unit );
  45648. }
  45649. function setValueT2DArray1( gl, v, textures ) {
  45650. const cache = this.cache;
  45651. const unit = textures.allocateTextureUnit();
  45652. if ( cache[ 0 ] !== unit ) {
  45653. gl.uniform1i( this.addr, unit );
  45654. cache[ 0 ] = unit;
  45655. }
  45656. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  45657. }
  45658. // Helper to pick the right setter for the singular case
  45659. function getSingularSetter( type ) {
  45660. switch ( type ) {
  45661. case 0x1406: return setValueV1f; // FLOAT
  45662. case 0x8b50: return setValueV2f; // _VEC2
  45663. case 0x8b51: return setValueV3f; // _VEC3
  45664. case 0x8b52: return setValueV4f; // _VEC4
  45665. case 0x8b5a: return setValueM2; // _MAT2
  45666. case 0x8b5b: return setValueM3; // _MAT3
  45667. case 0x8b5c: return setValueM4; // _MAT4
  45668. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  45669. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  45670. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  45671. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  45672. case 0x1405: return setValueV1ui; // UINT
  45673. case 0x8dc6: return setValueV2ui; // _VEC2
  45674. case 0x8dc7: return setValueV3ui; // _VEC3
  45675. case 0x8dc8: return setValueV4ui; // _VEC4
  45676. case 0x8b5e: // SAMPLER_2D
  45677. case 0x8d66: // SAMPLER_EXTERNAL_OES
  45678. case 0x8dca: // INT_SAMPLER_2D
  45679. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  45680. case 0x8b62: // SAMPLER_2D_SHADOW
  45681. return setValueT1;
  45682. case 0x8b5f: // SAMPLER_3D
  45683. case 0x8dcb: // INT_SAMPLER_3D
  45684. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  45685. return setValueT3D1;
  45686. case 0x8b60: // SAMPLER_CUBE
  45687. case 0x8dcc: // INT_SAMPLER_CUBE
  45688. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  45689. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  45690. return setValueT6;
  45691. case 0x8dc1: // SAMPLER_2D_ARRAY
  45692. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  45693. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  45694. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  45695. return setValueT2DArray1;
  45696. }
  45697. }
  45698. // Array of scalars
  45699. function setValueV1fArray( gl, v ) {
  45700. gl.uniform1fv( this.addr, v );
  45701. }
  45702. // Array of vectors (from flat array or array of THREE.VectorN)
  45703. function setValueV2fArray( gl, v ) {
  45704. const data = flatten( v, this.size, 2 );
  45705. gl.uniform2fv( this.addr, data );
  45706. }
  45707. function setValueV3fArray( gl, v ) {
  45708. const data = flatten( v, this.size, 3 );
  45709. gl.uniform3fv( this.addr, data );
  45710. }
  45711. function setValueV4fArray( gl, v ) {
  45712. const data = flatten( v, this.size, 4 );
  45713. gl.uniform4fv( this.addr, data );
  45714. }
  45715. // Array of matrices (from flat array or array of THREE.MatrixN)
  45716. function setValueM2Array( gl, v ) {
  45717. const data = flatten( v, this.size, 4 );
  45718. gl.uniformMatrix2fv( this.addr, false, data );
  45719. }
  45720. function setValueM3Array( gl, v ) {
  45721. const data = flatten( v, this.size, 9 );
  45722. gl.uniformMatrix3fv( this.addr, false, data );
  45723. }
  45724. function setValueM4Array( gl, v ) {
  45725. const data = flatten( v, this.size, 16 );
  45726. gl.uniformMatrix4fv( this.addr, false, data );
  45727. }
  45728. // Array of integer / boolean
  45729. function setValueV1iArray( gl, v ) {
  45730. gl.uniform1iv( this.addr, v );
  45731. }
  45732. // Array of integer / boolean vectors (from flat array)
  45733. function setValueV2iArray( gl, v ) {
  45734. gl.uniform2iv( this.addr, v );
  45735. }
  45736. function setValueV3iArray( gl, v ) {
  45737. gl.uniform3iv( this.addr, v );
  45738. }
  45739. function setValueV4iArray( gl, v ) {
  45740. gl.uniform4iv( this.addr, v );
  45741. }
  45742. // Array of unsigned integer
  45743. function setValueV1uiArray( gl, v ) {
  45744. gl.uniform1uiv( this.addr, v );
  45745. }
  45746. // Array of unsigned integer vectors (from flat array)
  45747. function setValueV2uiArray( gl, v ) {
  45748. gl.uniform2uiv( this.addr, v );
  45749. }
  45750. function setValueV3uiArray( gl, v ) {
  45751. gl.uniform3uiv( this.addr, v );
  45752. }
  45753. function setValueV4uiArray( gl, v ) {
  45754. gl.uniform4uiv( this.addr, v );
  45755. }
  45756. // Array of textures (2D / 3D / Cube / 2DArray)
  45757. function setValueT1Array( gl, v, textures ) {
  45758. const cache = this.cache;
  45759. const n = v.length;
  45760. const units = allocTexUnits( textures, n );
  45761. if ( ! arraysEqual( cache, units ) ) {
  45762. gl.uniform1iv( this.addr, units );
  45763. copyArray( cache, units );
  45764. }
  45765. for ( let i = 0; i !== n; ++ i ) {
  45766. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  45767. }
  45768. }
  45769. function setValueT3DArray( gl, v, textures ) {
  45770. const cache = this.cache;
  45771. const n = v.length;
  45772. const units = allocTexUnits( textures, n );
  45773. if ( ! arraysEqual( cache, units ) ) {
  45774. gl.uniform1iv( this.addr, units );
  45775. copyArray( cache, units );
  45776. }
  45777. for ( let i = 0; i !== n; ++ i ) {
  45778. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  45779. }
  45780. }
  45781. function setValueT6Array( gl, v, textures ) {
  45782. const cache = this.cache;
  45783. const n = v.length;
  45784. const units = allocTexUnits( textures, n );
  45785. if ( ! arraysEqual( cache, units ) ) {
  45786. gl.uniform1iv( this.addr, units );
  45787. copyArray( cache, units );
  45788. }
  45789. for ( let i = 0; i !== n; ++ i ) {
  45790. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  45791. }
  45792. }
  45793. function setValueT2DArrayArray( gl, v, textures ) {
  45794. const cache = this.cache;
  45795. const n = v.length;
  45796. const units = allocTexUnits( textures, n );
  45797. if ( ! arraysEqual( cache, units ) ) {
  45798. gl.uniform1iv( this.addr, units );
  45799. copyArray( cache, units );
  45800. }
  45801. for ( let i = 0; i !== n; ++ i ) {
  45802. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  45803. }
  45804. }
  45805. // Helper to pick the right setter for a pure (bottom-level) array
  45806. function getPureArraySetter( type ) {
  45807. switch ( type ) {
  45808. case 0x1406: return setValueV1fArray; // FLOAT
  45809. case 0x8b50: return setValueV2fArray; // _VEC2
  45810. case 0x8b51: return setValueV3fArray; // _VEC3
  45811. case 0x8b52: return setValueV4fArray; // _VEC4
  45812. case 0x8b5a: return setValueM2Array; // _MAT2
  45813. case 0x8b5b: return setValueM3Array; // _MAT3
  45814. case 0x8b5c: return setValueM4Array; // _MAT4
  45815. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  45816. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  45817. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  45818. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  45819. case 0x1405: return setValueV1uiArray; // UINT
  45820. case 0x8dc6: return setValueV2uiArray; // _VEC2
  45821. case 0x8dc7: return setValueV3uiArray; // _VEC3
  45822. case 0x8dc8: return setValueV4uiArray; // _VEC4
  45823. case 0x8b5e: // SAMPLER_2D
  45824. case 0x8d66: // SAMPLER_EXTERNAL_OES
  45825. case 0x8dca: // INT_SAMPLER_2D
  45826. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  45827. case 0x8b62: // SAMPLER_2D_SHADOW
  45828. return setValueT1Array;
  45829. case 0x8b5f: // SAMPLER_3D
  45830. case 0x8dcb: // INT_SAMPLER_3D
  45831. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  45832. return setValueT3DArray;
  45833. case 0x8b60: // SAMPLER_CUBE
  45834. case 0x8dcc: // INT_SAMPLER_CUBE
  45835. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  45836. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  45837. return setValueT6Array;
  45838. case 0x8dc1: // SAMPLER_2D_ARRAY
  45839. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  45840. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  45841. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  45842. return setValueT2DArrayArray;
  45843. }
  45844. }
  45845. // --- Uniform Classes ---
  45846. class SingleUniform {
  45847. constructor( id, activeInfo, addr ) {
  45848. this.id = id;
  45849. this.addr = addr;
  45850. this.cache = [];
  45851. this.type = activeInfo.type;
  45852. this.setValue = getSingularSetter( activeInfo.type );
  45853. // this.path = activeInfo.name; // DEBUG
  45854. }
  45855. }
  45856. class PureArrayUniform {
  45857. constructor( id, activeInfo, addr ) {
  45858. this.id = id;
  45859. this.addr = addr;
  45860. this.cache = [];
  45861. this.type = activeInfo.type;
  45862. this.size = activeInfo.size;
  45863. this.setValue = getPureArraySetter( activeInfo.type );
  45864. // this.path = activeInfo.name; // DEBUG
  45865. }
  45866. }
  45867. class StructuredUniform {
  45868. constructor( id ) {
  45869. this.id = id;
  45870. this.seq = [];
  45871. this.map = {};
  45872. }
  45873. setValue( gl, value, textures ) {
  45874. const seq = this.seq;
  45875. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  45876. const u = seq[ i ];
  45877. u.setValue( gl, value[ u.id ], textures );
  45878. }
  45879. }
  45880. }
  45881. // --- Top-level ---
  45882. // Parser - builds up the property tree from the path strings
  45883. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  45884. // extracts
  45885. // - the identifier (member name or array index)
  45886. // - followed by an optional right bracket (found when array index)
  45887. // - followed by an optional left bracket or dot (type of subscript)
  45888. //
  45889. // Note: These portions can be read in a non-overlapping fashion and
  45890. // allow straightforward parsing of the hierarchy that WebGL encodes
  45891. // in the uniform names.
  45892. function addUniform( container, uniformObject ) {
  45893. container.seq.push( uniformObject );
  45894. container.map[ uniformObject.id ] = uniformObject;
  45895. }
  45896. function parseUniform( activeInfo, addr, container ) {
  45897. const path = activeInfo.name,
  45898. pathLength = path.length;
  45899. // reset RegExp object, because of the early exit of a previous run
  45900. RePathPart.lastIndex = 0;
  45901. while ( true ) {
  45902. const match = RePathPart.exec( path ),
  45903. matchEnd = RePathPart.lastIndex;
  45904. let id = match[ 1 ];
  45905. const idIsIndex = match[ 2 ] === ']',
  45906. subscript = match[ 3 ];
  45907. if ( idIsIndex ) id = id | 0; // convert to integer
  45908. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  45909. // bare name or "pure" bottom-level array "[0]" suffix
  45910. addUniform( container, subscript === undefined ?
  45911. new SingleUniform( id, activeInfo, addr ) :
  45912. new PureArrayUniform( id, activeInfo, addr ) );
  45913. break;
  45914. } else {
  45915. // step into inner node / create it in case it doesn't exist
  45916. const map = container.map;
  45917. let next = map[ id ];
  45918. if ( next === undefined ) {
  45919. next = new StructuredUniform( id );
  45920. addUniform( container, next );
  45921. }
  45922. container = next;
  45923. }
  45924. }
  45925. }
  45926. // Root Container
  45927. class WebGLUniforms {
  45928. constructor( gl, program ) {
  45929. this.seq = [];
  45930. this.map = {};
  45931. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  45932. for ( let i = 0; i < n; ++ i ) {
  45933. const info = gl.getActiveUniform( program, i ),
  45934. addr = gl.getUniformLocation( program, info.name );
  45935. parseUniform( info, addr, this );
  45936. }
  45937. }
  45938. setValue( gl, name, value, textures ) {
  45939. const u = this.map[ name ];
  45940. if ( u !== undefined ) u.setValue( gl, value, textures );
  45941. }
  45942. setOptional( gl, object, name ) {
  45943. const v = object[ name ];
  45944. if ( v !== undefined ) this.setValue( gl, name, v );
  45945. }
  45946. static upload( gl, seq, values, textures ) {
  45947. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  45948. const u = seq[ i ],
  45949. v = values[ u.id ];
  45950. if ( v.needsUpdate !== false ) {
  45951. // note: always updating when .needsUpdate is undefined
  45952. u.setValue( gl, v.value, textures );
  45953. }
  45954. }
  45955. }
  45956. static seqWithValue( seq, values ) {
  45957. const r = [];
  45958. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  45959. const u = seq[ i ];
  45960. if ( u.id in values ) r.push( u );
  45961. }
  45962. return r;
  45963. }
  45964. }
  45965. function WebGLShader( gl, type, string ) {
  45966. const shader = gl.createShader( type );
  45967. gl.shaderSource( shader, string );
  45968. gl.compileShader( shader );
  45969. return shader;
  45970. }
  45971. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  45972. const COMPLETION_STATUS_KHR = 0x91B1;
  45973. let programIdCount = 0;
  45974. function handleSource( string, errorLine ) {
  45975. const lines = string.split( '\n' );
  45976. const lines2 = [];
  45977. const from = Math.max( errorLine - 6, 0 );
  45978. const to = Math.min( errorLine + 6, lines.length );
  45979. for ( let i = from; i < to; i ++ ) {
  45980. const line = i + 1;
  45981. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  45982. }
  45983. return lines2.join( '\n' );
  45984. }
  45985. const _m0 = /*@__PURE__*/ new Matrix3();
  45986. function getEncodingComponents( colorSpace ) {
  45987. ColorManagement._getMatrix( _m0, ColorManagement.workingColorSpace, colorSpace );
  45988. const encodingMatrix = `mat3( ${ _m0.elements.map( ( v ) => v.toFixed( 4 ) ) } )`;
  45989. switch ( ColorManagement.getTransfer( colorSpace ) ) {
  45990. case LinearTransfer:
  45991. return [ encodingMatrix, 'LinearTransferOETF' ];
  45992. case SRGBTransfer:
  45993. return [ encodingMatrix, 'sRGBTransferOETF' ];
  45994. default:
  45995. console.warn( 'THREE.WebGLProgram: Unsupported color space: ', colorSpace );
  45996. return [ encodingMatrix, 'LinearTransferOETF' ];
  45997. }
  45998. }
  45999. function getShaderErrors( gl, shader, type ) {
  46000. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  46001. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  46002. const errors = shaderInfoLog.trim();
  46003. if ( status && errors === '' ) return '';
  46004. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  46005. if ( errorMatches ) {
  46006. // --enable-privileged-webgl-extension
  46007. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  46008. const errorLine = parseInt( errorMatches[ 1 ] );
  46009. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  46010. } else {
  46011. return errors;
  46012. }
  46013. }
  46014. function getTexelEncodingFunction( functionName, colorSpace ) {
  46015. const components = getEncodingComponents( colorSpace );
  46016. return [
  46017. `vec4 ${functionName}( vec4 value ) {`,
  46018. ` return ${components[ 1 ]}( vec4( value.rgb * ${components[ 0 ]}, value.a ) );`,
  46019. '}',
  46020. ].join( '\n' );
  46021. }
  46022. function getToneMappingFunction( functionName, toneMapping ) {
  46023. let toneMappingName;
  46024. switch ( toneMapping ) {
  46025. case LinearToneMapping:
  46026. toneMappingName = 'Linear';
  46027. break;
  46028. case ReinhardToneMapping:
  46029. toneMappingName = 'Reinhard';
  46030. break;
  46031. case CineonToneMapping:
  46032. toneMappingName = 'Cineon';
  46033. break;
  46034. case ACESFilmicToneMapping:
  46035. toneMappingName = 'ACESFilmic';
  46036. break;
  46037. case AgXToneMapping:
  46038. toneMappingName = 'AgX';
  46039. break;
  46040. case NeutralToneMapping:
  46041. toneMappingName = 'Neutral';
  46042. break;
  46043. case CustomToneMapping:
  46044. toneMappingName = 'Custom';
  46045. break;
  46046. default:
  46047. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  46048. toneMappingName = 'Linear';
  46049. }
  46050. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  46051. }
  46052. const _v0 = /*@__PURE__*/ new Vector3();
  46053. function getLuminanceFunction() {
  46054. ColorManagement.getLuminanceCoefficients( _v0 );
  46055. const r = _v0.x.toFixed( 4 );
  46056. const g = _v0.y.toFixed( 4 );
  46057. const b = _v0.z.toFixed( 4 );
  46058. return [
  46059. 'float luminance( const in vec3 rgb ) {',
  46060. ` const vec3 weights = vec3( ${ r }, ${ g }, ${ b } );`,
  46061. ' return dot( weights, rgb );',
  46062. '}'
  46063. ].join( '\n' );
  46064. }
  46065. function generateVertexExtensions( parameters ) {
  46066. const chunks = [
  46067. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '',
  46068. parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '',
  46069. ];
  46070. return chunks.filter( filterEmptyLine ).join( '\n' );
  46071. }
  46072. function generateDefines( defines ) {
  46073. const chunks = [];
  46074. for ( const name in defines ) {
  46075. const value = defines[ name ];
  46076. if ( value === false ) continue;
  46077. chunks.push( '#define ' + name + ' ' + value );
  46078. }
  46079. return chunks.join( '\n' );
  46080. }
  46081. function fetchAttributeLocations( gl, program ) {
  46082. const attributes = {};
  46083. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  46084. for ( let i = 0; i < n; i ++ ) {
  46085. const info = gl.getActiveAttrib( program, i );
  46086. const name = info.name;
  46087. let locationSize = 1;
  46088. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  46089. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  46090. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  46091. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  46092. attributes[ name ] = {
  46093. type: info.type,
  46094. location: gl.getAttribLocation( program, name ),
  46095. locationSize: locationSize
  46096. };
  46097. }
  46098. return attributes;
  46099. }
  46100. function filterEmptyLine( string ) {
  46101. return string !== '';
  46102. }
  46103. function replaceLightNums( string, parameters ) {
  46104. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  46105. return string
  46106. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  46107. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  46108. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  46109. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  46110. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  46111. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  46112. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  46113. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  46114. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  46115. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  46116. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  46117. }
  46118. function replaceClippingPlaneNums( string, parameters ) {
  46119. return string
  46120. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  46121. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  46122. }
  46123. // Resolve Includes
  46124. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  46125. function resolveIncludes( string ) {
  46126. return string.replace( includePattern, includeReplacer );
  46127. }
  46128. const shaderChunkMap = new Map();
  46129. function includeReplacer( match, include ) {
  46130. let string = ShaderChunk[ include ];
  46131. if ( string === undefined ) {
  46132. const newInclude = shaderChunkMap.get( include );
  46133. if ( newInclude !== undefined ) {
  46134. string = ShaderChunk[ newInclude ];
  46135. console.warn( 'THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  46136. } else {
  46137. throw new Error( 'Can not resolve #include <' + include + '>' );
  46138. }
  46139. }
  46140. return resolveIncludes( string );
  46141. }
  46142. // Unroll Loops
  46143. 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;
  46144. function unrollLoops( string ) {
  46145. return string.replace( unrollLoopPattern, loopReplacer );
  46146. }
  46147. function loopReplacer( match, start, end, snippet ) {
  46148. let string = '';
  46149. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  46150. string += snippet
  46151. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  46152. .replace( /UNROLLED_LOOP_INDEX/g, i );
  46153. }
  46154. return string;
  46155. }
  46156. //
  46157. function generatePrecision( parameters ) {
  46158. let precisionstring = `precision ${parameters.precision} float;
  46159. precision ${parameters.precision} int;
  46160. precision ${parameters.precision} sampler2D;
  46161. precision ${parameters.precision} samplerCube;
  46162. precision ${parameters.precision} sampler3D;
  46163. precision ${parameters.precision} sampler2DArray;
  46164. precision ${parameters.precision} sampler2DShadow;
  46165. precision ${parameters.precision} samplerCubeShadow;
  46166. precision ${parameters.precision} sampler2DArrayShadow;
  46167. precision ${parameters.precision} isampler2D;
  46168. precision ${parameters.precision} isampler3D;
  46169. precision ${parameters.precision} isamplerCube;
  46170. precision ${parameters.precision} isampler2DArray;
  46171. precision ${parameters.precision} usampler2D;
  46172. precision ${parameters.precision} usampler3D;
  46173. precision ${parameters.precision} usamplerCube;
  46174. precision ${parameters.precision} usampler2DArray;
  46175. `;
  46176. if ( parameters.precision === 'highp' ) {
  46177. precisionstring += '\n#define HIGH_PRECISION';
  46178. } else if ( parameters.precision === 'mediump' ) {
  46179. precisionstring += '\n#define MEDIUM_PRECISION';
  46180. } else if ( parameters.precision === 'lowp' ) {
  46181. precisionstring += '\n#define LOW_PRECISION';
  46182. }
  46183. return precisionstring;
  46184. }
  46185. function generateShadowMapTypeDefine( parameters ) {
  46186. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  46187. if ( parameters.shadowMapType === PCFShadowMap ) {
  46188. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  46189. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  46190. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  46191. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  46192. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  46193. }
  46194. return shadowMapTypeDefine;
  46195. }
  46196. function generateEnvMapTypeDefine( parameters ) {
  46197. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  46198. if ( parameters.envMap ) {
  46199. switch ( parameters.envMapMode ) {
  46200. case CubeReflectionMapping:
  46201. case CubeRefractionMapping:
  46202. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  46203. break;
  46204. case CubeUVReflectionMapping:
  46205. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  46206. break;
  46207. }
  46208. }
  46209. return envMapTypeDefine;
  46210. }
  46211. function generateEnvMapModeDefine( parameters ) {
  46212. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  46213. if ( parameters.envMap ) {
  46214. switch ( parameters.envMapMode ) {
  46215. case CubeRefractionMapping:
  46216. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  46217. break;
  46218. }
  46219. }
  46220. return envMapModeDefine;
  46221. }
  46222. function generateEnvMapBlendingDefine( parameters ) {
  46223. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  46224. if ( parameters.envMap ) {
  46225. switch ( parameters.combine ) {
  46226. case MultiplyOperation:
  46227. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  46228. break;
  46229. case MixOperation:
  46230. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  46231. break;
  46232. case AddOperation:
  46233. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  46234. break;
  46235. }
  46236. }
  46237. return envMapBlendingDefine;
  46238. }
  46239. function generateCubeUVSize( parameters ) {
  46240. const imageHeight = parameters.envMapCubeUVHeight;
  46241. if ( imageHeight === null ) return null;
  46242. const maxMip = Math.log2( imageHeight ) - 2;
  46243. const texelHeight = 1.0 / imageHeight;
  46244. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  46245. return { texelWidth, texelHeight, maxMip };
  46246. }
  46247. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  46248. // TODO Send this event to Three.js DevTools
  46249. // console.log( 'WebGLProgram', cacheKey );
  46250. const gl = renderer.getContext();
  46251. const defines = parameters.defines;
  46252. let vertexShader = parameters.vertexShader;
  46253. let fragmentShader = parameters.fragmentShader;
  46254. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  46255. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  46256. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  46257. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  46258. const envMapCubeUVSize = generateCubeUVSize( parameters );
  46259. const customVertexExtensions = generateVertexExtensions( parameters );
  46260. const customDefines = generateDefines( defines );
  46261. const program = gl.createProgram();
  46262. let prefixVertex, prefixFragment;
  46263. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  46264. if ( parameters.isRawShaderMaterial ) {
  46265. prefixVertex = [
  46266. '#define SHADER_TYPE ' + parameters.shaderType,
  46267. '#define SHADER_NAME ' + parameters.shaderName,
  46268. customDefines
  46269. ].filter( filterEmptyLine ).join( '\n' );
  46270. if ( prefixVertex.length > 0 ) {
  46271. prefixVertex += '\n';
  46272. }
  46273. prefixFragment = [
  46274. '#define SHADER_TYPE ' + parameters.shaderType,
  46275. '#define SHADER_NAME ' + parameters.shaderName,
  46276. customDefines
  46277. ].filter( filterEmptyLine ).join( '\n' );
  46278. if ( prefixFragment.length > 0 ) {
  46279. prefixFragment += '\n';
  46280. }
  46281. } else {
  46282. prefixVertex = [
  46283. generatePrecision( parameters ),
  46284. '#define SHADER_TYPE ' + parameters.shaderType,
  46285. '#define SHADER_NAME ' + parameters.shaderName,
  46286. customDefines,
  46287. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  46288. parameters.batching ? '#define USE_BATCHING' : '',
  46289. parameters.batchingColor ? '#define USE_BATCHING_COLOR' : '',
  46290. parameters.instancing ? '#define USE_INSTANCING' : '',
  46291. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  46292. parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '',
  46293. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  46294. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  46295. parameters.map ? '#define USE_MAP' : '',
  46296. parameters.envMap ? '#define USE_ENVMAP' : '',
  46297. parameters.envMap ? '#define ' + envMapModeDefine : '',
  46298. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  46299. parameters.aoMap ? '#define USE_AOMAP' : '',
  46300. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  46301. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  46302. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  46303. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  46304. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  46305. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  46306. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  46307. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  46308. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  46309. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  46310. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  46311. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  46312. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  46313. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  46314. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  46315. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  46316. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  46317. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  46318. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  46319. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  46320. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  46321. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  46322. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  46323. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  46324. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  46325. //
  46326. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  46327. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  46328. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  46329. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  46330. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  46331. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  46332. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  46333. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  46334. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  46335. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  46336. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  46337. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  46338. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  46339. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  46340. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  46341. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  46342. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  46343. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  46344. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  46345. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  46346. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  46347. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  46348. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  46349. //
  46350. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  46351. parameters.vertexColors ? '#define USE_COLOR' : '',
  46352. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  46353. parameters.vertexUv1s ? '#define USE_UV1' : '',
  46354. parameters.vertexUv2s ? '#define USE_UV2' : '',
  46355. parameters.vertexUv3s ? '#define USE_UV3' : '',
  46356. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  46357. parameters.flatShading ? '#define FLAT_SHADED' : '',
  46358. parameters.skinning ? '#define USE_SKINNING' : '',
  46359. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  46360. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  46361. ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '',
  46362. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  46363. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  46364. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  46365. parameters.flipSided ? '#define FLIP_SIDED' : '',
  46366. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  46367. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  46368. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  46369. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  46370. parameters.logarithmicDepthBuffer ? '#define USE_LOGARITHMIC_DEPTH_BUFFER' : '',
  46371. parameters.reversedDepthBuffer ? '#define USE_REVERSED_DEPTH_BUFFER' : '',
  46372. 'uniform mat4 modelMatrix;',
  46373. 'uniform mat4 modelViewMatrix;',
  46374. 'uniform mat4 projectionMatrix;',
  46375. 'uniform mat4 viewMatrix;',
  46376. 'uniform mat3 normalMatrix;',
  46377. 'uniform vec3 cameraPosition;',
  46378. 'uniform bool isOrthographic;',
  46379. '#ifdef USE_INSTANCING',
  46380. ' attribute mat4 instanceMatrix;',
  46381. '#endif',
  46382. '#ifdef USE_INSTANCING_COLOR',
  46383. ' attribute vec3 instanceColor;',
  46384. '#endif',
  46385. '#ifdef USE_INSTANCING_MORPH',
  46386. ' uniform sampler2D morphTexture;',
  46387. '#endif',
  46388. 'attribute vec3 position;',
  46389. 'attribute vec3 normal;',
  46390. 'attribute vec2 uv;',
  46391. '#ifdef USE_UV1',
  46392. ' attribute vec2 uv1;',
  46393. '#endif',
  46394. '#ifdef USE_UV2',
  46395. ' attribute vec2 uv2;',
  46396. '#endif',
  46397. '#ifdef USE_UV3',
  46398. ' attribute vec2 uv3;',
  46399. '#endif',
  46400. '#ifdef USE_TANGENT',
  46401. ' attribute vec4 tangent;',
  46402. '#endif',
  46403. '#if defined( USE_COLOR_ALPHA )',
  46404. ' attribute vec4 color;',
  46405. '#elif defined( USE_COLOR )',
  46406. ' attribute vec3 color;',
  46407. '#endif',
  46408. '#ifdef USE_SKINNING',
  46409. ' attribute vec4 skinIndex;',
  46410. ' attribute vec4 skinWeight;',
  46411. '#endif',
  46412. '\n'
  46413. ].filter( filterEmptyLine ).join( '\n' );
  46414. prefixFragment = [
  46415. generatePrecision( parameters ),
  46416. '#define SHADER_TYPE ' + parameters.shaderType,
  46417. '#define SHADER_NAME ' + parameters.shaderName,
  46418. customDefines,
  46419. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  46420. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  46421. parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '',
  46422. parameters.map ? '#define USE_MAP' : '',
  46423. parameters.matcap ? '#define USE_MATCAP' : '',
  46424. parameters.envMap ? '#define USE_ENVMAP' : '',
  46425. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  46426. parameters.envMap ? '#define ' + envMapModeDefine : '',
  46427. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  46428. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  46429. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  46430. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  46431. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  46432. parameters.aoMap ? '#define USE_AOMAP' : '',
  46433. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  46434. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  46435. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  46436. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  46437. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  46438. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  46439. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  46440. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  46441. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  46442. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  46443. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  46444. parameters.dispersion ? '#define USE_DISPERSION' : '',
  46445. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  46446. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  46447. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  46448. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  46449. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  46450. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  46451. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  46452. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  46453. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  46454. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  46455. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  46456. parameters.sheen ? '#define USE_SHEEN' : '',
  46457. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  46458. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  46459. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  46460. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  46461. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  46462. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  46463. parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? '#define USE_COLOR' : '',
  46464. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  46465. parameters.vertexUv1s ? '#define USE_UV1' : '',
  46466. parameters.vertexUv2s ? '#define USE_UV2' : '',
  46467. parameters.vertexUv3s ? '#define USE_UV3' : '',
  46468. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  46469. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  46470. parameters.flatShading ? '#define FLAT_SHADED' : '',
  46471. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  46472. parameters.flipSided ? '#define FLIP_SIDED' : '',
  46473. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  46474. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  46475. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  46476. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  46477. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  46478. parameters.decodeVideoTextureEmissive ? '#define DECODE_VIDEO_TEXTURE_EMISSIVE' : '',
  46479. parameters.logarithmicDepthBuffer ? '#define USE_LOGARITHMIC_DEPTH_BUFFER' : '',
  46480. parameters.reversedDepthBuffer ? '#define USE_REVERSED_DEPTH_BUFFER' : '',
  46481. 'uniform mat4 viewMatrix;',
  46482. 'uniform vec3 cameraPosition;',
  46483. 'uniform bool isOrthographic;',
  46484. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  46485. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  46486. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  46487. parameters.dithering ? '#define DITHERING' : '',
  46488. parameters.opaque ? '#define OPAQUE' : '',
  46489. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  46490. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  46491. getLuminanceFunction(),
  46492. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  46493. '\n'
  46494. ].filter( filterEmptyLine ).join( '\n' );
  46495. }
  46496. vertexShader = resolveIncludes( vertexShader );
  46497. vertexShader = replaceLightNums( vertexShader, parameters );
  46498. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  46499. fragmentShader = resolveIncludes( fragmentShader );
  46500. fragmentShader = replaceLightNums( fragmentShader, parameters );
  46501. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  46502. vertexShader = unrollLoops( vertexShader );
  46503. fragmentShader = unrollLoops( fragmentShader );
  46504. if ( parameters.isRawShaderMaterial !== true ) {
  46505. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  46506. versionString = '#version 300 es\n';
  46507. prefixVertex = [
  46508. customVertexExtensions,
  46509. '#define attribute in',
  46510. '#define varying out',
  46511. '#define texture2D texture'
  46512. ].join( '\n' ) + '\n' + prefixVertex;
  46513. prefixFragment = [
  46514. '#define varying in',
  46515. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  46516. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  46517. '#define gl_FragDepthEXT gl_FragDepth',
  46518. '#define texture2D texture',
  46519. '#define textureCube texture',
  46520. '#define texture2DProj textureProj',
  46521. '#define texture2DLodEXT textureLod',
  46522. '#define texture2DProjLodEXT textureProjLod',
  46523. '#define textureCubeLodEXT textureLod',
  46524. '#define texture2DGradEXT textureGrad',
  46525. '#define texture2DProjGradEXT textureProjGrad',
  46526. '#define textureCubeGradEXT textureGrad'
  46527. ].join( '\n' ) + '\n' + prefixFragment;
  46528. }
  46529. const vertexGlsl = versionString + prefixVertex + vertexShader;
  46530. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  46531. // console.log( '*VERTEX*', vertexGlsl );
  46532. // console.log( '*FRAGMENT*', fragmentGlsl );
  46533. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  46534. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  46535. gl.attachShader( program, glVertexShader );
  46536. gl.attachShader( program, glFragmentShader );
  46537. // Force a particular attribute to index 0.
  46538. if ( parameters.index0AttributeName !== undefined ) {
  46539. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  46540. } else if ( parameters.morphTargets === true ) {
  46541. // programs with morphTargets displace position out of attribute 0
  46542. gl.bindAttribLocation( program, 0, 'position' );
  46543. }
  46544. gl.linkProgram( program );
  46545. function onFirstUse( self ) {
  46546. // check for link errors
  46547. if ( renderer.debug.checkShaderErrors ) {
  46548. const programInfoLog = gl.getProgramInfoLog( program ) || '';
  46549. const vertexShaderInfoLog = gl.getShaderInfoLog( glVertexShader ) || '';
  46550. const fragmentShaderInfoLog = gl.getShaderInfoLog( glFragmentShader ) || '';
  46551. const programLog = programInfoLog.trim();
  46552. const vertexLog = vertexShaderInfoLog.trim();
  46553. const fragmentLog = fragmentShaderInfoLog.trim();
  46554. let runnable = true;
  46555. let haveDiagnostics = true;
  46556. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  46557. runnable = false;
  46558. if ( typeof renderer.debug.onShaderError === 'function' ) {
  46559. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  46560. } else {
  46561. // default error reporting
  46562. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  46563. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  46564. console.error(
  46565. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  46566. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  46567. 'Material Name: ' + self.name + '\n' +
  46568. 'Material Type: ' + self.type + '\n\n' +
  46569. 'Program Info Log: ' + programLog + '\n' +
  46570. vertexErrors + '\n' +
  46571. fragmentErrors
  46572. );
  46573. }
  46574. } else if ( programLog !== '' ) {
  46575. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  46576. } else if ( vertexLog === '' || fragmentLog === '' ) {
  46577. haveDiagnostics = false;
  46578. }
  46579. if ( haveDiagnostics ) {
  46580. self.diagnostics = {
  46581. runnable: runnable,
  46582. programLog: programLog,
  46583. vertexShader: {
  46584. log: vertexLog,
  46585. prefix: prefixVertex
  46586. },
  46587. fragmentShader: {
  46588. log: fragmentLog,
  46589. prefix: prefixFragment
  46590. }
  46591. };
  46592. }
  46593. }
  46594. // Clean up
  46595. // Crashes in iOS9 and iOS10. #18402
  46596. // gl.detachShader( program, glVertexShader );
  46597. // gl.detachShader( program, glFragmentShader );
  46598. gl.deleteShader( glVertexShader );
  46599. gl.deleteShader( glFragmentShader );
  46600. cachedUniforms = new WebGLUniforms( gl, program );
  46601. cachedAttributes = fetchAttributeLocations( gl, program );
  46602. }
  46603. // set up caching for uniform locations
  46604. let cachedUniforms;
  46605. this.getUniforms = function () {
  46606. if ( cachedUniforms === undefined ) {
  46607. // Populates cachedUniforms and cachedAttributes
  46608. onFirstUse( this );
  46609. }
  46610. return cachedUniforms;
  46611. };
  46612. // set up caching for attribute locations
  46613. let cachedAttributes;
  46614. this.getAttributes = function () {
  46615. if ( cachedAttributes === undefined ) {
  46616. // Populates cachedAttributes and cachedUniforms
  46617. onFirstUse( this );
  46618. }
  46619. return cachedAttributes;
  46620. };
  46621. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  46622. // flag the program as ready immediately. It may cause a stall when it's first used.
  46623. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  46624. this.isReady = function () {
  46625. if ( programReady === false ) {
  46626. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  46627. }
  46628. return programReady;
  46629. };
  46630. // free resource
  46631. this.destroy = function () {
  46632. bindingStates.releaseStatesOfProgram( this );
  46633. gl.deleteProgram( program );
  46634. this.program = undefined;
  46635. };
  46636. //
  46637. this.type = parameters.shaderType;
  46638. this.name = parameters.shaderName;
  46639. this.id = programIdCount ++;
  46640. this.cacheKey = cacheKey;
  46641. this.usedTimes = 1;
  46642. this.program = program;
  46643. this.vertexShader = glVertexShader;
  46644. this.fragmentShader = glFragmentShader;
  46645. return this;
  46646. }
  46647. let _id = 0;
  46648. class WebGLShaderCache {
  46649. constructor() {
  46650. this.shaderCache = new Map();
  46651. this.materialCache = new Map();
  46652. }
  46653. update( material ) {
  46654. const vertexShader = material.vertexShader;
  46655. const fragmentShader = material.fragmentShader;
  46656. const vertexShaderStage = this._getShaderStage( vertexShader );
  46657. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  46658. const materialShaders = this._getShaderCacheForMaterial( material );
  46659. if ( materialShaders.has( vertexShaderStage ) === false ) {
  46660. materialShaders.add( vertexShaderStage );
  46661. vertexShaderStage.usedTimes ++;
  46662. }
  46663. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  46664. materialShaders.add( fragmentShaderStage );
  46665. fragmentShaderStage.usedTimes ++;
  46666. }
  46667. return this;
  46668. }
  46669. remove( material ) {
  46670. const materialShaders = this.materialCache.get( material );
  46671. for ( const shaderStage of materialShaders ) {
  46672. shaderStage.usedTimes --;
  46673. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  46674. }
  46675. this.materialCache.delete( material );
  46676. return this;
  46677. }
  46678. getVertexShaderID( material ) {
  46679. return this._getShaderStage( material.vertexShader ).id;
  46680. }
  46681. getFragmentShaderID( material ) {
  46682. return this._getShaderStage( material.fragmentShader ).id;
  46683. }
  46684. dispose() {
  46685. this.shaderCache.clear();
  46686. this.materialCache.clear();
  46687. }
  46688. _getShaderCacheForMaterial( material ) {
  46689. const cache = this.materialCache;
  46690. let set = cache.get( material );
  46691. if ( set === undefined ) {
  46692. set = new Set();
  46693. cache.set( material, set );
  46694. }
  46695. return set;
  46696. }
  46697. _getShaderStage( code ) {
  46698. const cache = this.shaderCache;
  46699. let stage = cache.get( code );
  46700. if ( stage === undefined ) {
  46701. stage = new WebGLShaderStage( code );
  46702. cache.set( code, stage );
  46703. }
  46704. return stage;
  46705. }
  46706. }
  46707. class WebGLShaderStage {
  46708. constructor( code ) {
  46709. this.id = _id ++;
  46710. this.code = code;
  46711. this.usedTimes = 0;
  46712. }
  46713. }
  46714. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  46715. const _programLayers = new Layers();
  46716. const _customShaders = new WebGLShaderCache();
  46717. const _activeChannels = new Set();
  46718. const programs = [];
  46719. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  46720. const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  46721. let precision = capabilities.precision;
  46722. const shaderIDs = {
  46723. MeshDepthMaterial: 'depth',
  46724. MeshDistanceMaterial: 'distanceRGBA',
  46725. MeshNormalMaterial: 'normal',
  46726. MeshBasicMaterial: 'basic',
  46727. MeshLambertMaterial: 'lambert',
  46728. MeshPhongMaterial: 'phong',
  46729. MeshToonMaterial: 'toon',
  46730. MeshStandardMaterial: 'physical',
  46731. MeshPhysicalMaterial: 'physical',
  46732. MeshMatcapMaterial: 'matcap',
  46733. LineBasicMaterial: 'basic',
  46734. LineDashedMaterial: 'dashed',
  46735. PointsMaterial: 'points',
  46736. ShadowMaterial: 'shadow',
  46737. SpriteMaterial: 'sprite'
  46738. };
  46739. function getChannel( value ) {
  46740. _activeChannels.add( value );
  46741. if ( value === 0 ) return 'uv';
  46742. return `uv${ value }`;
  46743. }
  46744. function getParameters( material, lights, shadows, scene, object ) {
  46745. const fog = scene.fog;
  46746. const geometry = object.geometry;
  46747. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  46748. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  46749. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  46750. const shaderID = shaderIDs[ material.type ];
  46751. // heuristics to create shader parameters according to lights in the scene
  46752. // (not to blow over maxLights budget)
  46753. if ( material.precision !== null ) {
  46754. precision = capabilities.getMaxPrecision( material.precision );
  46755. if ( precision !== material.precision ) {
  46756. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  46757. }
  46758. }
  46759. //
  46760. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  46761. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  46762. let morphTextureStride = 0;
  46763. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  46764. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  46765. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  46766. //
  46767. let vertexShader, fragmentShader;
  46768. let customVertexShaderID, customFragmentShaderID;
  46769. if ( shaderID ) {
  46770. const shader = ShaderLib[ shaderID ];
  46771. vertexShader = shader.vertexShader;
  46772. fragmentShader = shader.fragmentShader;
  46773. } else {
  46774. vertexShader = material.vertexShader;
  46775. fragmentShader = material.fragmentShader;
  46776. _customShaders.update( material );
  46777. customVertexShaderID = _customShaders.getVertexShaderID( material );
  46778. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  46779. }
  46780. const currentRenderTarget = renderer.getRenderTarget();
  46781. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  46782. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  46783. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  46784. const HAS_MAP = !! material.map;
  46785. const HAS_MATCAP = !! material.matcap;
  46786. const HAS_ENVMAP = !! envMap;
  46787. const HAS_AOMAP = !! material.aoMap;
  46788. const HAS_LIGHTMAP = !! material.lightMap;
  46789. const HAS_BUMPMAP = !! material.bumpMap;
  46790. const HAS_NORMALMAP = !! material.normalMap;
  46791. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  46792. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  46793. const HAS_METALNESSMAP = !! material.metalnessMap;
  46794. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  46795. const HAS_ANISOTROPY = material.anisotropy > 0;
  46796. const HAS_CLEARCOAT = material.clearcoat > 0;
  46797. const HAS_DISPERSION = material.dispersion > 0;
  46798. const HAS_IRIDESCENCE = material.iridescence > 0;
  46799. const HAS_SHEEN = material.sheen > 0;
  46800. const HAS_TRANSMISSION = material.transmission > 0;
  46801. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  46802. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  46803. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  46804. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  46805. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  46806. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  46807. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  46808. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  46809. const HAS_SPECULARMAP = !! material.specularMap;
  46810. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  46811. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  46812. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  46813. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  46814. const HAS_GRADIENTMAP = !! material.gradientMap;
  46815. const HAS_ALPHAMAP = !! material.alphaMap;
  46816. const HAS_ALPHATEST = material.alphaTest > 0;
  46817. const HAS_ALPHAHASH = !! material.alphaHash;
  46818. const HAS_EXTENSIONS = !! material.extensions;
  46819. let toneMapping = NoToneMapping;
  46820. if ( material.toneMapped ) {
  46821. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  46822. toneMapping = renderer.toneMapping;
  46823. }
  46824. }
  46825. const parameters = {
  46826. shaderID: shaderID,
  46827. shaderType: material.type,
  46828. shaderName: material.name,
  46829. vertexShader: vertexShader,
  46830. fragmentShader: fragmentShader,
  46831. defines: material.defines,
  46832. customVertexShaderID: customVertexShaderID,
  46833. customFragmentShaderID: customFragmentShaderID,
  46834. isRawShaderMaterial: material.isRawShaderMaterial === true,
  46835. glslVersion: material.glslVersion,
  46836. precision: precision,
  46837. batching: IS_BATCHEDMESH,
  46838. batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null,
  46839. instancing: IS_INSTANCEDMESH,
  46840. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  46841. instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
  46842. supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
  46843. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  46844. alphaToCoverage: !! material.alphaToCoverage,
  46845. map: HAS_MAP,
  46846. matcap: HAS_MATCAP,
  46847. envMap: HAS_ENVMAP,
  46848. envMapMode: HAS_ENVMAP && envMap.mapping,
  46849. envMapCubeUVHeight: envMapCubeUVHeight,
  46850. aoMap: HAS_AOMAP,
  46851. lightMap: HAS_LIGHTMAP,
  46852. bumpMap: HAS_BUMPMAP,
  46853. normalMap: HAS_NORMALMAP,
  46854. displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
  46855. emissiveMap: HAS_EMISSIVEMAP,
  46856. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  46857. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  46858. metalnessMap: HAS_METALNESSMAP,
  46859. roughnessMap: HAS_ROUGHNESSMAP,
  46860. anisotropy: HAS_ANISOTROPY,
  46861. anisotropyMap: HAS_ANISOTROPYMAP,
  46862. clearcoat: HAS_CLEARCOAT,
  46863. clearcoatMap: HAS_CLEARCOATMAP,
  46864. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  46865. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  46866. dispersion: HAS_DISPERSION,
  46867. iridescence: HAS_IRIDESCENCE,
  46868. iridescenceMap: HAS_IRIDESCENCEMAP,
  46869. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  46870. sheen: HAS_SHEEN,
  46871. sheenColorMap: HAS_SHEEN_COLORMAP,
  46872. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  46873. specularMap: HAS_SPECULARMAP,
  46874. specularColorMap: HAS_SPECULAR_COLORMAP,
  46875. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  46876. transmission: HAS_TRANSMISSION,
  46877. transmissionMap: HAS_TRANSMISSIONMAP,
  46878. thicknessMap: HAS_THICKNESSMAP,
  46879. gradientMap: HAS_GRADIENTMAP,
  46880. opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
  46881. alphaMap: HAS_ALPHAMAP,
  46882. alphaTest: HAS_ALPHATEST,
  46883. alphaHash: HAS_ALPHAHASH,
  46884. combine: material.combine,
  46885. //
  46886. mapUv: HAS_MAP && getChannel( material.map.channel ),
  46887. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  46888. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  46889. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  46890. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  46891. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  46892. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  46893. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  46894. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  46895. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  46896. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  46897. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  46898. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  46899. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  46900. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  46901. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  46902. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  46903. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  46904. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  46905. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  46906. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  46907. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  46908. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  46909. //
  46910. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  46911. vertexColors: material.vertexColors,
  46912. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  46913. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  46914. fog: !! fog,
  46915. useFog: material.fog === true,
  46916. fogExp2: ( !! fog && fog.isFogExp2 ),
  46917. flatShading: ( material.flatShading === true && material.wireframe === false ),
  46918. sizeAttenuation: material.sizeAttenuation === true,
  46919. logarithmicDepthBuffer: logarithmicDepthBuffer,
  46920. reversedDepthBuffer: reversedDepthBuffer,
  46921. skinning: object.isSkinnedMesh === true,
  46922. morphTargets: geometry.morphAttributes.position !== undefined,
  46923. morphNormals: geometry.morphAttributes.normal !== undefined,
  46924. morphColors: geometry.morphAttributes.color !== undefined,
  46925. morphTargetsCount: morphTargetsCount,
  46926. morphTextureStride: morphTextureStride,
  46927. numDirLights: lights.directional.length,
  46928. numPointLights: lights.point.length,
  46929. numSpotLights: lights.spot.length,
  46930. numSpotLightMaps: lights.spotLightMap.length,
  46931. numRectAreaLights: lights.rectArea.length,
  46932. numHemiLights: lights.hemi.length,
  46933. numDirLightShadows: lights.directionalShadowMap.length,
  46934. numPointLightShadows: lights.pointShadowMap.length,
  46935. numSpotLightShadows: lights.spotShadowMap.length,
  46936. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  46937. numLightProbes: lights.numLightProbes,
  46938. numClippingPlanes: clipping.numPlanes,
  46939. numClipIntersection: clipping.numIntersection,
  46940. dithering: material.dithering,
  46941. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  46942. shadowMapType: renderer.shadowMap.type,
  46943. toneMapping: toneMapping,
  46944. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  46945. decodeVideoTextureEmissive: HAS_EMISSIVEMAP && ( material.emissiveMap.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.emissiveMap.colorSpace ) === SRGBTransfer ),
  46946. premultipliedAlpha: material.premultipliedAlpha,
  46947. doubleSided: material.side === DoubleSide,
  46948. flipSided: material.side === BackSide,
  46949. useDepthPacking: material.depthPacking >= 0,
  46950. depthPacking: material.depthPacking || 0,
  46951. index0AttributeName: material.index0AttributeName,
  46952. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ),
  46953. extensionMultiDraw: ( HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH ) && extensions.has( 'WEBGL_multi_draw' ),
  46954. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  46955. customProgramCacheKey: material.customProgramCacheKey()
  46956. };
  46957. // the usage of getChannel() determines the active texture channels for this shader
  46958. parameters.vertexUv1s = _activeChannels.has( 1 );
  46959. parameters.vertexUv2s = _activeChannels.has( 2 );
  46960. parameters.vertexUv3s = _activeChannels.has( 3 );
  46961. _activeChannels.clear();
  46962. return parameters;
  46963. }
  46964. function getProgramCacheKey( parameters ) {
  46965. const array = [];
  46966. if ( parameters.shaderID ) {
  46967. array.push( parameters.shaderID );
  46968. } else {
  46969. array.push( parameters.customVertexShaderID );
  46970. array.push( parameters.customFragmentShaderID );
  46971. }
  46972. if ( parameters.defines !== undefined ) {
  46973. for ( const name in parameters.defines ) {
  46974. array.push( name );
  46975. array.push( parameters.defines[ name ] );
  46976. }
  46977. }
  46978. if ( parameters.isRawShaderMaterial === false ) {
  46979. getProgramCacheKeyParameters( array, parameters );
  46980. getProgramCacheKeyBooleans( array, parameters );
  46981. array.push( renderer.outputColorSpace );
  46982. }
  46983. array.push( parameters.customProgramCacheKey );
  46984. return array.join();
  46985. }
  46986. function getProgramCacheKeyParameters( array, parameters ) {
  46987. array.push( parameters.precision );
  46988. array.push( parameters.outputColorSpace );
  46989. array.push( parameters.envMapMode );
  46990. array.push( parameters.envMapCubeUVHeight );
  46991. array.push( parameters.mapUv );
  46992. array.push( parameters.alphaMapUv );
  46993. array.push( parameters.lightMapUv );
  46994. array.push( parameters.aoMapUv );
  46995. array.push( parameters.bumpMapUv );
  46996. array.push( parameters.normalMapUv );
  46997. array.push( parameters.displacementMapUv );
  46998. array.push( parameters.emissiveMapUv );
  46999. array.push( parameters.metalnessMapUv );
  47000. array.push( parameters.roughnessMapUv );
  47001. array.push( parameters.anisotropyMapUv );
  47002. array.push( parameters.clearcoatMapUv );
  47003. array.push( parameters.clearcoatNormalMapUv );
  47004. array.push( parameters.clearcoatRoughnessMapUv );
  47005. array.push( parameters.iridescenceMapUv );
  47006. array.push( parameters.iridescenceThicknessMapUv );
  47007. array.push( parameters.sheenColorMapUv );
  47008. array.push( parameters.sheenRoughnessMapUv );
  47009. array.push( parameters.specularMapUv );
  47010. array.push( parameters.specularColorMapUv );
  47011. array.push( parameters.specularIntensityMapUv );
  47012. array.push( parameters.transmissionMapUv );
  47013. array.push( parameters.thicknessMapUv );
  47014. array.push( parameters.combine );
  47015. array.push( parameters.fogExp2 );
  47016. array.push( parameters.sizeAttenuation );
  47017. array.push( parameters.morphTargetsCount );
  47018. array.push( parameters.morphAttributeCount );
  47019. array.push( parameters.numDirLights );
  47020. array.push( parameters.numPointLights );
  47021. array.push( parameters.numSpotLights );
  47022. array.push( parameters.numSpotLightMaps );
  47023. array.push( parameters.numHemiLights );
  47024. array.push( parameters.numRectAreaLights );
  47025. array.push( parameters.numDirLightShadows );
  47026. array.push( parameters.numPointLightShadows );
  47027. array.push( parameters.numSpotLightShadows );
  47028. array.push( parameters.numSpotLightShadowsWithMaps );
  47029. array.push( parameters.numLightProbes );
  47030. array.push( parameters.shadowMapType );
  47031. array.push( parameters.toneMapping );
  47032. array.push( parameters.numClippingPlanes );
  47033. array.push( parameters.numClipIntersection );
  47034. array.push( parameters.depthPacking );
  47035. }
  47036. function getProgramCacheKeyBooleans( array, parameters ) {
  47037. _programLayers.disableAll();
  47038. if ( parameters.supportsVertexTextures )
  47039. _programLayers.enable( 0 );
  47040. if ( parameters.instancing )
  47041. _programLayers.enable( 1 );
  47042. if ( parameters.instancingColor )
  47043. _programLayers.enable( 2 );
  47044. if ( parameters.instancingMorph )
  47045. _programLayers.enable( 3 );
  47046. if ( parameters.matcap )
  47047. _programLayers.enable( 4 );
  47048. if ( parameters.envMap )
  47049. _programLayers.enable( 5 );
  47050. if ( parameters.normalMapObjectSpace )
  47051. _programLayers.enable( 6 );
  47052. if ( parameters.normalMapTangentSpace )
  47053. _programLayers.enable( 7 );
  47054. if ( parameters.clearcoat )
  47055. _programLayers.enable( 8 );
  47056. if ( parameters.iridescence )
  47057. _programLayers.enable( 9 );
  47058. if ( parameters.alphaTest )
  47059. _programLayers.enable( 10 );
  47060. if ( parameters.vertexColors )
  47061. _programLayers.enable( 11 );
  47062. if ( parameters.vertexAlphas )
  47063. _programLayers.enable( 12 );
  47064. if ( parameters.vertexUv1s )
  47065. _programLayers.enable( 13 );
  47066. if ( parameters.vertexUv2s )
  47067. _programLayers.enable( 14 );
  47068. if ( parameters.vertexUv3s )
  47069. _programLayers.enable( 15 );
  47070. if ( parameters.vertexTangents )
  47071. _programLayers.enable( 16 );
  47072. if ( parameters.anisotropy )
  47073. _programLayers.enable( 17 );
  47074. if ( parameters.alphaHash )
  47075. _programLayers.enable( 18 );
  47076. if ( parameters.batching )
  47077. _programLayers.enable( 19 );
  47078. if ( parameters.dispersion )
  47079. _programLayers.enable( 20 );
  47080. if ( parameters.batchingColor )
  47081. _programLayers.enable( 21 );
  47082. if ( parameters.gradientMap )
  47083. _programLayers.enable( 22 );
  47084. array.push( _programLayers.mask );
  47085. _programLayers.disableAll();
  47086. if ( parameters.fog )
  47087. _programLayers.enable( 0 );
  47088. if ( parameters.useFog )
  47089. _programLayers.enable( 1 );
  47090. if ( parameters.flatShading )
  47091. _programLayers.enable( 2 );
  47092. if ( parameters.logarithmicDepthBuffer )
  47093. _programLayers.enable( 3 );
  47094. if ( parameters.reversedDepthBuffer )
  47095. _programLayers.enable( 4 );
  47096. if ( parameters.skinning )
  47097. _programLayers.enable( 5 );
  47098. if ( parameters.morphTargets )
  47099. _programLayers.enable( 6 );
  47100. if ( parameters.morphNormals )
  47101. _programLayers.enable( 7 );
  47102. if ( parameters.morphColors )
  47103. _programLayers.enable( 8 );
  47104. if ( parameters.premultipliedAlpha )
  47105. _programLayers.enable( 9 );
  47106. if ( parameters.shadowMapEnabled )
  47107. _programLayers.enable( 10 );
  47108. if ( parameters.doubleSided )
  47109. _programLayers.enable( 11 );
  47110. if ( parameters.flipSided )
  47111. _programLayers.enable( 12 );
  47112. if ( parameters.useDepthPacking )
  47113. _programLayers.enable( 13 );
  47114. if ( parameters.dithering )
  47115. _programLayers.enable( 14 );
  47116. if ( parameters.transmission )
  47117. _programLayers.enable( 15 );
  47118. if ( parameters.sheen )
  47119. _programLayers.enable( 16 );
  47120. if ( parameters.opaque )
  47121. _programLayers.enable( 17 );
  47122. if ( parameters.pointsUvs )
  47123. _programLayers.enable( 18 );
  47124. if ( parameters.decodeVideoTexture )
  47125. _programLayers.enable( 19 );
  47126. if ( parameters.decodeVideoTextureEmissive )
  47127. _programLayers.enable( 20 );
  47128. if ( parameters.alphaToCoverage )
  47129. _programLayers.enable( 21 );
  47130. array.push( _programLayers.mask );
  47131. }
  47132. function getUniforms( material ) {
  47133. const shaderID = shaderIDs[ material.type ];
  47134. let uniforms;
  47135. if ( shaderID ) {
  47136. const shader = ShaderLib[ shaderID ];
  47137. uniforms = UniformsUtils.clone( shader.uniforms );
  47138. } else {
  47139. uniforms = material.uniforms;
  47140. }
  47141. return uniforms;
  47142. }
  47143. function acquireProgram( parameters, cacheKey ) {
  47144. let program;
  47145. // Check if code has been already compiled
  47146. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  47147. const preexistingProgram = programs[ p ];
  47148. if ( preexistingProgram.cacheKey === cacheKey ) {
  47149. program = preexistingProgram;
  47150. ++ program.usedTimes;
  47151. break;
  47152. }
  47153. }
  47154. if ( program === undefined ) {
  47155. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  47156. programs.push( program );
  47157. }
  47158. return program;
  47159. }
  47160. function releaseProgram( program ) {
  47161. if ( -- program.usedTimes === 0 ) {
  47162. // Remove from unordered set
  47163. const i = programs.indexOf( program );
  47164. programs[ i ] = programs[ programs.length - 1 ];
  47165. programs.pop();
  47166. // Free WebGL resources
  47167. program.destroy();
  47168. }
  47169. }
  47170. function releaseShaderCache( material ) {
  47171. _customShaders.remove( material );
  47172. }
  47173. function dispose() {
  47174. _customShaders.dispose();
  47175. }
  47176. return {
  47177. getParameters: getParameters,
  47178. getProgramCacheKey: getProgramCacheKey,
  47179. getUniforms: getUniforms,
  47180. acquireProgram: acquireProgram,
  47181. releaseProgram: releaseProgram,
  47182. releaseShaderCache: releaseShaderCache,
  47183. // Exposed for resource monitoring & error feedback via renderer.info:
  47184. programs: programs,
  47185. dispose: dispose
  47186. };
  47187. }
  47188. function WebGLProperties() {
  47189. let properties = new WeakMap();
  47190. function has( object ) {
  47191. return properties.has( object );
  47192. }
  47193. function get( object ) {
  47194. let map = properties.get( object );
  47195. if ( map === undefined ) {
  47196. map = {};
  47197. properties.set( object, map );
  47198. }
  47199. return map;
  47200. }
  47201. function remove( object ) {
  47202. properties.delete( object );
  47203. }
  47204. function update( object, key, value ) {
  47205. properties.get( object )[ key ] = value;
  47206. }
  47207. function dispose() {
  47208. properties = new WeakMap();
  47209. }
  47210. return {
  47211. has: has,
  47212. get: get,
  47213. remove: remove,
  47214. update: update,
  47215. dispose: dispose
  47216. };
  47217. }
  47218. function painterSortStable( a, b ) {
  47219. if ( a.groupOrder !== b.groupOrder ) {
  47220. return a.groupOrder - b.groupOrder;
  47221. } else if ( a.renderOrder !== b.renderOrder ) {
  47222. return a.renderOrder - b.renderOrder;
  47223. } else if ( a.material.id !== b.material.id ) {
  47224. return a.material.id - b.material.id;
  47225. } else if ( a.z !== b.z ) {
  47226. return a.z - b.z;
  47227. } else {
  47228. return a.id - b.id;
  47229. }
  47230. }
  47231. function reversePainterSortStable( a, b ) {
  47232. if ( a.groupOrder !== b.groupOrder ) {
  47233. return a.groupOrder - b.groupOrder;
  47234. } else if ( a.renderOrder !== b.renderOrder ) {
  47235. return a.renderOrder - b.renderOrder;
  47236. } else if ( a.z !== b.z ) {
  47237. return b.z - a.z;
  47238. } else {
  47239. return a.id - b.id;
  47240. }
  47241. }
  47242. function WebGLRenderList() {
  47243. const renderItems = [];
  47244. let renderItemsIndex = 0;
  47245. const opaque = [];
  47246. const transmissive = [];
  47247. const transparent = [];
  47248. function init() {
  47249. renderItemsIndex = 0;
  47250. opaque.length = 0;
  47251. transmissive.length = 0;
  47252. transparent.length = 0;
  47253. }
  47254. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  47255. let renderItem = renderItems[ renderItemsIndex ];
  47256. if ( renderItem === undefined ) {
  47257. renderItem = {
  47258. id: object.id,
  47259. object: object,
  47260. geometry: geometry,
  47261. material: material,
  47262. groupOrder: groupOrder,
  47263. renderOrder: object.renderOrder,
  47264. z: z,
  47265. group: group
  47266. };
  47267. renderItems[ renderItemsIndex ] = renderItem;
  47268. } else {
  47269. renderItem.id = object.id;
  47270. renderItem.object = object;
  47271. renderItem.geometry = geometry;
  47272. renderItem.material = material;
  47273. renderItem.groupOrder = groupOrder;
  47274. renderItem.renderOrder = object.renderOrder;
  47275. renderItem.z = z;
  47276. renderItem.group = group;
  47277. }
  47278. renderItemsIndex ++;
  47279. return renderItem;
  47280. }
  47281. function push( object, geometry, material, groupOrder, z, group ) {
  47282. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  47283. if ( material.transmission > 0.0 ) {
  47284. transmissive.push( renderItem );
  47285. } else if ( material.transparent === true ) {
  47286. transparent.push( renderItem );
  47287. } else {
  47288. opaque.push( renderItem );
  47289. }
  47290. }
  47291. function unshift( object, geometry, material, groupOrder, z, group ) {
  47292. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  47293. if ( material.transmission > 0.0 ) {
  47294. transmissive.unshift( renderItem );
  47295. } else if ( material.transparent === true ) {
  47296. transparent.unshift( renderItem );
  47297. } else {
  47298. opaque.unshift( renderItem );
  47299. }
  47300. }
  47301. function sort( customOpaqueSort, customTransparentSort ) {
  47302. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  47303. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  47304. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  47305. }
  47306. function finish() {
  47307. // Clear references from inactive renderItems in the list
  47308. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  47309. const renderItem = renderItems[ i ];
  47310. if ( renderItem.id === null ) break;
  47311. renderItem.id = null;
  47312. renderItem.object = null;
  47313. renderItem.geometry = null;
  47314. renderItem.material = null;
  47315. renderItem.group = null;
  47316. }
  47317. }
  47318. return {
  47319. opaque: opaque,
  47320. transmissive: transmissive,
  47321. transparent: transparent,
  47322. init: init,
  47323. push: push,
  47324. unshift: unshift,
  47325. finish: finish,
  47326. sort: sort
  47327. };
  47328. }
  47329. function WebGLRenderLists() {
  47330. let lists = new WeakMap();
  47331. function get( scene, renderCallDepth ) {
  47332. const listArray = lists.get( scene );
  47333. let list;
  47334. if ( listArray === undefined ) {
  47335. list = new WebGLRenderList();
  47336. lists.set( scene, [ list ] );
  47337. } else {
  47338. if ( renderCallDepth >= listArray.length ) {
  47339. list = new WebGLRenderList();
  47340. listArray.push( list );
  47341. } else {
  47342. list = listArray[ renderCallDepth ];
  47343. }
  47344. }
  47345. return list;
  47346. }
  47347. function dispose() {
  47348. lists = new WeakMap();
  47349. }
  47350. return {
  47351. get: get,
  47352. dispose: dispose
  47353. };
  47354. }
  47355. function UniformsCache() {
  47356. const lights = {};
  47357. return {
  47358. get: function ( light ) {
  47359. if ( lights[ light.id ] !== undefined ) {
  47360. return lights[ light.id ];
  47361. }
  47362. let uniforms;
  47363. switch ( light.type ) {
  47364. case 'DirectionalLight':
  47365. uniforms = {
  47366. direction: new Vector3(),
  47367. color: new Color()
  47368. };
  47369. break;
  47370. case 'SpotLight':
  47371. uniforms = {
  47372. position: new Vector3(),
  47373. direction: new Vector3(),
  47374. color: new Color(),
  47375. distance: 0,
  47376. coneCos: 0,
  47377. penumbraCos: 0,
  47378. decay: 0
  47379. };
  47380. break;
  47381. case 'PointLight':
  47382. uniforms = {
  47383. position: new Vector3(),
  47384. color: new Color(),
  47385. distance: 0,
  47386. decay: 0
  47387. };
  47388. break;
  47389. case 'HemisphereLight':
  47390. uniforms = {
  47391. direction: new Vector3(),
  47392. skyColor: new Color(),
  47393. groundColor: new Color()
  47394. };
  47395. break;
  47396. case 'RectAreaLight':
  47397. uniforms = {
  47398. color: new Color(),
  47399. position: new Vector3(),
  47400. halfWidth: new Vector3(),
  47401. halfHeight: new Vector3()
  47402. };
  47403. break;
  47404. }
  47405. lights[ light.id ] = uniforms;
  47406. return uniforms;
  47407. }
  47408. };
  47409. }
  47410. function ShadowUniformsCache() {
  47411. const lights = {};
  47412. return {
  47413. get: function ( light ) {
  47414. if ( lights[ light.id ] !== undefined ) {
  47415. return lights[ light.id ];
  47416. }
  47417. let uniforms;
  47418. switch ( light.type ) {
  47419. case 'DirectionalLight':
  47420. uniforms = {
  47421. shadowIntensity: 1,
  47422. shadowBias: 0,
  47423. shadowNormalBias: 0,
  47424. shadowRadius: 1,
  47425. shadowMapSize: new Vector2()
  47426. };
  47427. break;
  47428. case 'SpotLight':
  47429. uniforms = {
  47430. shadowIntensity: 1,
  47431. shadowBias: 0,
  47432. shadowNormalBias: 0,
  47433. shadowRadius: 1,
  47434. shadowMapSize: new Vector2()
  47435. };
  47436. break;
  47437. case 'PointLight':
  47438. uniforms = {
  47439. shadowIntensity: 1,
  47440. shadowBias: 0,
  47441. shadowNormalBias: 0,
  47442. shadowRadius: 1,
  47443. shadowMapSize: new Vector2(),
  47444. shadowCameraNear: 1,
  47445. shadowCameraFar: 1000
  47446. };
  47447. break;
  47448. // TODO (abelnation): set RectAreaLight shadow uniforms
  47449. }
  47450. lights[ light.id ] = uniforms;
  47451. return uniforms;
  47452. }
  47453. };
  47454. }
  47455. let nextVersion = 0;
  47456. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  47457. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  47458. }
  47459. function WebGLLights( extensions ) {
  47460. const cache = new UniformsCache();
  47461. const shadowCache = ShadowUniformsCache();
  47462. const state = {
  47463. version: 0,
  47464. hash: {
  47465. directionalLength: -1,
  47466. pointLength: -1,
  47467. spotLength: -1,
  47468. rectAreaLength: -1,
  47469. hemiLength: -1,
  47470. numDirectionalShadows: -1,
  47471. numPointShadows: -1,
  47472. numSpotShadows: -1,
  47473. numSpotMaps: -1,
  47474. numLightProbes: -1
  47475. },
  47476. ambient: [ 0, 0, 0 ],
  47477. probe: [],
  47478. directional: [],
  47479. directionalShadow: [],
  47480. directionalShadowMap: [],
  47481. directionalShadowMatrix: [],
  47482. spot: [],
  47483. spotLightMap: [],
  47484. spotShadow: [],
  47485. spotShadowMap: [],
  47486. spotLightMatrix: [],
  47487. rectArea: [],
  47488. rectAreaLTC1: null,
  47489. rectAreaLTC2: null,
  47490. point: [],
  47491. pointShadow: [],
  47492. pointShadowMap: [],
  47493. pointShadowMatrix: [],
  47494. hemi: [],
  47495. numSpotLightShadowsWithMaps: 0,
  47496. numLightProbes: 0
  47497. };
  47498. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  47499. const vector3 = new Vector3();
  47500. const matrix4 = new Matrix4();
  47501. const matrix42 = new Matrix4();
  47502. function setup( lights ) {
  47503. let r = 0, g = 0, b = 0;
  47504. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  47505. let directionalLength = 0;
  47506. let pointLength = 0;
  47507. let spotLength = 0;
  47508. let rectAreaLength = 0;
  47509. let hemiLength = 0;
  47510. let numDirectionalShadows = 0;
  47511. let numPointShadows = 0;
  47512. let numSpotShadows = 0;
  47513. let numSpotMaps = 0;
  47514. let numSpotShadowsWithMaps = 0;
  47515. let numLightProbes = 0;
  47516. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  47517. lights.sort( shadowCastingAndTexturingLightsFirst );
  47518. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  47519. const light = lights[ i ];
  47520. const color = light.color;
  47521. const intensity = light.intensity;
  47522. const distance = light.distance;
  47523. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  47524. if ( light.isAmbientLight ) {
  47525. r += color.r * intensity;
  47526. g += color.g * intensity;
  47527. b += color.b * intensity;
  47528. } else if ( light.isLightProbe ) {
  47529. for ( let j = 0; j < 9; j ++ ) {
  47530. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  47531. }
  47532. numLightProbes ++;
  47533. } else if ( light.isDirectionalLight ) {
  47534. const uniforms = cache.get( light );
  47535. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  47536. if ( light.castShadow ) {
  47537. const shadow = light.shadow;
  47538. const shadowUniforms = shadowCache.get( light );
  47539. shadowUniforms.shadowIntensity = shadow.intensity;
  47540. shadowUniforms.shadowBias = shadow.bias;
  47541. shadowUniforms.shadowNormalBias = shadow.normalBias;
  47542. shadowUniforms.shadowRadius = shadow.radius;
  47543. shadowUniforms.shadowMapSize = shadow.mapSize;
  47544. state.directionalShadow[ directionalLength ] = shadowUniforms;
  47545. state.directionalShadowMap[ directionalLength ] = shadowMap;
  47546. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  47547. numDirectionalShadows ++;
  47548. }
  47549. state.directional[ directionalLength ] = uniforms;
  47550. directionalLength ++;
  47551. } else if ( light.isSpotLight ) {
  47552. const uniforms = cache.get( light );
  47553. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  47554. uniforms.color.copy( color ).multiplyScalar( intensity );
  47555. uniforms.distance = distance;
  47556. uniforms.coneCos = Math.cos( light.angle );
  47557. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  47558. uniforms.decay = light.decay;
  47559. state.spot[ spotLength ] = uniforms;
  47560. const shadow = light.shadow;
  47561. if ( light.map ) {
  47562. state.spotLightMap[ numSpotMaps ] = light.map;
  47563. numSpotMaps ++;
  47564. // make sure the lightMatrix is up to date
  47565. // TODO : do it if required only
  47566. shadow.updateMatrices( light );
  47567. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  47568. }
  47569. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  47570. if ( light.castShadow ) {
  47571. const shadowUniforms = shadowCache.get( light );
  47572. shadowUniforms.shadowIntensity = shadow.intensity;
  47573. shadowUniforms.shadowBias = shadow.bias;
  47574. shadowUniforms.shadowNormalBias = shadow.normalBias;
  47575. shadowUniforms.shadowRadius = shadow.radius;
  47576. shadowUniforms.shadowMapSize = shadow.mapSize;
  47577. state.spotShadow[ spotLength ] = shadowUniforms;
  47578. state.spotShadowMap[ spotLength ] = shadowMap;
  47579. numSpotShadows ++;
  47580. }
  47581. spotLength ++;
  47582. } else if ( light.isRectAreaLight ) {
  47583. const uniforms = cache.get( light );
  47584. uniforms.color.copy( color ).multiplyScalar( intensity );
  47585. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  47586. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  47587. state.rectArea[ rectAreaLength ] = uniforms;
  47588. rectAreaLength ++;
  47589. } else if ( light.isPointLight ) {
  47590. const uniforms = cache.get( light );
  47591. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  47592. uniforms.distance = light.distance;
  47593. uniforms.decay = light.decay;
  47594. if ( light.castShadow ) {
  47595. const shadow = light.shadow;
  47596. const shadowUniforms = shadowCache.get( light );
  47597. shadowUniforms.shadowIntensity = shadow.intensity;
  47598. shadowUniforms.shadowBias = shadow.bias;
  47599. shadowUniforms.shadowNormalBias = shadow.normalBias;
  47600. shadowUniforms.shadowRadius = shadow.radius;
  47601. shadowUniforms.shadowMapSize = shadow.mapSize;
  47602. shadowUniforms.shadowCameraNear = shadow.camera.near;
  47603. shadowUniforms.shadowCameraFar = shadow.camera.far;
  47604. state.pointShadow[ pointLength ] = shadowUniforms;
  47605. state.pointShadowMap[ pointLength ] = shadowMap;
  47606. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  47607. numPointShadows ++;
  47608. }
  47609. state.point[ pointLength ] = uniforms;
  47610. pointLength ++;
  47611. } else if ( light.isHemisphereLight ) {
  47612. const uniforms = cache.get( light );
  47613. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  47614. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  47615. state.hemi[ hemiLength ] = uniforms;
  47616. hemiLength ++;
  47617. }
  47618. }
  47619. if ( rectAreaLength > 0 ) {
  47620. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  47621. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  47622. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  47623. } else {
  47624. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  47625. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  47626. }
  47627. }
  47628. state.ambient[ 0 ] = r;
  47629. state.ambient[ 1 ] = g;
  47630. state.ambient[ 2 ] = b;
  47631. const hash = state.hash;
  47632. if ( hash.directionalLength !== directionalLength ||
  47633. hash.pointLength !== pointLength ||
  47634. hash.spotLength !== spotLength ||
  47635. hash.rectAreaLength !== rectAreaLength ||
  47636. hash.hemiLength !== hemiLength ||
  47637. hash.numDirectionalShadows !== numDirectionalShadows ||
  47638. hash.numPointShadows !== numPointShadows ||
  47639. hash.numSpotShadows !== numSpotShadows ||
  47640. hash.numSpotMaps !== numSpotMaps ||
  47641. hash.numLightProbes !== numLightProbes ) {
  47642. state.directional.length = directionalLength;
  47643. state.spot.length = spotLength;
  47644. state.rectArea.length = rectAreaLength;
  47645. state.point.length = pointLength;
  47646. state.hemi.length = hemiLength;
  47647. state.directionalShadow.length = numDirectionalShadows;
  47648. state.directionalShadowMap.length = numDirectionalShadows;
  47649. state.pointShadow.length = numPointShadows;
  47650. state.pointShadowMap.length = numPointShadows;
  47651. state.spotShadow.length = numSpotShadows;
  47652. state.spotShadowMap.length = numSpotShadows;
  47653. state.directionalShadowMatrix.length = numDirectionalShadows;
  47654. state.pointShadowMatrix.length = numPointShadows;
  47655. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  47656. state.spotLightMap.length = numSpotMaps;
  47657. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  47658. state.numLightProbes = numLightProbes;
  47659. hash.directionalLength = directionalLength;
  47660. hash.pointLength = pointLength;
  47661. hash.spotLength = spotLength;
  47662. hash.rectAreaLength = rectAreaLength;
  47663. hash.hemiLength = hemiLength;
  47664. hash.numDirectionalShadows = numDirectionalShadows;
  47665. hash.numPointShadows = numPointShadows;
  47666. hash.numSpotShadows = numSpotShadows;
  47667. hash.numSpotMaps = numSpotMaps;
  47668. hash.numLightProbes = numLightProbes;
  47669. state.version = nextVersion ++;
  47670. }
  47671. }
  47672. function setupView( lights, camera ) {
  47673. let directionalLength = 0;
  47674. let pointLength = 0;
  47675. let spotLength = 0;
  47676. let rectAreaLength = 0;
  47677. let hemiLength = 0;
  47678. const viewMatrix = camera.matrixWorldInverse;
  47679. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  47680. const light = lights[ i ];
  47681. if ( light.isDirectionalLight ) {
  47682. const uniforms = state.directional[ directionalLength ];
  47683. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  47684. vector3.setFromMatrixPosition( light.target.matrixWorld );
  47685. uniforms.direction.sub( vector3 );
  47686. uniforms.direction.transformDirection( viewMatrix );
  47687. directionalLength ++;
  47688. } else if ( light.isSpotLight ) {
  47689. const uniforms = state.spot[ spotLength ];
  47690. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  47691. uniforms.position.applyMatrix4( viewMatrix );
  47692. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  47693. vector3.setFromMatrixPosition( light.target.matrixWorld );
  47694. uniforms.direction.sub( vector3 );
  47695. uniforms.direction.transformDirection( viewMatrix );
  47696. spotLength ++;
  47697. } else if ( light.isRectAreaLight ) {
  47698. const uniforms = state.rectArea[ rectAreaLength ];
  47699. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  47700. uniforms.position.applyMatrix4( viewMatrix );
  47701. // extract local rotation of light to derive width/height half vectors
  47702. matrix42.identity();
  47703. matrix4.copy( light.matrixWorld );
  47704. matrix4.premultiply( viewMatrix );
  47705. matrix42.extractRotation( matrix4 );
  47706. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  47707. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  47708. uniforms.halfWidth.applyMatrix4( matrix42 );
  47709. uniforms.halfHeight.applyMatrix4( matrix42 );
  47710. rectAreaLength ++;
  47711. } else if ( light.isPointLight ) {
  47712. const uniforms = state.point[ pointLength ];
  47713. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  47714. uniforms.position.applyMatrix4( viewMatrix );
  47715. pointLength ++;
  47716. } else if ( light.isHemisphereLight ) {
  47717. const uniforms = state.hemi[ hemiLength ];
  47718. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  47719. uniforms.direction.transformDirection( viewMatrix );
  47720. hemiLength ++;
  47721. }
  47722. }
  47723. }
  47724. return {
  47725. setup: setup,
  47726. setupView: setupView,
  47727. state: state
  47728. };
  47729. }
  47730. function WebGLRenderState( extensions ) {
  47731. const lights = new WebGLLights( extensions );
  47732. const lightsArray = [];
  47733. const shadowsArray = [];
  47734. function init( camera ) {
  47735. state.camera = camera;
  47736. lightsArray.length = 0;
  47737. shadowsArray.length = 0;
  47738. }
  47739. function pushLight( light ) {
  47740. lightsArray.push( light );
  47741. }
  47742. function pushShadow( shadowLight ) {
  47743. shadowsArray.push( shadowLight );
  47744. }
  47745. function setupLights() {
  47746. lights.setup( lightsArray );
  47747. }
  47748. function setupLightsView( camera ) {
  47749. lights.setupView( lightsArray, camera );
  47750. }
  47751. const state = {
  47752. lightsArray: lightsArray,
  47753. shadowsArray: shadowsArray,
  47754. camera: null,
  47755. lights: lights,
  47756. transmissionRenderTarget: {}
  47757. };
  47758. return {
  47759. init: init,
  47760. state: state,
  47761. setupLights: setupLights,
  47762. setupLightsView: setupLightsView,
  47763. pushLight: pushLight,
  47764. pushShadow: pushShadow
  47765. };
  47766. }
  47767. function WebGLRenderStates( extensions ) {
  47768. let renderStates = new WeakMap();
  47769. function get( scene, renderCallDepth = 0 ) {
  47770. const renderStateArray = renderStates.get( scene );
  47771. let renderState;
  47772. if ( renderStateArray === undefined ) {
  47773. renderState = new WebGLRenderState( extensions );
  47774. renderStates.set( scene, [ renderState ] );
  47775. } else {
  47776. if ( renderCallDepth >= renderStateArray.length ) {
  47777. renderState = new WebGLRenderState( extensions );
  47778. renderStateArray.push( renderState );
  47779. } else {
  47780. renderState = renderStateArray[ renderCallDepth ];
  47781. }
  47782. }
  47783. return renderState;
  47784. }
  47785. function dispose() {
  47786. renderStates = new WeakMap();
  47787. }
  47788. return {
  47789. get: get,
  47790. dispose: dispose
  47791. };
  47792. }
  47793. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  47794. 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}";
  47795. function WebGLShadowMap( renderer, objects, capabilities ) {
  47796. let _frustum = new Frustum();
  47797. const _shadowMapSize = new Vector2(),
  47798. _viewportSize = new Vector2(),
  47799. _viewport = new Vector4(),
  47800. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  47801. _distanceMaterial = new MeshDistanceMaterial(),
  47802. _materialCache = {},
  47803. _maxTextureSize = capabilities.maxTextureSize;
  47804. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  47805. const shadowMaterialVertical = new ShaderMaterial( {
  47806. defines: {
  47807. VSM_SAMPLES: 8
  47808. },
  47809. uniforms: {
  47810. shadow_pass: { value: null },
  47811. resolution: { value: new Vector2() },
  47812. radius: { value: 4.0 }
  47813. },
  47814. vertexShader: vertex,
  47815. fragmentShader: fragment
  47816. } );
  47817. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  47818. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  47819. const fullScreenTri = new BufferGeometry();
  47820. fullScreenTri.setAttribute(
  47821. 'position',
  47822. new BufferAttribute(
  47823. new Float32Array( [ -1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5 ] ),
  47824. 3
  47825. )
  47826. );
  47827. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  47828. const scope = this;
  47829. this.enabled = false;
  47830. this.autoUpdate = true;
  47831. this.needsUpdate = false;
  47832. this.type = PCFShadowMap;
  47833. let _previousType = this.type;
  47834. this.render = function ( lights, scene, camera ) {
  47835. if ( scope.enabled === false ) return;
  47836. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  47837. if ( lights.length === 0 ) return;
  47838. const currentRenderTarget = renderer.getRenderTarget();
  47839. const activeCubeFace = renderer.getActiveCubeFace();
  47840. const activeMipmapLevel = renderer.getActiveMipmapLevel();
  47841. const _state = renderer.state;
  47842. // Set GL state for depth map.
  47843. _state.setBlending( NoBlending );
  47844. if ( _state.buffers.depth.getReversed() === true ) {
  47845. _state.buffers.color.setClear( 0, 0, 0, 0 );
  47846. } else {
  47847. _state.buffers.color.setClear( 1, 1, 1, 1 );
  47848. }
  47849. _state.buffers.depth.setTest( true );
  47850. _state.setScissorTest( false );
  47851. // check for shadow map type changes
  47852. const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap );
  47853. const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap );
  47854. // render depth map
  47855. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  47856. const light = lights[ i ];
  47857. const shadow = light.shadow;
  47858. if ( shadow === undefined ) {
  47859. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  47860. continue;
  47861. }
  47862. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  47863. _shadowMapSize.copy( shadow.mapSize );
  47864. const shadowFrameExtents = shadow.getFrameExtents();
  47865. _shadowMapSize.multiply( shadowFrameExtents );
  47866. _viewportSize.copy( shadow.mapSize );
  47867. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  47868. if ( _shadowMapSize.x > _maxTextureSize ) {
  47869. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  47870. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  47871. shadow.mapSize.x = _viewportSize.x;
  47872. }
  47873. if ( _shadowMapSize.y > _maxTextureSize ) {
  47874. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  47875. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  47876. shadow.mapSize.y = _viewportSize.y;
  47877. }
  47878. }
  47879. if ( shadow.map === null || toVSM === true || fromVSM === true ) {
  47880. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  47881. if ( shadow.map !== null ) {
  47882. shadow.map.dispose();
  47883. }
  47884. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  47885. shadow.map.texture.name = light.name + '.shadowMap';
  47886. shadow.camera.updateProjectionMatrix();
  47887. }
  47888. renderer.setRenderTarget( shadow.map );
  47889. renderer.clear();
  47890. const viewportCount = shadow.getViewportCount();
  47891. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  47892. const viewport = shadow.getViewport( vp );
  47893. _viewport.set(
  47894. _viewportSize.x * viewport.x,
  47895. _viewportSize.y * viewport.y,
  47896. _viewportSize.x * viewport.z,
  47897. _viewportSize.y * viewport.w
  47898. );
  47899. _state.viewport( _viewport );
  47900. shadow.updateMatrices( light, vp );
  47901. _frustum = shadow.getFrustum();
  47902. renderObject( scene, camera, shadow.camera, light, this.type );
  47903. }
  47904. // do blur pass for VSM
  47905. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  47906. VSMPass( shadow, camera );
  47907. }
  47908. shadow.needsUpdate = false;
  47909. }
  47910. _previousType = this.type;
  47911. scope.needsUpdate = false;
  47912. renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  47913. };
  47914. function VSMPass( shadow, camera ) {
  47915. const geometry = objects.update( fullScreenMesh );
  47916. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  47917. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  47918. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  47919. shadowMaterialVertical.needsUpdate = true;
  47920. shadowMaterialHorizontal.needsUpdate = true;
  47921. }
  47922. if ( shadow.mapPass === null ) {
  47923. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  47924. }
  47925. // vertical pass
  47926. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  47927. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  47928. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  47929. renderer.setRenderTarget( shadow.mapPass );
  47930. renderer.clear();
  47931. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  47932. // horizontal pass
  47933. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  47934. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  47935. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  47936. renderer.setRenderTarget( shadow.map );
  47937. renderer.clear();
  47938. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  47939. }
  47940. function getDepthMaterial( object, material, light, type ) {
  47941. let result = null;
  47942. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  47943. if ( customMaterial !== undefined ) {
  47944. result = customMaterial;
  47945. } else {
  47946. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  47947. if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  47948. ( material.displacementMap && material.displacementScale !== 0 ) ||
  47949. ( material.alphaMap && material.alphaTest > 0 ) ||
  47950. ( material.map && material.alphaTest > 0 ) ||
  47951. ( material.alphaToCoverage === true ) ) {
  47952. // in this case we need a unique material instance reflecting the
  47953. // appropriate state
  47954. const keyA = result.uuid, keyB = material.uuid;
  47955. let materialsForVariant = _materialCache[ keyA ];
  47956. if ( materialsForVariant === undefined ) {
  47957. materialsForVariant = {};
  47958. _materialCache[ keyA ] = materialsForVariant;
  47959. }
  47960. let cachedMaterial = materialsForVariant[ keyB ];
  47961. if ( cachedMaterial === undefined ) {
  47962. cachedMaterial = result.clone();
  47963. materialsForVariant[ keyB ] = cachedMaterial;
  47964. material.addEventListener( 'dispose', onMaterialDispose );
  47965. }
  47966. result = cachedMaterial;
  47967. }
  47968. }
  47969. result.visible = material.visible;
  47970. result.wireframe = material.wireframe;
  47971. if ( type === VSMShadowMap ) {
  47972. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  47973. } else {
  47974. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  47975. }
  47976. result.alphaMap = material.alphaMap;
  47977. result.alphaTest = ( material.alphaToCoverage === true ) ? 0.5 : material.alphaTest; // approximate alphaToCoverage by using a fixed alphaTest value
  47978. result.map = material.map;
  47979. result.clipShadows = material.clipShadows;
  47980. result.clippingPlanes = material.clippingPlanes;
  47981. result.clipIntersection = material.clipIntersection;
  47982. result.displacementMap = material.displacementMap;
  47983. result.displacementScale = material.displacementScale;
  47984. result.displacementBias = material.displacementBias;
  47985. result.wireframeLinewidth = material.wireframeLinewidth;
  47986. result.linewidth = material.linewidth;
  47987. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  47988. const materialProperties = renderer.properties.get( result );
  47989. materialProperties.light = light;
  47990. }
  47991. return result;
  47992. }
  47993. function renderObject( object, camera, shadowCamera, light, type ) {
  47994. if ( object.visible === false ) return;
  47995. const visible = object.layers.test( camera.layers );
  47996. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  47997. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  47998. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  47999. const geometry = objects.update( object );
  48000. const material = object.material;
  48001. if ( Array.isArray( material ) ) {
  48002. const groups = geometry.groups;
  48003. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  48004. const group = groups[ k ];
  48005. const groupMaterial = material[ group.materialIndex ];
  48006. if ( groupMaterial && groupMaterial.visible ) {
  48007. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  48008. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  48009. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  48010. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  48011. }
  48012. }
  48013. } else if ( material.visible ) {
  48014. const depthMaterial = getDepthMaterial( object, material, light, type );
  48015. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  48016. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  48017. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  48018. }
  48019. }
  48020. }
  48021. const children = object.children;
  48022. for ( let i = 0, l = children.length; i < l; i ++ ) {
  48023. renderObject( children[ i ], camera, shadowCamera, light, type );
  48024. }
  48025. }
  48026. function onMaterialDispose( event ) {
  48027. const material = event.target;
  48028. material.removeEventListener( 'dispose', onMaterialDispose );
  48029. // make sure to remove the unique distance/depth materials used for shadow map rendering
  48030. for ( const id in _materialCache ) {
  48031. const cache = _materialCache[ id ];
  48032. const uuid = event.target.uuid;
  48033. if ( uuid in cache ) {
  48034. const shadowMaterial = cache[ uuid ];
  48035. shadowMaterial.dispose();
  48036. delete cache[ uuid ];
  48037. }
  48038. }
  48039. }
  48040. }
  48041. const reversedFuncs = {
  48042. [ NeverDepth ]: AlwaysDepth,
  48043. [ LessDepth ]: GreaterDepth,
  48044. [ EqualDepth ]: NotEqualDepth,
  48045. [ LessEqualDepth ]: GreaterEqualDepth,
  48046. [ AlwaysDepth ]: NeverDepth,
  48047. [ GreaterDepth ]: LessDepth,
  48048. [ NotEqualDepth ]: EqualDepth,
  48049. [ GreaterEqualDepth ]: LessEqualDepth,
  48050. };
  48051. function WebGLState( gl, extensions ) {
  48052. function ColorBuffer() {
  48053. let locked = false;
  48054. const color = new Vector4();
  48055. let currentColorMask = null;
  48056. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  48057. return {
  48058. setMask: function ( colorMask ) {
  48059. if ( currentColorMask !== colorMask && ! locked ) {
  48060. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  48061. currentColorMask = colorMask;
  48062. }
  48063. },
  48064. setLocked: function ( lock ) {
  48065. locked = lock;
  48066. },
  48067. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  48068. if ( premultipliedAlpha === true ) {
  48069. r *= a; g *= a; b *= a;
  48070. }
  48071. color.set( r, g, b, a );
  48072. if ( currentColorClear.equals( color ) === false ) {
  48073. gl.clearColor( r, g, b, a );
  48074. currentColorClear.copy( color );
  48075. }
  48076. },
  48077. reset: function () {
  48078. locked = false;
  48079. currentColorMask = null;
  48080. currentColorClear.set( -1, 0, 0, 0 ); // set to invalid state
  48081. }
  48082. };
  48083. }
  48084. function DepthBuffer() {
  48085. let locked = false;
  48086. let currentReversed = false;
  48087. let currentDepthMask = null;
  48088. let currentDepthFunc = null;
  48089. let currentDepthClear = null;
  48090. return {
  48091. setReversed: function ( reversed ) {
  48092. if ( currentReversed !== reversed ) {
  48093. const ext = extensions.get( 'EXT_clip_control' );
  48094. if ( reversed ) {
  48095. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT );
  48096. } else {
  48097. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT );
  48098. }
  48099. currentReversed = reversed;
  48100. const oldDepth = currentDepthClear;
  48101. currentDepthClear = null;
  48102. this.setClear( oldDepth );
  48103. }
  48104. },
  48105. getReversed: function () {
  48106. return currentReversed;
  48107. },
  48108. setTest: function ( depthTest ) {
  48109. if ( depthTest ) {
  48110. enable( gl.DEPTH_TEST );
  48111. } else {
  48112. disable( gl.DEPTH_TEST );
  48113. }
  48114. },
  48115. setMask: function ( depthMask ) {
  48116. if ( currentDepthMask !== depthMask && ! locked ) {
  48117. gl.depthMask( depthMask );
  48118. currentDepthMask = depthMask;
  48119. }
  48120. },
  48121. setFunc: function ( depthFunc ) {
  48122. if ( currentReversed ) depthFunc = reversedFuncs[ depthFunc ];
  48123. if ( currentDepthFunc !== depthFunc ) {
  48124. switch ( depthFunc ) {
  48125. case NeverDepth:
  48126. gl.depthFunc( gl.NEVER );
  48127. break;
  48128. case AlwaysDepth:
  48129. gl.depthFunc( gl.ALWAYS );
  48130. break;
  48131. case LessDepth:
  48132. gl.depthFunc( gl.LESS );
  48133. break;
  48134. case LessEqualDepth:
  48135. gl.depthFunc( gl.LEQUAL );
  48136. break;
  48137. case EqualDepth:
  48138. gl.depthFunc( gl.EQUAL );
  48139. break;
  48140. case GreaterEqualDepth:
  48141. gl.depthFunc( gl.GEQUAL );
  48142. break;
  48143. case GreaterDepth:
  48144. gl.depthFunc( gl.GREATER );
  48145. break;
  48146. case NotEqualDepth:
  48147. gl.depthFunc( gl.NOTEQUAL );
  48148. break;
  48149. default:
  48150. gl.depthFunc( gl.LEQUAL );
  48151. }
  48152. currentDepthFunc = depthFunc;
  48153. }
  48154. },
  48155. setLocked: function ( lock ) {
  48156. locked = lock;
  48157. },
  48158. setClear: function ( depth ) {
  48159. if ( currentDepthClear !== depth ) {
  48160. if ( currentReversed ) {
  48161. depth = 1 - depth;
  48162. }
  48163. gl.clearDepth( depth );
  48164. currentDepthClear = depth;
  48165. }
  48166. },
  48167. reset: function () {
  48168. locked = false;
  48169. currentDepthMask = null;
  48170. currentDepthFunc = null;
  48171. currentDepthClear = null;
  48172. currentReversed = false;
  48173. }
  48174. };
  48175. }
  48176. function StencilBuffer() {
  48177. let locked = false;
  48178. let currentStencilMask = null;
  48179. let currentStencilFunc = null;
  48180. let currentStencilRef = null;
  48181. let currentStencilFuncMask = null;
  48182. let currentStencilFail = null;
  48183. let currentStencilZFail = null;
  48184. let currentStencilZPass = null;
  48185. let currentStencilClear = null;
  48186. return {
  48187. setTest: function ( stencilTest ) {
  48188. if ( ! locked ) {
  48189. if ( stencilTest ) {
  48190. enable( gl.STENCIL_TEST );
  48191. } else {
  48192. disable( gl.STENCIL_TEST );
  48193. }
  48194. }
  48195. },
  48196. setMask: function ( stencilMask ) {
  48197. if ( currentStencilMask !== stencilMask && ! locked ) {
  48198. gl.stencilMask( stencilMask );
  48199. currentStencilMask = stencilMask;
  48200. }
  48201. },
  48202. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  48203. if ( currentStencilFunc !== stencilFunc ||
  48204. currentStencilRef !== stencilRef ||
  48205. currentStencilFuncMask !== stencilMask ) {
  48206. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  48207. currentStencilFunc = stencilFunc;
  48208. currentStencilRef = stencilRef;
  48209. currentStencilFuncMask = stencilMask;
  48210. }
  48211. },
  48212. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  48213. if ( currentStencilFail !== stencilFail ||
  48214. currentStencilZFail !== stencilZFail ||
  48215. currentStencilZPass !== stencilZPass ) {
  48216. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  48217. currentStencilFail = stencilFail;
  48218. currentStencilZFail = stencilZFail;
  48219. currentStencilZPass = stencilZPass;
  48220. }
  48221. },
  48222. setLocked: function ( lock ) {
  48223. locked = lock;
  48224. },
  48225. setClear: function ( stencil ) {
  48226. if ( currentStencilClear !== stencil ) {
  48227. gl.clearStencil( stencil );
  48228. currentStencilClear = stencil;
  48229. }
  48230. },
  48231. reset: function () {
  48232. locked = false;
  48233. currentStencilMask = null;
  48234. currentStencilFunc = null;
  48235. currentStencilRef = null;
  48236. currentStencilFuncMask = null;
  48237. currentStencilFail = null;
  48238. currentStencilZFail = null;
  48239. currentStencilZPass = null;
  48240. currentStencilClear = null;
  48241. }
  48242. };
  48243. }
  48244. //
  48245. const colorBuffer = new ColorBuffer();
  48246. const depthBuffer = new DepthBuffer();
  48247. const stencilBuffer = new StencilBuffer();
  48248. const uboBindings = new WeakMap();
  48249. const uboProgramMap = new WeakMap();
  48250. let enabledCapabilities = {};
  48251. let currentBoundFramebuffers = {};
  48252. let currentDrawbuffers = new WeakMap();
  48253. let defaultDrawbuffers = [];
  48254. let currentProgram = null;
  48255. let currentBlendingEnabled = false;
  48256. let currentBlending = null;
  48257. let currentBlendEquation = null;
  48258. let currentBlendSrc = null;
  48259. let currentBlendDst = null;
  48260. let currentBlendEquationAlpha = null;
  48261. let currentBlendSrcAlpha = null;
  48262. let currentBlendDstAlpha = null;
  48263. let currentBlendColor = new Color( 0, 0, 0 );
  48264. let currentBlendAlpha = 0;
  48265. let currentPremultipledAlpha = false;
  48266. let currentFlipSided = null;
  48267. let currentCullFace = null;
  48268. let currentLineWidth = null;
  48269. let currentPolygonOffsetFactor = null;
  48270. let currentPolygonOffsetUnits = null;
  48271. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  48272. let lineWidthAvailable = false;
  48273. let version = 0;
  48274. const glVersion = gl.getParameter( gl.VERSION );
  48275. if ( glVersion.indexOf( 'WebGL' ) !== -1 ) {
  48276. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  48277. lineWidthAvailable = ( version >= 1.0 );
  48278. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== -1 ) {
  48279. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  48280. lineWidthAvailable = ( version >= 2.0 );
  48281. }
  48282. let currentTextureSlot = null;
  48283. let currentBoundTextures = {};
  48284. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  48285. const viewportParam = gl.getParameter( gl.VIEWPORT );
  48286. const currentScissor = new Vector4().fromArray( scissorParam );
  48287. const currentViewport = new Vector4().fromArray( viewportParam );
  48288. function createTexture( type, target, count, dimensions ) {
  48289. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  48290. const texture = gl.createTexture();
  48291. gl.bindTexture( type, texture );
  48292. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  48293. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  48294. for ( let i = 0; i < count; i ++ ) {
  48295. if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) {
  48296. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  48297. } else {
  48298. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  48299. }
  48300. }
  48301. return texture;
  48302. }
  48303. const emptyTextures = {};
  48304. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  48305. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  48306. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  48307. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  48308. // init
  48309. colorBuffer.setClear( 0, 0, 0, 1 );
  48310. depthBuffer.setClear( 1 );
  48311. stencilBuffer.setClear( 0 );
  48312. enable( gl.DEPTH_TEST );
  48313. depthBuffer.setFunc( LessEqualDepth );
  48314. setFlipSided( false );
  48315. setCullFace( CullFaceBack );
  48316. enable( gl.CULL_FACE );
  48317. setBlending( NoBlending );
  48318. //
  48319. function enable( id ) {
  48320. if ( enabledCapabilities[ id ] !== true ) {
  48321. gl.enable( id );
  48322. enabledCapabilities[ id ] = true;
  48323. }
  48324. }
  48325. function disable( id ) {
  48326. if ( enabledCapabilities[ id ] !== false ) {
  48327. gl.disable( id );
  48328. enabledCapabilities[ id ] = false;
  48329. }
  48330. }
  48331. function bindFramebuffer( target, framebuffer ) {
  48332. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  48333. gl.bindFramebuffer( target, framebuffer );
  48334. currentBoundFramebuffers[ target ] = framebuffer;
  48335. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  48336. if ( target === gl.DRAW_FRAMEBUFFER ) {
  48337. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  48338. }
  48339. if ( target === gl.FRAMEBUFFER ) {
  48340. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  48341. }
  48342. return true;
  48343. }
  48344. return false;
  48345. }
  48346. function drawBuffers( renderTarget, framebuffer ) {
  48347. let drawBuffers = defaultDrawbuffers;
  48348. let needsUpdate = false;
  48349. if ( renderTarget ) {
  48350. drawBuffers = currentDrawbuffers.get( framebuffer );
  48351. if ( drawBuffers === undefined ) {
  48352. drawBuffers = [];
  48353. currentDrawbuffers.set( framebuffer, drawBuffers );
  48354. }
  48355. const textures = renderTarget.textures;
  48356. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  48357. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  48358. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  48359. }
  48360. drawBuffers.length = textures.length;
  48361. needsUpdate = true;
  48362. }
  48363. } else {
  48364. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  48365. drawBuffers[ 0 ] = gl.BACK;
  48366. needsUpdate = true;
  48367. }
  48368. }
  48369. if ( needsUpdate ) {
  48370. gl.drawBuffers( drawBuffers );
  48371. }
  48372. }
  48373. function useProgram( program ) {
  48374. if ( currentProgram !== program ) {
  48375. gl.useProgram( program );
  48376. currentProgram = program;
  48377. return true;
  48378. }
  48379. return false;
  48380. }
  48381. const equationToGL = {
  48382. [ AddEquation ]: gl.FUNC_ADD,
  48383. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  48384. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  48385. };
  48386. equationToGL[ MinEquation ] = gl.MIN;
  48387. equationToGL[ MaxEquation ] = gl.MAX;
  48388. const factorToGL = {
  48389. [ ZeroFactor ]: gl.ZERO,
  48390. [ OneFactor ]: gl.ONE,
  48391. [ SrcColorFactor ]: gl.SRC_COLOR,
  48392. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  48393. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  48394. [ DstColorFactor ]: gl.DST_COLOR,
  48395. [ DstAlphaFactor ]: gl.DST_ALPHA,
  48396. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  48397. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  48398. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  48399. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  48400. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  48401. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  48402. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  48403. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  48404. };
  48405. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  48406. if ( blending === NoBlending ) {
  48407. if ( currentBlendingEnabled === true ) {
  48408. disable( gl.BLEND );
  48409. currentBlendingEnabled = false;
  48410. }
  48411. return;
  48412. }
  48413. if ( currentBlendingEnabled === false ) {
  48414. enable( gl.BLEND );
  48415. currentBlendingEnabled = true;
  48416. }
  48417. if ( blending !== CustomBlending ) {
  48418. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  48419. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  48420. gl.blendEquation( gl.FUNC_ADD );
  48421. currentBlendEquation = AddEquation;
  48422. currentBlendEquationAlpha = AddEquation;
  48423. }
  48424. if ( premultipliedAlpha ) {
  48425. switch ( blending ) {
  48426. case NormalBlending:
  48427. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  48428. break;
  48429. case AdditiveBlending:
  48430. gl.blendFunc( gl.ONE, gl.ONE );
  48431. break;
  48432. case SubtractiveBlending:
  48433. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  48434. break;
  48435. case MultiplyBlending:
  48436. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  48437. break;
  48438. default:
  48439. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  48440. break;
  48441. }
  48442. } else {
  48443. switch ( blending ) {
  48444. case NormalBlending:
  48445. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  48446. break;
  48447. case AdditiveBlending:
  48448. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  48449. break;
  48450. case SubtractiveBlending:
  48451. console.error( 'THREE.WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  48452. break;
  48453. case MultiplyBlending:
  48454. console.error( 'THREE.WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  48455. break;
  48456. default:
  48457. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  48458. break;
  48459. }
  48460. }
  48461. currentBlendSrc = null;
  48462. currentBlendDst = null;
  48463. currentBlendSrcAlpha = null;
  48464. currentBlendDstAlpha = null;
  48465. currentBlendColor.set( 0, 0, 0 );
  48466. currentBlendAlpha = 0;
  48467. currentBlending = blending;
  48468. currentPremultipledAlpha = premultipliedAlpha;
  48469. }
  48470. return;
  48471. }
  48472. // custom blending
  48473. blendEquationAlpha = blendEquationAlpha || blendEquation;
  48474. blendSrcAlpha = blendSrcAlpha || blendSrc;
  48475. blendDstAlpha = blendDstAlpha || blendDst;
  48476. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  48477. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  48478. currentBlendEquation = blendEquation;
  48479. currentBlendEquationAlpha = blendEquationAlpha;
  48480. }
  48481. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  48482. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  48483. currentBlendSrc = blendSrc;
  48484. currentBlendDst = blendDst;
  48485. currentBlendSrcAlpha = blendSrcAlpha;
  48486. currentBlendDstAlpha = blendDstAlpha;
  48487. }
  48488. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  48489. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  48490. currentBlendColor.copy( blendColor );
  48491. currentBlendAlpha = blendAlpha;
  48492. }
  48493. currentBlending = blending;
  48494. currentPremultipledAlpha = false;
  48495. }
  48496. function setMaterial( material, frontFaceCW ) {
  48497. material.side === DoubleSide
  48498. ? disable( gl.CULL_FACE )
  48499. : enable( gl.CULL_FACE );
  48500. let flipSided = ( material.side === BackSide );
  48501. if ( frontFaceCW ) flipSided = ! flipSided;
  48502. setFlipSided( flipSided );
  48503. ( material.blending === NormalBlending && material.transparent === false )
  48504. ? setBlending( NoBlending )
  48505. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  48506. depthBuffer.setFunc( material.depthFunc );
  48507. depthBuffer.setTest( material.depthTest );
  48508. depthBuffer.setMask( material.depthWrite );
  48509. colorBuffer.setMask( material.colorWrite );
  48510. const stencilWrite = material.stencilWrite;
  48511. stencilBuffer.setTest( stencilWrite );
  48512. if ( stencilWrite ) {
  48513. stencilBuffer.setMask( material.stencilWriteMask );
  48514. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  48515. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  48516. }
  48517. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  48518. material.alphaToCoverage === true
  48519. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  48520. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  48521. }
  48522. //
  48523. function setFlipSided( flipSided ) {
  48524. if ( currentFlipSided !== flipSided ) {
  48525. if ( flipSided ) {
  48526. gl.frontFace( gl.CW );
  48527. } else {
  48528. gl.frontFace( gl.CCW );
  48529. }
  48530. currentFlipSided = flipSided;
  48531. }
  48532. }
  48533. function setCullFace( cullFace ) {
  48534. if ( cullFace !== CullFaceNone ) {
  48535. enable( gl.CULL_FACE );
  48536. if ( cullFace !== currentCullFace ) {
  48537. if ( cullFace === CullFaceBack ) {
  48538. gl.cullFace( gl.BACK );
  48539. } else if ( cullFace === CullFaceFront ) {
  48540. gl.cullFace( gl.FRONT );
  48541. } else {
  48542. gl.cullFace( gl.FRONT_AND_BACK );
  48543. }
  48544. }
  48545. } else {
  48546. disable( gl.CULL_FACE );
  48547. }
  48548. currentCullFace = cullFace;
  48549. }
  48550. function setLineWidth( width ) {
  48551. if ( width !== currentLineWidth ) {
  48552. if ( lineWidthAvailable ) gl.lineWidth( width );
  48553. currentLineWidth = width;
  48554. }
  48555. }
  48556. function setPolygonOffset( polygonOffset, factor, units ) {
  48557. if ( polygonOffset ) {
  48558. enable( gl.POLYGON_OFFSET_FILL );
  48559. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  48560. gl.polygonOffset( factor, units );
  48561. currentPolygonOffsetFactor = factor;
  48562. currentPolygonOffsetUnits = units;
  48563. }
  48564. } else {
  48565. disable( gl.POLYGON_OFFSET_FILL );
  48566. }
  48567. }
  48568. function setScissorTest( scissorTest ) {
  48569. if ( scissorTest ) {
  48570. enable( gl.SCISSOR_TEST );
  48571. } else {
  48572. disable( gl.SCISSOR_TEST );
  48573. }
  48574. }
  48575. // texture
  48576. function activeTexture( webglSlot ) {
  48577. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  48578. if ( currentTextureSlot !== webglSlot ) {
  48579. gl.activeTexture( webglSlot );
  48580. currentTextureSlot = webglSlot;
  48581. }
  48582. }
  48583. function bindTexture( webglType, webglTexture, webglSlot ) {
  48584. if ( webglSlot === undefined ) {
  48585. if ( currentTextureSlot === null ) {
  48586. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  48587. } else {
  48588. webglSlot = currentTextureSlot;
  48589. }
  48590. }
  48591. let boundTexture = currentBoundTextures[ webglSlot ];
  48592. if ( boundTexture === undefined ) {
  48593. boundTexture = { type: undefined, texture: undefined };
  48594. currentBoundTextures[ webglSlot ] = boundTexture;
  48595. }
  48596. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  48597. if ( currentTextureSlot !== webglSlot ) {
  48598. gl.activeTexture( webglSlot );
  48599. currentTextureSlot = webglSlot;
  48600. }
  48601. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  48602. boundTexture.type = webglType;
  48603. boundTexture.texture = webglTexture;
  48604. }
  48605. }
  48606. function unbindTexture() {
  48607. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  48608. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  48609. gl.bindTexture( boundTexture.type, null );
  48610. boundTexture.type = undefined;
  48611. boundTexture.texture = undefined;
  48612. }
  48613. }
  48614. function compressedTexImage2D() {
  48615. try {
  48616. gl.compressedTexImage2D( ...arguments );
  48617. } catch ( error ) {
  48618. console.error( 'THREE.WebGLState:', error );
  48619. }
  48620. }
  48621. function compressedTexImage3D() {
  48622. try {
  48623. gl.compressedTexImage3D( ...arguments );
  48624. } catch ( error ) {
  48625. console.error( 'THREE.WebGLState:', error );
  48626. }
  48627. }
  48628. function texSubImage2D() {
  48629. try {
  48630. gl.texSubImage2D( ...arguments );
  48631. } catch ( error ) {
  48632. console.error( 'THREE.WebGLState:', error );
  48633. }
  48634. }
  48635. function texSubImage3D() {
  48636. try {
  48637. gl.texSubImage3D( ...arguments );
  48638. } catch ( error ) {
  48639. console.error( 'THREE.WebGLState:', error );
  48640. }
  48641. }
  48642. function compressedTexSubImage2D() {
  48643. try {
  48644. gl.compressedTexSubImage2D( ...arguments );
  48645. } catch ( error ) {
  48646. console.error( 'THREE.WebGLState:', error );
  48647. }
  48648. }
  48649. function compressedTexSubImage3D() {
  48650. try {
  48651. gl.compressedTexSubImage3D( ...arguments );
  48652. } catch ( error ) {
  48653. console.error( 'THREE.WebGLState:', error );
  48654. }
  48655. }
  48656. function texStorage2D() {
  48657. try {
  48658. gl.texStorage2D( ...arguments );
  48659. } catch ( error ) {
  48660. console.error( 'THREE.WebGLState:', error );
  48661. }
  48662. }
  48663. function texStorage3D() {
  48664. try {
  48665. gl.texStorage3D( ...arguments );
  48666. } catch ( error ) {
  48667. console.error( 'THREE.WebGLState:', error );
  48668. }
  48669. }
  48670. function texImage2D() {
  48671. try {
  48672. gl.texImage2D( ...arguments );
  48673. } catch ( error ) {
  48674. console.error( 'THREE.WebGLState:', error );
  48675. }
  48676. }
  48677. function texImage3D() {
  48678. try {
  48679. gl.texImage3D( ...arguments );
  48680. } catch ( error ) {
  48681. console.error( 'THREE.WebGLState:', error );
  48682. }
  48683. }
  48684. //
  48685. function scissor( scissor ) {
  48686. if ( currentScissor.equals( scissor ) === false ) {
  48687. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  48688. currentScissor.copy( scissor );
  48689. }
  48690. }
  48691. function viewport( viewport ) {
  48692. if ( currentViewport.equals( viewport ) === false ) {
  48693. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  48694. currentViewport.copy( viewport );
  48695. }
  48696. }
  48697. function updateUBOMapping( uniformsGroup, program ) {
  48698. let mapping = uboProgramMap.get( program );
  48699. if ( mapping === undefined ) {
  48700. mapping = new WeakMap();
  48701. uboProgramMap.set( program, mapping );
  48702. }
  48703. let blockIndex = mapping.get( uniformsGroup );
  48704. if ( blockIndex === undefined ) {
  48705. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  48706. mapping.set( uniformsGroup, blockIndex );
  48707. }
  48708. }
  48709. function uniformBlockBinding( uniformsGroup, program ) {
  48710. const mapping = uboProgramMap.get( program );
  48711. const blockIndex = mapping.get( uniformsGroup );
  48712. if ( uboBindings.get( program ) !== blockIndex ) {
  48713. // bind shader specific block index to global block point
  48714. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  48715. uboBindings.set( program, blockIndex );
  48716. }
  48717. }
  48718. //
  48719. function reset() {
  48720. // reset state
  48721. gl.disable( gl.BLEND );
  48722. gl.disable( gl.CULL_FACE );
  48723. gl.disable( gl.DEPTH_TEST );
  48724. gl.disable( gl.POLYGON_OFFSET_FILL );
  48725. gl.disable( gl.SCISSOR_TEST );
  48726. gl.disable( gl.STENCIL_TEST );
  48727. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  48728. gl.blendEquation( gl.FUNC_ADD );
  48729. gl.blendFunc( gl.ONE, gl.ZERO );
  48730. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  48731. gl.blendColor( 0, 0, 0, 0 );
  48732. gl.colorMask( true, true, true, true );
  48733. gl.clearColor( 0, 0, 0, 0 );
  48734. gl.depthMask( true );
  48735. gl.depthFunc( gl.LESS );
  48736. depthBuffer.setReversed( false );
  48737. gl.clearDepth( 1 );
  48738. gl.stencilMask( 0xffffffff );
  48739. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  48740. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  48741. gl.clearStencil( 0 );
  48742. gl.cullFace( gl.BACK );
  48743. gl.frontFace( gl.CCW );
  48744. gl.polygonOffset( 0, 0 );
  48745. gl.activeTexture( gl.TEXTURE0 );
  48746. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  48747. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  48748. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  48749. gl.useProgram( null );
  48750. gl.lineWidth( 1 );
  48751. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  48752. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  48753. // reset internals
  48754. enabledCapabilities = {};
  48755. currentTextureSlot = null;
  48756. currentBoundTextures = {};
  48757. currentBoundFramebuffers = {};
  48758. currentDrawbuffers = new WeakMap();
  48759. defaultDrawbuffers = [];
  48760. currentProgram = null;
  48761. currentBlendingEnabled = false;
  48762. currentBlending = null;
  48763. currentBlendEquation = null;
  48764. currentBlendSrc = null;
  48765. currentBlendDst = null;
  48766. currentBlendEquationAlpha = null;
  48767. currentBlendSrcAlpha = null;
  48768. currentBlendDstAlpha = null;
  48769. currentBlendColor = new Color( 0, 0, 0 );
  48770. currentBlendAlpha = 0;
  48771. currentPremultipledAlpha = false;
  48772. currentFlipSided = null;
  48773. currentCullFace = null;
  48774. currentLineWidth = null;
  48775. currentPolygonOffsetFactor = null;
  48776. currentPolygonOffsetUnits = null;
  48777. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  48778. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  48779. colorBuffer.reset();
  48780. depthBuffer.reset();
  48781. stencilBuffer.reset();
  48782. }
  48783. return {
  48784. buffers: {
  48785. color: colorBuffer,
  48786. depth: depthBuffer,
  48787. stencil: stencilBuffer
  48788. },
  48789. enable: enable,
  48790. disable: disable,
  48791. bindFramebuffer: bindFramebuffer,
  48792. drawBuffers: drawBuffers,
  48793. useProgram: useProgram,
  48794. setBlending: setBlending,
  48795. setMaterial: setMaterial,
  48796. setFlipSided: setFlipSided,
  48797. setCullFace: setCullFace,
  48798. setLineWidth: setLineWidth,
  48799. setPolygonOffset: setPolygonOffset,
  48800. setScissorTest: setScissorTest,
  48801. activeTexture: activeTexture,
  48802. bindTexture: bindTexture,
  48803. unbindTexture: unbindTexture,
  48804. compressedTexImage2D: compressedTexImage2D,
  48805. compressedTexImage3D: compressedTexImage3D,
  48806. texImage2D: texImage2D,
  48807. texImage3D: texImage3D,
  48808. updateUBOMapping: updateUBOMapping,
  48809. uniformBlockBinding: uniformBlockBinding,
  48810. texStorage2D: texStorage2D,
  48811. texStorage3D: texStorage3D,
  48812. texSubImage2D: texSubImage2D,
  48813. texSubImage3D: texSubImage3D,
  48814. compressedTexSubImage2D: compressedTexSubImage2D,
  48815. compressedTexSubImage3D: compressedTexSubImage3D,
  48816. scissor: scissor,
  48817. viewport: viewport,
  48818. reset: reset
  48819. };
  48820. }
  48821. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  48822. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  48823. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  48824. const _imageDimensions = new Vector2();
  48825. const _videoTextures = new WeakMap();
  48826. let _canvas;
  48827. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  48828. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  48829. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  48830. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  48831. let useOffscreenCanvas = false;
  48832. try {
  48833. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  48834. // eslint-disable-next-line compat/compat
  48835. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  48836. } catch ( err ) {
  48837. // Ignore any errors
  48838. }
  48839. function createCanvas( width, height ) {
  48840. // Use OffscreenCanvas when available. Specially needed in web workers
  48841. return useOffscreenCanvas ?
  48842. // eslint-disable-next-line compat/compat
  48843. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  48844. }
  48845. function resizeImage( image, needsNewCanvas, maxSize ) {
  48846. let scale = 1;
  48847. const dimensions = getDimensions( image );
  48848. // handle case if texture exceeds max size
  48849. if ( dimensions.width > maxSize || dimensions.height > maxSize ) {
  48850. scale = maxSize / Math.max( dimensions.width, dimensions.height );
  48851. }
  48852. // only perform resize if necessary
  48853. if ( scale < 1 ) {
  48854. // only perform resize for certain image types
  48855. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  48856. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  48857. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  48858. ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) {
  48859. const width = Math.floor( scale * dimensions.width );
  48860. const height = Math.floor( scale * dimensions.height );
  48861. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  48862. // cube textures can't reuse the same canvas
  48863. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  48864. canvas.width = width;
  48865. canvas.height = height;
  48866. const context = canvas.getContext( '2d' );
  48867. context.drawImage( image, 0, 0, width, height );
  48868. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' );
  48869. return canvas;
  48870. } else {
  48871. if ( 'data' in image ) {
  48872. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' );
  48873. }
  48874. return image;
  48875. }
  48876. }
  48877. return image;
  48878. }
  48879. function textureNeedsGenerateMipmaps( texture ) {
  48880. return texture.generateMipmaps;
  48881. }
  48882. function generateMipmap( target ) {
  48883. _gl.generateMipmap( target );
  48884. }
  48885. function getTargetType( texture ) {
  48886. if ( texture.isWebGLCubeRenderTarget ) return _gl.TEXTURE_CUBE_MAP;
  48887. if ( texture.isWebGL3DRenderTarget ) return _gl.TEXTURE_3D;
  48888. if ( texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture ) return _gl.TEXTURE_2D_ARRAY;
  48889. return _gl.TEXTURE_2D;
  48890. }
  48891. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  48892. if ( internalFormatName !== null ) {
  48893. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  48894. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  48895. }
  48896. let internalFormat = glFormat;
  48897. if ( glFormat === _gl.RED ) {
  48898. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  48899. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  48900. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  48901. }
  48902. if ( glFormat === _gl.RED_INTEGER ) {
  48903. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  48904. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  48905. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  48906. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  48907. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  48908. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  48909. }
  48910. if ( glFormat === _gl.RG ) {
  48911. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  48912. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  48913. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  48914. }
  48915. if ( glFormat === _gl.RG_INTEGER ) {
  48916. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI;
  48917. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI;
  48918. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI;
  48919. if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I;
  48920. if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I;
  48921. if ( glType === _gl.INT ) internalFormat = _gl.RG32I;
  48922. }
  48923. if ( glFormat === _gl.RGB_INTEGER ) {
  48924. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGB8UI;
  48925. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGB16UI;
  48926. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGB32UI;
  48927. if ( glType === _gl.BYTE ) internalFormat = _gl.RGB8I;
  48928. if ( glType === _gl.SHORT ) internalFormat = _gl.RGB16I;
  48929. if ( glType === _gl.INT ) internalFormat = _gl.RGB32I;
  48930. }
  48931. if ( glFormat === _gl.RGBA_INTEGER ) {
  48932. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGBA8UI;
  48933. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGBA16UI;
  48934. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGBA32UI;
  48935. if ( glType === _gl.BYTE ) internalFormat = _gl.RGBA8I;
  48936. if ( glType === _gl.SHORT ) internalFormat = _gl.RGBA16I;
  48937. if ( glType === _gl.INT ) internalFormat = _gl.RGBA32I;
  48938. }
  48939. if ( glFormat === _gl.RGB ) {
  48940. if ( glType === _gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = _gl.RGB9_E5;
  48941. if ( glType === _gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = _gl.R11F_G11F_B10F;
  48942. }
  48943. if ( glFormat === _gl.RGBA ) {
  48944. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  48945. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  48946. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  48947. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  48948. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  48949. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  48950. }
  48951. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  48952. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  48953. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  48954. extensions.get( 'EXT_color_buffer_float' );
  48955. }
  48956. return internalFormat;
  48957. }
  48958. function getInternalDepthFormat( useStencil, depthType ) {
  48959. let glInternalFormat;
  48960. if ( useStencil ) {
  48961. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  48962. glInternalFormat = _gl.DEPTH24_STENCIL8;
  48963. } else if ( depthType === FloatType ) {
  48964. glInternalFormat = _gl.DEPTH32F_STENCIL8;
  48965. } else if ( depthType === UnsignedShortType ) {
  48966. glInternalFormat = _gl.DEPTH24_STENCIL8;
  48967. console.warn( 'DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.' );
  48968. }
  48969. } else {
  48970. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  48971. glInternalFormat = _gl.DEPTH_COMPONENT24;
  48972. } else if ( depthType === FloatType ) {
  48973. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  48974. } else if ( depthType === UnsignedShortType ) {
  48975. glInternalFormat = _gl.DEPTH_COMPONENT16;
  48976. }
  48977. }
  48978. return glInternalFormat;
  48979. }
  48980. function getMipLevels( texture, image ) {
  48981. if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  48982. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  48983. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  48984. // user-defined mipmaps
  48985. return texture.mipmaps.length;
  48986. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  48987. return image.mipmaps.length;
  48988. } else {
  48989. // texture without mipmaps (only base level)
  48990. return 1;
  48991. }
  48992. }
  48993. //
  48994. function onTextureDispose( event ) {
  48995. const texture = event.target;
  48996. texture.removeEventListener( 'dispose', onTextureDispose );
  48997. deallocateTexture( texture );
  48998. if ( texture.isVideoTexture ) {
  48999. _videoTextures.delete( texture );
  49000. }
  49001. }
  49002. function onRenderTargetDispose( event ) {
  49003. const renderTarget = event.target;
  49004. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  49005. deallocateRenderTarget( renderTarget );
  49006. }
  49007. //
  49008. function deallocateTexture( texture ) {
  49009. const textureProperties = properties.get( texture );
  49010. if ( textureProperties.__webglInit === undefined ) return;
  49011. // check if it's necessary to remove the WebGLTexture object
  49012. const source = texture.source;
  49013. const webglTextures = _sources.get( source );
  49014. if ( webglTextures ) {
  49015. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  49016. webglTexture.usedTimes --;
  49017. // the WebGLTexture object is not used anymore, remove it
  49018. if ( webglTexture.usedTimes === 0 ) {
  49019. deleteTexture( texture );
  49020. }
  49021. // remove the weak map entry if no WebGLTexture uses the source anymore
  49022. if ( Object.keys( webglTextures ).length === 0 ) {
  49023. _sources.delete( source );
  49024. }
  49025. }
  49026. properties.remove( texture );
  49027. }
  49028. function deleteTexture( texture ) {
  49029. const textureProperties = properties.get( texture );
  49030. _gl.deleteTexture( textureProperties.__webglTexture );
  49031. const source = texture.source;
  49032. const webglTextures = _sources.get( source );
  49033. delete webglTextures[ textureProperties.__cacheKey ];
  49034. info.memory.textures --;
  49035. }
  49036. function deallocateRenderTarget( renderTarget ) {
  49037. const renderTargetProperties = properties.get( renderTarget );
  49038. if ( renderTarget.depthTexture ) {
  49039. renderTarget.depthTexture.dispose();
  49040. properties.remove( renderTarget.depthTexture );
  49041. }
  49042. if ( renderTarget.isWebGLCubeRenderTarget ) {
  49043. for ( let i = 0; i < 6; i ++ ) {
  49044. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  49045. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  49046. } else {
  49047. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  49048. }
  49049. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  49050. }
  49051. } else {
  49052. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  49053. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  49054. } else {
  49055. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  49056. }
  49057. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  49058. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  49059. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  49060. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  49061. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  49062. }
  49063. }
  49064. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  49065. }
  49066. const textures = renderTarget.textures;
  49067. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49068. const attachmentProperties = properties.get( textures[ i ] );
  49069. if ( attachmentProperties.__webglTexture ) {
  49070. _gl.deleteTexture( attachmentProperties.__webglTexture );
  49071. info.memory.textures --;
  49072. }
  49073. properties.remove( textures[ i ] );
  49074. }
  49075. properties.remove( renderTarget );
  49076. }
  49077. //
  49078. let textureUnits = 0;
  49079. function resetTextureUnits() {
  49080. textureUnits = 0;
  49081. }
  49082. function allocateTextureUnit() {
  49083. const textureUnit = textureUnits;
  49084. if ( textureUnit >= capabilities.maxTextures ) {
  49085. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  49086. }
  49087. textureUnits += 1;
  49088. return textureUnit;
  49089. }
  49090. function getTextureCacheKey( texture ) {
  49091. const array = [];
  49092. array.push( texture.wrapS );
  49093. array.push( texture.wrapT );
  49094. array.push( texture.wrapR || 0 );
  49095. array.push( texture.magFilter );
  49096. array.push( texture.minFilter );
  49097. array.push( texture.anisotropy );
  49098. array.push( texture.internalFormat );
  49099. array.push( texture.format );
  49100. array.push( texture.type );
  49101. array.push( texture.generateMipmaps );
  49102. array.push( texture.premultiplyAlpha );
  49103. array.push( texture.flipY );
  49104. array.push( texture.unpackAlignment );
  49105. array.push( texture.colorSpace );
  49106. return array.join();
  49107. }
  49108. //
  49109. function setTexture2D( texture, slot ) {
  49110. const textureProperties = properties.get( texture );
  49111. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  49112. if ( texture.isRenderTargetTexture === false && texture.isExternalTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49113. const image = texture.image;
  49114. if ( image === null ) {
  49115. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  49116. } else if ( image.complete === false ) {
  49117. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  49118. } else {
  49119. uploadTexture( textureProperties, texture, slot );
  49120. return;
  49121. }
  49122. } else if ( texture.isExternalTexture ) {
  49123. textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null;
  49124. }
  49125. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49126. }
  49127. function setTexture2DArray( texture, slot ) {
  49128. const textureProperties = properties.get( texture );
  49129. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49130. uploadTexture( textureProperties, texture, slot );
  49131. return;
  49132. }
  49133. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49134. }
  49135. function setTexture3D( texture, slot ) {
  49136. const textureProperties = properties.get( texture );
  49137. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49138. uploadTexture( textureProperties, texture, slot );
  49139. return;
  49140. }
  49141. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49142. }
  49143. function setTextureCube( texture, slot ) {
  49144. const textureProperties = properties.get( texture );
  49145. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  49146. uploadCubeTexture( textureProperties, texture, slot );
  49147. return;
  49148. }
  49149. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49150. }
  49151. const wrappingToGL = {
  49152. [ RepeatWrapping ]: _gl.REPEAT,
  49153. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  49154. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  49155. };
  49156. const filterToGL = {
  49157. [ NearestFilter ]: _gl.NEAREST,
  49158. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  49159. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  49160. [ LinearFilter ]: _gl.LINEAR,
  49161. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  49162. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  49163. };
  49164. const compareToGL = {
  49165. [ NeverCompare ]: _gl.NEVER,
  49166. [ AlwaysCompare ]: _gl.ALWAYS,
  49167. [ LessCompare ]: _gl.LESS,
  49168. [ LessEqualCompare ]: _gl.LEQUAL,
  49169. [ EqualCompare ]: _gl.EQUAL,
  49170. [ GreaterEqualCompare ]: _gl.GEQUAL,
  49171. [ GreaterCompare ]: _gl.GREATER,
  49172. [ NotEqualCompare ]: _gl.NOTEQUAL
  49173. };
  49174. function setTextureParameters( textureType, texture ) {
  49175. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false &&
  49176. ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  49177. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) {
  49178. console.warn( 'THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' );
  49179. }
  49180. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  49181. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  49182. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  49183. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  49184. }
  49185. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  49186. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  49187. if ( texture.compareFunction ) {
  49188. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  49189. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  49190. }
  49191. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  49192. if ( texture.magFilter === NearestFilter ) return;
  49193. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  49194. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension
  49195. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  49196. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  49197. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  49198. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  49199. }
  49200. }
  49201. }
  49202. function initTexture( textureProperties, texture ) {
  49203. let forceUpload = false;
  49204. if ( textureProperties.__webglInit === undefined ) {
  49205. textureProperties.__webglInit = true;
  49206. texture.addEventListener( 'dispose', onTextureDispose );
  49207. }
  49208. // create Source <-> WebGLTextures mapping if necessary
  49209. const source = texture.source;
  49210. let webglTextures = _sources.get( source );
  49211. if ( webglTextures === undefined ) {
  49212. webglTextures = {};
  49213. _sources.set( source, webglTextures );
  49214. }
  49215. // check if there is already a WebGLTexture object for the given texture parameters
  49216. const textureCacheKey = getTextureCacheKey( texture );
  49217. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  49218. // if not, create a new instance of WebGLTexture
  49219. if ( webglTextures[ textureCacheKey ] === undefined ) {
  49220. // create new entry
  49221. webglTextures[ textureCacheKey ] = {
  49222. texture: _gl.createTexture(),
  49223. usedTimes: 0
  49224. };
  49225. info.memory.textures ++;
  49226. // when a new instance of WebGLTexture was created, a texture upload is required
  49227. // even if the image contents are identical
  49228. forceUpload = true;
  49229. }
  49230. webglTextures[ textureCacheKey ].usedTimes ++;
  49231. // every time the texture cache key changes, it's necessary to check if an instance of
  49232. // WebGLTexture can be deleted in order to avoid a memory leak.
  49233. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  49234. if ( webglTexture !== undefined ) {
  49235. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  49236. if ( webglTexture.usedTimes === 0 ) {
  49237. deleteTexture( texture );
  49238. }
  49239. }
  49240. // store references to cache key and WebGLTexture object
  49241. textureProperties.__cacheKey = textureCacheKey;
  49242. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  49243. }
  49244. return forceUpload;
  49245. }
  49246. function getRow( index, rowLength, componentStride ) {
  49247. return Math.floor( Math.floor( index / componentStride ) / rowLength );
  49248. }
  49249. function updateTexture( texture, image, glFormat, glType ) {
  49250. const componentStride = 4; // only RGBA supported
  49251. const updateRanges = texture.updateRanges;
  49252. if ( updateRanges.length === 0 ) {
  49253. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  49254. } else {
  49255. // Before applying update ranges, we merge any adjacent / overlapping
  49256. // ranges to reduce load on `gl.texSubImage2D`. Empirically, this has led
  49257. // to performance improvements for applications which make heavy use of
  49258. // update ranges. Likely due to GPU command overhead.
  49259. //
  49260. // Note that to reduce garbage collection between frames, we merge the
  49261. // update ranges in-place. This is safe because this method will clear the
  49262. // update ranges once updated.
  49263. updateRanges.sort( ( a, b ) => a.start - b.start );
  49264. // To merge the update ranges in-place, we work from left to right in the
  49265. // existing updateRanges array, merging ranges. This may result in a final
  49266. // array which is smaller than the original. This index tracks the last
  49267. // index representing a merged range, any data after this index can be
  49268. // trimmed once the merge algorithm is completed.
  49269. let mergeIndex = 0;
  49270. for ( let i = 1; i < updateRanges.length; i ++ ) {
  49271. const previousRange = updateRanges[ mergeIndex ];
  49272. const range = updateRanges[ i ];
  49273. // Only merge if in the same row and overlapping/adjacent
  49274. const previousEnd = previousRange.start + previousRange.count;
  49275. const currentRow = getRow( range.start, image.width, componentStride );
  49276. const previousRow = getRow( previousRange.start, image.width, componentStride );
  49277. // We add one here to merge adjacent ranges. This is safe because ranges
  49278. // operate over positive integers.
  49279. if (
  49280. range.start <= previousEnd + 1 &&
  49281. currentRow === previousRow &&
  49282. getRow( range.start + range.count - 1, image.width, componentStride ) === currentRow // ensure range doesn't spill
  49283. ) {
  49284. previousRange.count = Math.max(
  49285. previousRange.count,
  49286. range.start + range.count - previousRange.start
  49287. );
  49288. } else {
  49289. ++ mergeIndex;
  49290. updateRanges[ mergeIndex ] = range;
  49291. }
  49292. }
  49293. // Trim the array to only contain the merged ranges.
  49294. updateRanges.length = mergeIndex + 1;
  49295. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  49296. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  49297. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  49298. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  49299. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  49300. const range = updateRanges[ i ];
  49301. const pixelStart = Math.floor( range.start / componentStride );
  49302. const pixelCount = Math.ceil( range.count / componentStride );
  49303. const x = pixelStart % image.width;
  49304. const y = Math.floor( pixelStart / image.width );
  49305. // Assumes update ranges refer to contiguous memory
  49306. const width = pixelCount;
  49307. const height = 1;
  49308. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, x );
  49309. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, y );
  49310. state.texSubImage2D( _gl.TEXTURE_2D, 0, x, y, width, height, glFormat, glType, image.data );
  49311. }
  49312. texture.clearUpdateRanges();
  49313. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  49314. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  49315. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  49316. }
  49317. }
  49318. function uploadTexture( textureProperties, texture, slot ) {
  49319. let textureType = _gl.TEXTURE_2D;
  49320. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  49321. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  49322. const forceUpload = initTexture( textureProperties, texture );
  49323. const source = texture.source;
  49324. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49325. const sourceProperties = properties.get( source );
  49326. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  49327. state.activeTexture( _gl.TEXTURE0 + slot );
  49328. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  49329. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  49330. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  49331. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  49332. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  49333. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  49334. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  49335. let image = resizeImage( texture.image, false, capabilities.maxTextureSize );
  49336. image = verifyColorSpace( texture, image );
  49337. const glFormat = utils.convert( texture.format, texture.colorSpace );
  49338. const glType = utils.convert( texture.type );
  49339. let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  49340. setTextureParameters( textureType, texture );
  49341. let mipmap;
  49342. const mipmaps = texture.mipmaps;
  49343. const useTexStorage = ( texture.isVideoTexture !== true );
  49344. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  49345. const dataReady = source.dataReady;
  49346. const levels = getMipLevels( texture, image );
  49347. if ( texture.isDepthTexture ) {
  49348. glInternalFormat = getInternalDepthFormat( texture.format === DepthStencilFormat, texture.type );
  49349. //
  49350. if ( allocateMemory ) {
  49351. if ( useTexStorage ) {
  49352. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  49353. } else {
  49354. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  49355. }
  49356. }
  49357. } else if ( texture.isDataTexture ) {
  49358. // use manually created mipmaps if available
  49359. // if there are no manual mipmaps
  49360. // set 0 level mipmap and then use GL to generate other mipmap levels
  49361. if ( mipmaps.length > 0 ) {
  49362. if ( useTexStorage && allocateMemory ) {
  49363. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  49364. }
  49365. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49366. mipmap = mipmaps[ i ];
  49367. if ( useTexStorage ) {
  49368. if ( dataReady ) {
  49369. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  49370. }
  49371. } else {
  49372. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  49373. }
  49374. }
  49375. texture.generateMipmaps = false;
  49376. } else {
  49377. if ( useTexStorage ) {
  49378. if ( allocateMemory ) {
  49379. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  49380. }
  49381. if ( dataReady ) {
  49382. updateTexture( texture, image, glFormat, glType );
  49383. }
  49384. } else {
  49385. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  49386. }
  49387. }
  49388. } else if ( texture.isCompressedTexture ) {
  49389. if ( texture.isCompressedArrayTexture ) {
  49390. if ( useTexStorage && allocateMemory ) {
  49391. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  49392. }
  49393. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49394. mipmap = mipmaps[ i ];
  49395. if ( texture.format !== RGBAFormat ) {
  49396. if ( glFormat !== null ) {
  49397. if ( useTexStorage ) {
  49398. if ( dataReady ) {
  49399. if ( texture.layerUpdates.size > 0 ) {
  49400. const layerByteLength = getByteLength( mipmap.width, mipmap.height, texture.format, texture.type );
  49401. for ( const layerIndex of texture.layerUpdates ) {
  49402. const layerData = mipmap.data.subarray(
  49403. layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT,
  49404. ( layerIndex + 1 ) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT
  49405. );
  49406. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData );
  49407. }
  49408. texture.clearLayerUpdates();
  49409. } else {
  49410. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  49411. }
  49412. }
  49413. } else {
  49414. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  49415. }
  49416. } else {
  49417. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  49418. }
  49419. } else {
  49420. if ( useTexStorage ) {
  49421. if ( dataReady ) {
  49422. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  49423. }
  49424. } else {
  49425. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  49426. }
  49427. }
  49428. }
  49429. } else {
  49430. if ( useTexStorage && allocateMemory ) {
  49431. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  49432. }
  49433. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49434. mipmap = mipmaps[ i ];
  49435. if ( texture.format !== RGBAFormat ) {
  49436. if ( glFormat !== null ) {
  49437. if ( useTexStorage ) {
  49438. if ( dataReady ) {
  49439. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  49440. }
  49441. } else {
  49442. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  49443. }
  49444. } else {
  49445. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  49446. }
  49447. } else {
  49448. if ( useTexStorage ) {
  49449. if ( dataReady ) {
  49450. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  49451. }
  49452. } else {
  49453. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  49454. }
  49455. }
  49456. }
  49457. }
  49458. } else if ( texture.isDataArrayTexture ) {
  49459. if ( useTexStorage ) {
  49460. if ( allocateMemory ) {
  49461. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  49462. }
  49463. if ( dataReady ) {
  49464. if ( texture.layerUpdates.size > 0 ) {
  49465. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  49466. for ( const layerIndex of texture.layerUpdates ) {
  49467. const layerData = image.data.subarray(
  49468. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  49469. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  49470. );
  49471. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  49472. }
  49473. texture.clearLayerUpdates();
  49474. } else {
  49475. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  49476. }
  49477. }
  49478. } else {
  49479. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  49480. }
  49481. } else if ( texture.isData3DTexture ) {
  49482. if ( useTexStorage ) {
  49483. if ( allocateMemory ) {
  49484. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  49485. }
  49486. if ( dataReady ) {
  49487. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  49488. }
  49489. } else {
  49490. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  49491. }
  49492. } else if ( texture.isFramebufferTexture ) {
  49493. if ( allocateMemory ) {
  49494. if ( useTexStorage ) {
  49495. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  49496. } else {
  49497. let width = image.width, height = image.height;
  49498. for ( let i = 0; i < levels; i ++ ) {
  49499. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  49500. width >>= 1;
  49501. height >>= 1;
  49502. }
  49503. }
  49504. }
  49505. } else {
  49506. // regular Texture (image, video, canvas)
  49507. // use manually created mipmaps if available
  49508. // if there are no manual mipmaps
  49509. // set 0 level mipmap and then use GL to generate other mipmap levels
  49510. if ( mipmaps.length > 0 ) {
  49511. if ( useTexStorage && allocateMemory ) {
  49512. const dimensions = getDimensions( mipmaps[ 0 ] );
  49513. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  49514. }
  49515. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49516. mipmap = mipmaps[ i ];
  49517. if ( useTexStorage ) {
  49518. if ( dataReady ) {
  49519. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  49520. }
  49521. } else {
  49522. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  49523. }
  49524. }
  49525. texture.generateMipmaps = false;
  49526. } else {
  49527. if ( useTexStorage ) {
  49528. if ( allocateMemory ) {
  49529. const dimensions = getDimensions( image );
  49530. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  49531. }
  49532. if ( dataReady ) {
  49533. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  49534. }
  49535. } else {
  49536. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  49537. }
  49538. }
  49539. }
  49540. if ( textureNeedsGenerateMipmaps( texture ) ) {
  49541. generateMipmap( textureType );
  49542. }
  49543. sourceProperties.__version = source.version;
  49544. if ( texture.onUpdate ) texture.onUpdate( texture );
  49545. }
  49546. textureProperties.__version = texture.version;
  49547. }
  49548. function uploadCubeTexture( textureProperties, texture, slot ) {
  49549. if ( texture.image.length !== 6 ) return;
  49550. const forceUpload = initTexture( textureProperties, texture );
  49551. const source = texture.source;
  49552. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49553. const sourceProperties = properties.get( source );
  49554. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  49555. state.activeTexture( _gl.TEXTURE0 + slot );
  49556. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  49557. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  49558. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  49559. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  49560. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  49561. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  49562. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  49563. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  49564. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  49565. const cubeImage = [];
  49566. for ( let i = 0; i < 6; i ++ ) {
  49567. if ( ! isCompressed && ! isDataTexture ) {
  49568. cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize );
  49569. } else {
  49570. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  49571. }
  49572. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  49573. }
  49574. const image = cubeImage[ 0 ],
  49575. glFormat = utils.convert( texture.format, texture.colorSpace ),
  49576. glType = utils.convert( texture.type ),
  49577. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  49578. const useTexStorage = ( texture.isVideoTexture !== true );
  49579. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  49580. const dataReady = source.dataReady;
  49581. let levels = getMipLevels( texture, image );
  49582. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  49583. let mipmaps;
  49584. if ( isCompressed ) {
  49585. if ( useTexStorage && allocateMemory ) {
  49586. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  49587. }
  49588. for ( let i = 0; i < 6; i ++ ) {
  49589. mipmaps = cubeImage[ i ].mipmaps;
  49590. for ( let j = 0; j < mipmaps.length; j ++ ) {
  49591. const mipmap = mipmaps[ j ];
  49592. if ( texture.format !== RGBAFormat ) {
  49593. if ( glFormat !== null ) {
  49594. if ( useTexStorage ) {
  49595. if ( dataReady ) {
  49596. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  49597. }
  49598. } else {
  49599. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  49600. }
  49601. } else {
  49602. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  49603. }
  49604. } else {
  49605. if ( useTexStorage ) {
  49606. if ( dataReady ) {
  49607. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  49608. }
  49609. } else {
  49610. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  49611. }
  49612. }
  49613. }
  49614. }
  49615. } else {
  49616. mipmaps = texture.mipmaps;
  49617. if ( useTexStorage && allocateMemory ) {
  49618. // TODO: Uniformly handle mipmap definitions
  49619. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  49620. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  49621. if ( mipmaps.length > 0 ) levels ++;
  49622. const dimensions = getDimensions( cubeImage[ 0 ] );
  49623. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height );
  49624. }
  49625. for ( let i = 0; i < 6; i ++ ) {
  49626. if ( isDataTexture ) {
  49627. if ( useTexStorage ) {
  49628. if ( dataReady ) {
  49629. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  49630. }
  49631. } else {
  49632. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  49633. }
  49634. for ( let j = 0; j < mipmaps.length; j ++ ) {
  49635. const mipmap = mipmaps[ j ];
  49636. const mipmapImage = mipmap.image[ i ].image;
  49637. if ( useTexStorage ) {
  49638. if ( dataReady ) {
  49639. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  49640. }
  49641. } else {
  49642. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  49643. }
  49644. }
  49645. } else {
  49646. if ( useTexStorage ) {
  49647. if ( dataReady ) {
  49648. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  49649. }
  49650. } else {
  49651. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  49652. }
  49653. for ( let j = 0; j < mipmaps.length; j ++ ) {
  49654. const mipmap = mipmaps[ j ];
  49655. if ( useTexStorage ) {
  49656. if ( dataReady ) {
  49657. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  49658. }
  49659. } else {
  49660. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  49661. }
  49662. }
  49663. }
  49664. }
  49665. }
  49666. if ( textureNeedsGenerateMipmaps( texture ) ) {
  49667. // We assume images for cube map have the same size.
  49668. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  49669. }
  49670. sourceProperties.__version = source.version;
  49671. if ( texture.onUpdate ) texture.onUpdate( texture );
  49672. }
  49673. textureProperties.__version = texture.version;
  49674. }
  49675. // Render targets
  49676. // Setup storage for target texture and bind it to correct framebuffer
  49677. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  49678. const glFormat = utils.convert( texture.format, texture.colorSpace );
  49679. const glType = utils.convert( texture.type );
  49680. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  49681. const renderTargetProperties = properties.get( renderTarget );
  49682. const textureProperties = properties.get( texture );
  49683. textureProperties.__renderTarget = renderTarget;
  49684. if ( ! renderTargetProperties.__hasExternalTextures ) {
  49685. const width = Math.max( 1, renderTarget.width >> level );
  49686. const height = Math.max( 1, renderTarget.height >> level );
  49687. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  49688. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  49689. } else {
  49690. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  49691. }
  49692. }
  49693. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  49694. if ( useMultisampledRTT( renderTarget ) ) {
  49695. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  49696. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  49697. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level );
  49698. }
  49699. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  49700. }
  49701. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  49702. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  49703. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  49704. if ( renderTarget.depthBuffer ) {
  49705. // retrieve the depth attachment types
  49706. const depthTexture = renderTarget.depthTexture;
  49707. const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null;
  49708. const glInternalFormat = getInternalDepthFormat( renderTarget.stencilBuffer, depthType );
  49709. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  49710. // set up the attachment
  49711. const samples = getRenderTargetSamples( renderTarget );
  49712. const isUseMultisampledRTT = useMultisampledRTT( renderTarget );
  49713. if ( isUseMultisampledRTT ) {
  49714. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49715. } else if ( isMultisample ) {
  49716. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49717. } else {
  49718. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  49719. }
  49720. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  49721. } else {
  49722. const textures = renderTarget.textures;
  49723. for ( let i = 0; i < textures.length; i ++ ) {
  49724. const texture = textures[ i ];
  49725. const glFormat = utils.convert( texture.format, texture.colorSpace );
  49726. const glType = utils.convert( texture.type );
  49727. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  49728. const samples = getRenderTargetSamples( renderTarget );
  49729. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  49730. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49731. } else if ( useMultisampledRTT( renderTarget ) ) {
  49732. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49733. } else {
  49734. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  49735. }
  49736. }
  49737. }
  49738. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  49739. }
  49740. // Setup resources for a Depth Texture for a FBO (needs an extension)
  49741. function setupDepthTexture( framebuffer, renderTarget ) {
  49742. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  49743. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  49744. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  49745. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  49746. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  49747. }
  49748. const textureProperties = properties.get( renderTarget.depthTexture );
  49749. textureProperties.__renderTarget = renderTarget;
  49750. // upload an empty depth texture with framebuffer size
  49751. if ( ! textureProperties.__webglTexture ||
  49752. renderTarget.depthTexture.image.width !== renderTarget.width ||
  49753. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  49754. renderTarget.depthTexture.image.width = renderTarget.width;
  49755. renderTarget.depthTexture.image.height = renderTarget.height;
  49756. renderTarget.depthTexture.needsUpdate = true;
  49757. }
  49758. setTexture2D( renderTarget.depthTexture, 0 );
  49759. const webglDepthTexture = textureProperties.__webglTexture;
  49760. const samples = getRenderTargetSamples( renderTarget );
  49761. if ( renderTarget.depthTexture.format === DepthFormat ) {
  49762. if ( useMultisampledRTT( renderTarget ) ) {
  49763. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  49764. } else {
  49765. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  49766. }
  49767. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  49768. if ( useMultisampledRTT( renderTarget ) ) {
  49769. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  49770. } else {
  49771. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  49772. }
  49773. } else {
  49774. throw new Error( 'Unknown depthTexture format' );
  49775. }
  49776. }
  49777. // Setup GL resources for a non-texture depth buffer
  49778. function setupDepthRenderbuffer( renderTarget ) {
  49779. const renderTargetProperties = properties.get( renderTarget );
  49780. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  49781. // if the bound depth texture has changed
  49782. if ( renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture ) {
  49783. // fire the dispose event to get rid of stored state associated with the previously bound depth buffer
  49784. const depthTexture = renderTarget.depthTexture;
  49785. if ( renderTargetProperties.__depthDisposeCallback ) {
  49786. renderTargetProperties.__depthDisposeCallback();
  49787. }
  49788. // set up dispose listeners to track when the currently attached buffer is implicitly unbound
  49789. if ( depthTexture ) {
  49790. const disposeEvent = () => {
  49791. delete renderTargetProperties.__boundDepthTexture;
  49792. delete renderTargetProperties.__depthDisposeCallback;
  49793. depthTexture.removeEventListener( 'dispose', disposeEvent );
  49794. };
  49795. depthTexture.addEventListener( 'dispose', disposeEvent );
  49796. renderTargetProperties.__depthDisposeCallback = disposeEvent;
  49797. }
  49798. renderTargetProperties.__boundDepthTexture = depthTexture;
  49799. }
  49800. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  49801. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  49802. const mipmaps = renderTarget.texture.mipmaps;
  49803. if ( mipmaps && mipmaps.length > 0 ) {
  49804. setupDepthTexture( renderTargetProperties.__webglFramebuffer[ 0 ], renderTarget );
  49805. } else {
  49806. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  49807. }
  49808. } else {
  49809. if ( isCube ) {
  49810. renderTargetProperties.__webglDepthbuffer = [];
  49811. for ( let i = 0; i < 6; i ++ ) {
  49812. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  49813. if ( renderTargetProperties.__webglDepthbuffer[ i ] === undefined ) {
  49814. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  49815. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  49816. } else {
  49817. // attach buffer if it's been created already
  49818. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  49819. const renderbuffer = renderTargetProperties.__webglDepthbuffer[ i ];
  49820. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  49821. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  49822. }
  49823. }
  49824. } else {
  49825. const mipmaps = renderTarget.texture.mipmaps;
  49826. if ( mipmaps && mipmaps.length > 0 ) {
  49827. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  49828. } else {
  49829. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  49830. }
  49831. if ( renderTargetProperties.__webglDepthbuffer === undefined ) {
  49832. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  49833. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  49834. } else {
  49835. // attach buffer if it's been created already
  49836. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  49837. const renderbuffer = renderTargetProperties.__webglDepthbuffer;
  49838. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  49839. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  49840. }
  49841. }
  49842. }
  49843. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  49844. }
  49845. // rebind framebuffer with external textures
  49846. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  49847. const renderTargetProperties = properties.get( renderTarget );
  49848. if ( colorTexture !== undefined ) {
  49849. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  49850. }
  49851. if ( depthTexture !== undefined ) {
  49852. setupDepthRenderbuffer( renderTarget );
  49853. }
  49854. }
  49855. // Set up GL resources for the render target
  49856. function setupRenderTarget( renderTarget ) {
  49857. const texture = renderTarget.texture;
  49858. const renderTargetProperties = properties.get( renderTarget );
  49859. const textureProperties = properties.get( texture );
  49860. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  49861. const textures = renderTarget.textures;
  49862. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  49863. const isMultipleRenderTargets = ( textures.length > 1 );
  49864. if ( ! isMultipleRenderTargets ) {
  49865. if ( textureProperties.__webglTexture === undefined ) {
  49866. textureProperties.__webglTexture = _gl.createTexture();
  49867. }
  49868. textureProperties.__version = texture.version;
  49869. info.memory.textures ++;
  49870. }
  49871. // Setup framebuffer
  49872. if ( isCube ) {
  49873. renderTargetProperties.__webglFramebuffer = [];
  49874. for ( let i = 0; i < 6; i ++ ) {
  49875. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  49876. renderTargetProperties.__webglFramebuffer[ i ] = [];
  49877. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  49878. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  49879. }
  49880. } else {
  49881. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  49882. }
  49883. }
  49884. } else {
  49885. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  49886. renderTargetProperties.__webglFramebuffer = [];
  49887. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  49888. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  49889. }
  49890. } else {
  49891. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  49892. }
  49893. if ( isMultipleRenderTargets ) {
  49894. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49895. const attachmentProperties = properties.get( textures[ i ] );
  49896. if ( attachmentProperties.__webglTexture === undefined ) {
  49897. attachmentProperties.__webglTexture = _gl.createTexture();
  49898. info.memory.textures ++;
  49899. }
  49900. }
  49901. }
  49902. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  49903. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  49904. renderTargetProperties.__webglColorRenderbuffer = [];
  49905. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  49906. for ( let i = 0; i < textures.length; i ++ ) {
  49907. const texture = textures[ i ];
  49908. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  49909. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  49910. const glFormat = utils.convert( texture.format, texture.colorSpace );
  49911. const glType = utils.convert( texture.type );
  49912. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  49913. const samples = getRenderTargetSamples( renderTarget );
  49914. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49915. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  49916. }
  49917. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  49918. if ( renderTarget.depthBuffer ) {
  49919. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  49920. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  49921. }
  49922. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  49923. }
  49924. }
  49925. // Setup color buffer
  49926. if ( isCube ) {
  49927. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  49928. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  49929. for ( let i = 0; i < 6; i ++ ) {
  49930. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  49931. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  49932. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  49933. }
  49934. } else {
  49935. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  49936. }
  49937. }
  49938. if ( textureNeedsGenerateMipmaps( texture ) ) {
  49939. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  49940. }
  49941. state.unbindTexture();
  49942. } else if ( isMultipleRenderTargets ) {
  49943. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49944. const attachment = textures[ i ];
  49945. const attachmentProperties = properties.get( attachment );
  49946. let glTextureType = _gl.TEXTURE_2D;
  49947. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  49948. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  49949. }
  49950. state.bindTexture( glTextureType, attachmentProperties.__webglTexture );
  49951. setTextureParameters( glTextureType, attachment );
  49952. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, glTextureType, 0 );
  49953. if ( textureNeedsGenerateMipmaps( attachment ) ) {
  49954. generateMipmap( glTextureType );
  49955. }
  49956. }
  49957. state.unbindTexture();
  49958. } else {
  49959. let glTextureType = _gl.TEXTURE_2D;
  49960. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  49961. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  49962. }
  49963. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  49964. setTextureParameters( glTextureType, texture );
  49965. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  49966. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  49967. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  49968. }
  49969. } else {
  49970. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  49971. }
  49972. if ( textureNeedsGenerateMipmaps( texture ) ) {
  49973. generateMipmap( glTextureType );
  49974. }
  49975. state.unbindTexture();
  49976. }
  49977. // Setup depth and stencil buffers
  49978. if ( renderTarget.depthBuffer ) {
  49979. setupDepthRenderbuffer( renderTarget );
  49980. }
  49981. }
  49982. function updateRenderTargetMipmap( renderTarget ) {
  49983. const textures = renderTarget.textures;
  49984. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49985. const texture = textures[ i ];
  49986. if ( textureNeedsGenerateMipmaps( texture ) ) {
  49987. const targetType = getTargetType( renderTarget );
  49988. const webglTexture = properties.get( texture ).__webglTexture;
  49989. state.bindTexture( targetType, webglTexture );
  49990. generateMipmap( targetType );
  49991. state.unbindTexture();
  49992. }
  49993. }
  49994. }
  49995. const invalidationArrayRead = [];
  49996. const invalidationArrayDraw = [];
  49997. function updateMultisampleRenderTarget( renderTarget ) {
  49998. if ( renderTarget.samples > 0 ) {
  49999. if ( useMultisampledRTT( renderTarget ) === false ) {
  50000. const textures = renderTarget.textures;
  50001. const width = renderTarget.width;
  50002. const height = renderTarget.height;
  50003. let mask = _gl.COLOR_BUFFER_BIT;
  50004. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50005. const renderTargetProperties = properties.get( renderTarget );
  50006. const isMultipleRenderTargets = ( textures.length > 1 );
  50007. // If MRT we need to remove FBO attachments
  50008. if ( isMultipleRenderTargets ) {
  50009. for ( let i = 0; i < textures.length; i ++ ) {
  50010. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50011. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  50012. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50013. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  50014. }
  50015. }
  50016. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50017. const mipmaps = renderTarget.texture.mipmaps;
  50018. if ( mipmaps && mipmaps.length > 0 ) {
  50019. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  50020. } else {
  50021. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50022. }
  50023. for ( let i = 0; i < textures.length; i ++ ) {
  50024. if ( renderTarget.resolveDepthBuffer ) {
  50025. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  50026. // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799)
  50027. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  50028. }
  50029. if ( isMultipleRenderTargets ) {
  50030. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50031. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  50032. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  50033. }
  50034. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  50035. if ( supportsInvalidateFramebuffer === true ) {
  50036. invalidationArrayRead.length = 0;
  50037. invalidationArrayDraw.length = 0;
  50038. invalidationArrayRead.push( _gl.COLOR_ATTACHMENT0 + i );
  50039. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false ) {
  50040. invalidationArrayRead.push( depthStyle );
  50041. invalidationArrayDraw.push( depthStyle );
  50042. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, invalidationArrayDraw );
  50043. }
  50044. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArrayRead );
  50045. }
  50046. }
  50047. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  50048. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  50049. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  50050. if ( isMultipleRenderTargets ) {
  50051. for ( let i = 0; i < textures.length; i ++ ) {
  50052. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50053. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50054. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  50055. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50056. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  50057. }
  50058. }
  50059. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50060. } else {
  50061. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer ) {
  50062. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50063. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  50064. }
  50065. }
  50066. }
  50067. }
  50068. function getRenderTargetSamples( renderTarget ) {
  50069. return Math.min( capabilities.maxSamples, renderTarget.samples );
  50070. }
  50071. function useMultisampledRTT( renderTarget ) {
  50072. const renderTargetProperties = properties.get( renderTarget );
  50073. return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  50074. }
  50075. function updateVideoTexture( texture ) {
  50076. const frame = info.render.frame;
  50077. // Check the last frame we updated the VideoTexture
  50078. if ( _videoTextures.get( texture ) !== frame ) {
  50079. _videoTextures.set( texture, frame );
  50080. texture.update();
  50081. }
  50082. }
  50083. function verifyColorSpace( texture, image ) {
  50084. const colorSpace = texture.colorSpace;
  50085. const format = texture.format;
  50086. const type = texture.type;
  50087. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image;
  50088. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  50089. // sRGB
  50090. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  50091. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  50092. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  50093. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  50094. }
  50095. } else {
  50096. console.error( 'THREE.WebGLTextures: Unsupported texture color space:', colorSpace );
  50097. }
  50098. }
  50099. return image;
  50100. }
  50101. function getDimensions( image ) {
  50102. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) {
  50103. // if intrinsic data are not available, fallback to width/height
  50104. _imageDimensions.width = image.naturalWidth || image.width;
  50105. _imageDimensions.height = image.naturalHeight || image.height;
  50106. } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) {
  50107. _imageDimensions.width = image.displayWidth;
  50108. _imageDimensions.height = image.displayHeight;
  50109. } else {
  50110. _imageDimensions.width = image.width;
  50111. _imageDimensions.height = image.height;
  50112. }
  50113. return _imageDimensions;
  50114. }
  50115. //
  50116. this.allocateTextureUnit = allocateTextureUnit;
  50117. this.resetTextureUnits = resetTextureUnits;
  50118. this.setTexture2D = setTexture2D;
  50119. this.setTexture2DArray = setTexture2DArray;
  50120. this.setTexture3D = setTexture3D;
  50121. this.setTextureCube = setTextureCube;
  50122. this.rebindTextures = rebindTextures;
  50123. this.setupRenderTarget = setupRenderTarget;
  50124. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  50125. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  50126. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  50127. this.setupFrameBufferTexture = setupFrameBufferTexture;
  50128. this.useMultisampledRTT = useMultisampledRTT;
  50129. }
  50130. function WebGLUtils( gl, extensions ) {
  50131. function convert( p, colorSpace = NoColorSpace ) {
  50132. let extension;
  50133. const transfer = ColorManagement.getTransfer( colorSpace );
  50134. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  50135. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  50136. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  50137. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  50138. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  50139. if ( p === ByteType ) return gl.BYTE;
  50140. if ( p === ShortType ) return gl.SHORT;
  50141. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  50142. if ( p === IntType ) return gl.INT;
  50143. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  50144. if ( p === FloatType ) return gl.FLOAT;
  50145. if ( p === HalfFloatType ) return gl.HALF_FLOAT;
  50146. if ( p === AlphaFormat ) return gl.ALPHA;
  50147. if ( p === RGBFormat ) return gl.RGB;
  50148. if ( p === RGBAFormat ) return gl.RGBA;
  50149. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  50150. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  50151. // WebGL2 formats.
  50152. if ( p === RedFormat ) return gl.RED;
  50153. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  50154. if ( p === RGFormat ) return gl.RG;
  50155. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  50156. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  50157. // S3TC
  50158. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  50159. if ( transfer === SRGBTransfer ) {
  50160. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  50161. if ( extension !== null ) {
  50162. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  50163. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  50164. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  50165. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  50166. } else {
  50167. return null;
  50168. }
  50169. } else {
  50170. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  50171. if ( extension !== null ) {
  50172. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  50173. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  50174. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  50175. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  50176. } else {
  50177. return null;
  50178. }
  50179. }
  50180. }
  50181. // PVRTC
  50182. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  50183. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  50184. if ( extension !== null ) {
  50185. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  50186. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  50187. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  50188. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  50189. } else {
  50190. return null;
  50191. }
  50192. }
  50193. // ETC
  50194. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  50195. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  50196. if ( extension !== null ) {
  50197. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  50198. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  50199. } else {
  50200. return null;
  50201. }
  50202. }
  50203. // ASTC
  50204. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  50205. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  50206. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  50207. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  50208. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  50209. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  50210. if ( extension !== null ) {
  50211. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  50212. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  50213. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  50214. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  50215. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  50216. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  50217. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  50218. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  50219. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  50220. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  50221. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  50222. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  50223. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  50224. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  50225. } else {
  50226. return null;
  50227. }
  50228. }
  50229. // BPTC
  50230. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  50231. extension = extensions.get( 'EXT_texture_compression_bptc' );
  50232. if ( extension !== null ) {
  50233. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  50234. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  50235. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  50236. } else {
  50237. return null;
  50238. }
  50239. }
  50240. // RGTC
  50241. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  50242. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  50243. if ( extension !== null ) {
  50244. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  50245. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  50246. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  50247. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  50248. } else {
  50249. return null;
  50250. }
  50251. }
  50252. //
  50253. if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8;
  50254. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  50255. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  50256. }
  50257. return { convert: convert };
  50258. }
  50259. const _occlusion_vertex = `
  50260. void main() {
  50261. gl_Position = vec4( position, 1.0 );
  50262. }`;
  50263. const _occlusion_fragment = `
  50264. uniform sampler2DArray depthColor;
  50265. uniform float depthWidth;
  50266. uniform float depthHeight;
  50267. void main() {
  50268. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  50269. if ( coord.x >= 1.0 ) {
  50270. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  50271. } else {
  50272. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  50273. }
  50274. }`;
  50275. /**
  50276. * A XR module that manages the access to the Depth Sensing API.
  50277. */
  50278. class WebXRDepthSensing {
  50279. /**
  50280. * Constructs a new depth sensing module.
  50281. */
  50282. constructor() {
  50283. /**
  50284. * An opaque texture representing the depth of the user's environment.
  50285. *
  50286. * @type {?ExternalTexture}
  50287. */
  50288. this.texture = null;
  50289. /**
  50290. * A plane mesh for visualizing the depth texture.
  50291. *
  50292. * @type {?Mesh}
  50293. */
  50294. this.mesh = null;
  50295. /**
  50296. * The depth near value.
  50297. *
  50298. * @type {number}
  50299. */
  50300. this.depthNear = 0;
  50301. /**
  50302. * The depth near far.
  50303. *
  50304. * @type {number}
  50305. */
  50306. this.depthFar = 0;
  50307. }
  50308. /**
  50309. * Inits the depth sensing module
  50310. *
  50311. * @param {XRWebGLDepthInformation} depthData - The XR depth data.
  50312. * @param {XRRenderState} renderState - The XR render state.
  50313. */
  50314. init( depthData, renderState ) {
  50315. if ( this.texture === null ) {
  50316. const texture = new ExternalTexture( depthData.texture );
  50317. if ( ( depthData.depthNear !== renderState.depthNear ) || ( depthData.depthFar !== renderState.depthFar ) ) {
  50318. this.depthNear = depthData.depthNear;
  50319. this.depthFar = depthData.depthFar;
  50320. }
  50321. this.texture = texture;
  50322. }
  50323. }
  50324. /**
  50325. * Returns a plane mesh that visualizes the depth texture.
  50326. *
  50327. * @param {ArrayCamera} cameraXR - The XR camera.
  50328. * @return {?Mesh} The plane mesh.
  50329. */
  50330. getMesh( cameraXR ) {
  50331. if ( this.texture !== null ) {
  50332. if ( this.mesh === null ) {
  50333. const viewport = cameraXR.cameras[ 0 ].viewport;
  50334. const material = new ShaderMaterial( {
  50335. vertexShader: _occlusion_vertex,
  50336. fragmentShader: _occlusion_fragment,
  50337. uniforms: {
  50338. depthColor: { value: this.texture },
  50339. depthWidth: { value: viewport.z },
  50340. depthHeight: { value: viewport.w }
  50341. }
  50342. } );
  50343. this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material );
  50344. }
  50345. }
  50346. return this.mesh;
  50347. }
  50348. /**
  50349. * Resets the module
  50350. */
  50351. reset() {
  50352. this.texture = null;
  50353. this.mesh = null;
  50354. }
  50355. /**
  50356. * Returns a texture representing the depth of the user's environment.
  50357. *
  50358. * @return {?ExternalTexture} The depth texture.
  50359. */
  50360. getDepthTexture() {
  50361. return this.texture;
  50362. }
  50363. }
  50364. /**
  50365. * This class represents an abstraction of the WebXR Device API and is
  50366. * internally used by {@link WebGLRenderer}. `WebXRManager` also provides a public
  50367. * interface that allows users to enable/disable XR and perform XR related
  50368. * tasks like for instance retrieving controllers.
  50369. *
  50370. * @augments EventDispatcher
  50371. * @hideconstructor
  50372. */
  50373. class WebXRManager extends EventDispatcher {
  50374. /**
  50375. * Constructs a new WebGL renderer.
  50376. *
  50377. * @param {WebGLRenderer} renderer - The renderer.
  50378. * @param {WebGL2RenderingContext} gl - The rendering context.
  50379. */
  50380. constructor( renderer, gl ) {
  50381. super();
  50382. const scope = this;
  50383. let session = null;
  50384. let framebufferScaleFactor = 1.0;
  50385. let referenceSpace = null;
  50386. let referenceSpaceType = 'local-floor';
  50387. // Set default foveation to maximum.
  50388. let foveation = 1.0;
  50389. let customReferenceSpace = null;
  50390. let pose = null;
  50391. let glBinding = null;
  50392. let glProjLayer = null;
  50393. let glBaseLayer = null;
  50394. let xrFrame = null;
  50395. const supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  50396. const depthSensing = new WebXRDepthSensing();
  50397. const cameraAccessTextures = {};
  50398. const attributes = gl.getContextAttributes();
  50399. let initialRenderTarget = null;
  50400. let newRenderTarget = null;
  50401. const controllers = [];
  50402. const controllerInputSources = [];
  50403. const currentSize = new Vector2();
  50404. let currentPixelRatio = null;
  50405. //
  50406. const cameraL = new PerspectiveCamera();
  50407. cameraL.viewport = new Vector4();
  50408. const cameraR = new PerspectiveCamera();
  50409. cameraR.viewport = new Vector4();
  50410. const cameras = [ cameraL, cameraR ];
  50411. const cameraXR = new ArrayCamera();
  50412. let _currentDepthNear = null;
  50413. let _currentDepthFar = null;
  50414. //
  50415. /**
  50416. * Whether the manager's XR camera should be automatically updated or not.
  50417. *
  50418. * @type {boolean}
  50419. * @default true
  50420. */
  50421. this.cameraAutoUpdate = true;
  50422. /**
  50423. * This flag notifies the renderer to be ready for XR rendering. Set it to `true`
  50424. * if you are going to use XR in your app.
  50425. *
  50426. * @type {boolean}
  50427. * @default false
  50428. */
  50429. this.enabled = false;
  50430. /**
  50431. * Whether XR presentation is active or not.
  50432. *
  50433. * @type {boolean}
  50434. * @readonly
  50435. * @default false
  50436. */
  50437. this.isPresenting = false;
  50438. /**
  50439. * Returns a group representing the `target ray` space of the XR controller.
  50440. * Use this space for visualizing 3D objects that support the user in pointing
  50441. * tasks like UI interaction.
  50442. *
  50443. * @param {number} index - The index of the controller.
  50444. * @return {Group} A group representing the `target ray` space.
  50445. */
  50446. this.getController = function ( index ) {
  50447. let controller = controllers[ index ];
  50448. if ( controller === undefined ) {
  50449. controller = new WebXRController();
  50450. controllers[ index ] = controller;
  50451. }
  50452. return controller.getTargetRaySpace();
  50453. };
  50454. /**
  50455. * Returns a group representing the `grip` space of the XR controller.
  50456. * Use this space for visualizing 3D objects that support the user in pointing
  50457. * tasks like UI interaction.
  50458. *
  50459. * Note: If you want to show something in the user's hand AND offer a
  50460. * pointing ray at the same time, you'll want to attached the handheld object
  50461. * to the group returned by `getControllerGrip()` and the ray to the
  50462. * group returned by `getController()`. The idea is to have two
  50463. * different groups in two different coordinate spaces for the same WebXR
  50464. * controller.
  50465. *
  50466. * @param {number} index - The index of the controller.
  50467. * @return {Group} A group representing the `grip` space.
  50468. */
  50469. this.getControllerGrip = function ( index ) {
  50470. let controller = controllers[ index ];
  50471. if ( controller === undefined ) {
  50472. controller = new WebXRController();
  50473. controllers[ index ] = controller;
  50474. }
  50475. return controller.getGripSpace();
  50476. };
  50477. /**
  50478. * Returns a group representing the `hand` space of the XR controller.
  50479. * Use this space for visualizing 3D objects that support the user in pointing
  50480. * tasks like UI interaction.
  50481. *
  50482. * @param {number} index - The index of the controller.
  50483. * @return {Group} A group representing the `hand` space.
  50484. */
  50485. this.getHand = function ( index ) {
  50486. let controller = controllers[ index ];
  50487. if ( controller === undefined ) {
  50488. controller = new WebXRController();
  50489. controllers[ index ] = controller;
  50490. }
  50491. return controller.getHandSpace();
  50492. };
  50493. //
  50494. function onSessionEvent( event ) {
  50495. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  50496. if ( controllerIndex === -1 ) {
  50497. return;
  50498. }
  50499. const controller = controllers[ controllerIndex ];
  50500. if ( controller !== undefined ) {
  50501. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  50502. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  50503. }
  50504. }
  50505. function onSessionEnd() {
  50506. session.removeEventListener( 'select', onSessionEvent );
  50507. session.removeEventListener( 'selectstart', onSessionEvent );
  50508. session.removeEventListener( 'selectend', onSessionEvent );
  50509. session.removeEventListener( 'squeeze', onSessionEvent );
  50510. session.removeEventListener( 'squeezestart', onSessionEvent );
  50511. session.removeEventListener( 'squeezeend', onSessionEvent );
  50512. session.removeEventListener( 'end', onSessionEnd );
  50513. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  50514. for ( let i = 0; i < controllers.length; i ++ ) {
  50515. const inputSource = controllerInputSources[ i ];
  50516. if ( inputSource === null ) continue;
  50517. controllerInputSources[ i ] = null;
  50518. controllers[ i ].disconnect( inputSource );
  50519. }
  50520. _currentDepthNear = null;
  50521. _currentDepthFar = null;
  50522. depthSensing.reset();
  50523. for ( const key in cameraAccessTextures ) {
  50524. delete cameraAccessTextures[ key ];
  50525. }
  50526. // restore framebuffer/rendering state
  50527. renderer.setRenderTarget( initialRenderTarget );
  50528. glBaseLayer = null;
  50529. glProjLayer = null;
  50530. glBinding = null;
  50531. session = null;
  50532. newRenderTarget = null;
  50533. //
  50534. animation.stop();
  50535. scope.isPresenting = false;
  50536. renderer.setPixelRatio( currentPixelRatio );
  50537. renderer.setSize( currentSize.width, currentSize.height, false );
  50538. scope.dispatchEvent( { type: 'sessionend' } );
  50539. }
  50540. /**
  50541. * Sets the framebuffer scale factor.
  50542. *
  50543. * This method can not be used during a XR session.
  50544. *
  50545. * @param {number} value - The framebuffer scale factor.
  50546. */
  50547. this.setFramebufferScaleFactor = function ( value ) {
  50548. framebufferScaleFactor = value;
  50549. if ( scope.isPresenting === true ) {
  50550. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  50551. }
  50552. };
  50553. /**
  50554. * Sets the reference space type. Can be used to configure a spatial relationship with the user's physical
  50555. * environment. Depending on how the user moves in 3D space, setting an appropriate reference space can
  50556. * improve tracking. Default is `local-floor`. Valid values can be found here
  50557. * https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpace#reference_space_types.
  50558. *
  50559. * This method can not be used during a XR session.
  50560. *
  50561. * @param {string} value - The reference space type.
  50562. */
  50563. this.setReferenceSpaceType = function ( value ) {
  50564. referenceSpaceType = value;
  50565. if ( scope.isPresenting === true ) {
  50566. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  50567. }
  50568. };
  50569. /**
  50570. * Returns the XR reference space.
  50571. *
  50572. * @return {XRReferenceSpace} The XR reference space.
  50573. */
  50574. this.getReferenceSpace = function () {
  50575. return customReferenceSpace || referenceSpace;
  50576. };
  50577. /**
  50578. * Sets a custom XR reference space.
  50579. *
  50580. * @param {XRReferenceSpace} space - The XR reference space.
  50581. */
  50582. this.setReferenceSpace = function ( space ) {
  50583. customReferenceSpace = space;
  50584. };
  50585. /**
  50586. * Returns the current base layer.
  50587. *
  50588. * This is an `XRProjectionLayer` when the targeted XR device supports the
  50589. * WebXR Layers API, or an `XRWebGLLayer` otherwise.
  50590. *
  50591. * @return {?(XRWebGLLayer|XRProjectionLayer)} The XR base layer.
  50592. */
  50593. this.getBaseLayer = function () {
  50594. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  50595. };
  50596. /**
  50597. * Returns the current XR binding.
  50598. *
  50599. * Creates a new binding if needed and the browser is
  50600. * capable of doing so.
  50601. *
  50602. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  50603. */
  50604. this.getBinding = function () {
  50605. if ( glBinding === null && supportsGlBinding ) {
  50606. glBinding = new XRWebGLBinding( session, gl );
  50607. }
  50608. return glBinding;
  50609. };
  50610. /**
  50611. * Returns the current XR frame.
  50612. *
  50613. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  50614. */
  50615. this.getFrame = function () {
  50616. return xrFrame;
  50617. };
  50618. /**
  50619. * Returns the current XR session.
  50620. *
  50621. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  50622. */
  50623. this.getSession = function () {
  50624. return session;
  50625. };
  50626. /**
  50627. * After a XR session has been requested usually with one of the `*Button` modules, it
  50628. * is injected into the renderer with this method. This method triggers the start of
  50629. * the actual XR rendering.
  50630. *
  50631. * @async
  50632. * @param {XRSession} value - The XR session to set.
  50633. * @return {Promise} A Promise that resolves when the session has been set.
  50634. */
  50635. this.setSession = async function ( value ) {
  50636. session = value;
  50637. if ( session !== null ) {
  50638. initialRenderTarget = renderer.getRenderTarget();
  50639. session.addEventListener( 'select', onSessionEvent );
  50640. session.addEventListener( 'selectstart', onSessionEvent );
  50641. session.addEventListener( 'selectend', onSessionEvent );
  50642. session.addEventListener( 'squeeze', onSessionEvent );
  50643. session.addEventListener( 'squeezestart', onSessionEvent );
  50644. session.addEventListener( 'squeezeend', onSessionEvent );
  50645. session.addEventListener( 'end', onSessionEnd );
  50646. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  50647. if ( attributes.xrCompatible !== true ) {
  50648. await gl.makeXRCompatible();
  50649. }
  50650. currentPixelRatio = renderer.getPixelRatio();
  50651. renderer.getSize( currentSize );
  50652. // Check that the browser implements the necessary APIs to use an
  50653. // XRProjectionLayer rather than an XRWebGLLayer
  50654. const supportsLayers = supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype;
  50655. if ( ! supportsLayers ) {
  50656. const layerInit = {
  50657. antialias: attributes.antialias,
  50658. alpha: true,
  50659. depth: attributes.depth,
  50660. stencil: attributes.stencil,
  50661. framebufferScaleFactor: framebufferScaleFactor
  50662. };
  50663. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  50664. session.updateRenderState( { baseLayer: glBaseLayer } );
  50665. renderer.setPixelRatio( 1 );
  50666. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  50667. newRenderTarget = new WebGLRenderTarget(
  50668. glBaseLayer.framebufferWidth,
  50669. glBaseLayer.framebufferHeight,
  50670. {
  50671. format: RGBAFormat,
  50672. type: UnsignedByteType,
  50673. colorSpace: renderer.outputColorSpace,
  50674. stencilBuffer: attributes.stencil,
  50675. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  50676. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false )
  50677. }
  50678. );
  50679. } else {
  50680. let depthFormat = null;
  50681. let depthType = null;
  50682. let glDepthFormat = null;
  50683. if ( attributes.depth ) {
  50684. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  50685. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  50686. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  50687. }
  50688. const projectionlayerInit = {
  50689. colorFormat: gl.RGBA8,
  50690. depthFormat: glDepthFormat,
  50691. scaleFactor: framebufferScaleFactor
  50692. };
  50693. glBinding = this.getBinding();
  50694. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  50695. session.updateRenderState( { layers: [ glProjLayer ] } );
  50696. renderer.setPixelRatio( 1 );
  50697. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  50698. newRenderTarget = new WebGLRenderTarget(
  50699. glProjLayer.textureWidth,
  50700. glProjLayer.textureHeight,
  50701. {
  50702. format: RGBAFormat,
  50703. type: UnsignedByteType,
  50704. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  50705. stencilBuffer: attributes.stencil,
  50706. colorSpace: renderer.outputColorSpace,
  50707. samples: attributes.antialias ? 4 : 0,
  50708. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  50709. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false )
  50710. } );
  50711. }
  50712. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  50713. this.setFoveation( foveation );
  50714. customReferenceSpace = null;
  50715. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  50716. animation.setContext( session );
  50717. animation.start();
  50718. scope.isPresenting = true;
  50719. scope.dispatchEvent( { type: 'sessionstart' } );
  50720. }
  50721. };
  50722. /**
  50723. * Returns the environment blend mode from the current XR session.
  50724. *
  50725. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  50726. */
  50727. this.getEnvironmentBlendMode = function () {
  50728. if ( session !== null ) {
  50729. return session.environmentBlendMode;
  50730. }
  50731. };
  50732. /**
  50733. * Returns the current depth texture computed via depth sensing.
  50734. *
  50735. * See {@link WebXRDepthSensing#getDepthTexture}.
  50736. *
  50737. * @return {?Texture} The depth texture.
  50738. */
  50739. this.getDepthTexture = function () {
  50740. return depthSensing.getDepthTexture();
  50741. };
  50742. function onInputSourcesChange( event ) {
  50743. // Notify disconnected
  50744. for ( let i = 0; i < event.removed.length; i ++ ) {
  50745. const inputSource = event.removed[ i ];
  50746. const index = controllerInputSources.indexOf( inputSource );
  50747. if ( index >= 0 ) {
  50748. controllerInputSources[ index ] = null;
  50749. controllers[ index ].disconnect( inputSource );
  50750. }
  50751. }
  50752. // Notify connected
  50753. for ( let i = 0; i < event.added.length; i ++ ) {
  50754. const inputSource = event.added[ i ];
  50755. let controllerIndex = controllerInputSources.indexOf( inputSource );
  50756. if ( controllerIndex === -1 ) {
  50757. // Assign input source a controller that currently has no input source
  50758. for ( let i = 0; i < controllers.length; i ++ ) {
  50759. if ( i >= controllerInputSources.length ) {
  50760. controllerInputSources.push( inputSource );
  50761. controllerIndex = i;
  50762. break;
  50763. } else if ( controllerInputSources[ i ] === null ) {
  50764. controllerInputSources[ i ] = inputSource;
  50765. controllerIndex = i;
  50766. break;
  50767. }
  50768. }
  50769. // If all controllers do currently receive input we ignore new ones
  50770. if ( controllerIndex === -1 ) break;
  50771. }
  50772. const controller = controllers[ controllerIndex ];
  50773. if ( controller ) {
  50774. controller.connect( inputSource );
  50775. }
  50776. }
  50777. }
  50778. //
  50779. const cameraLPos = new Vector3();
  50780. const cameraRPos = new Vector3();
  50781. /**
  50782. * Assumes 2 cameras that are parallel and share an X-axis, and that
  50783. * the cameras' projection and world matrices have already been set.
  50784. * And that near and far planes are identical for both cameras.
  50785. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  50786. *
  50787. * @param {ArrayCamera} camera - The camera to update.
  50788. * @param {PerspectiveCamera} cameraL - The left camera.
  50789. * @param {PerspectiveCamera} cameraR - The right camera.
  50790. */
  50791. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  50792. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  50793. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  50794. const ipd = cameraLPos.distanceTo( cameraRPos );
  50795. const projL = cameraL.projectionMatrix.elements;
  50796. const projR = cameraR.projectionMatrix.elements;
  50797. // VR systems will have identical far and near planes, and
  50798. // most likely identical top and bottom frustum extents.
  50799. // Use the left camera for these values.
  50800. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  50801. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  50802. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  50803. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  50804. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  50805. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  50806. const left = near * leftFov;
  50807. const right = near * rightFov;
  50808. // Calculate the new camera's position offset from the
  50809. // left camera. xOffset should be roughly half `ipd`.
  50810. const zOffset = ipd / ( - leftFov + rightFov );
  50811. const xOffset = zOffset * - leftFov;
  50812. // TODO: Better way to apply this offset?
  50813. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  50814. camera.translateX( xOffset );
  50815. camera.translateZ( zOffset );
  50816. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  50817. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  50818. // Check if the projection uses an infinite far plane.
  50819. if ( projL[ 10 ] === -1 ) {
  50820. // Use the projection matrix from the left eye.
  50821. // The camera offset is sufficient to include the view volumes
  50822. // of both eyes (assuming symmetric projections).
  50823. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  50824. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  50825. } else {
  50826. // Find the union of the frustum values of the cameras and scale
  50827. // the values so that the near plane's position does not change in world space,
  50828. // although must now be relative to the new union camera.
  50829. const near2 = near + zOffset;
  50830. const far2 = far + zOffset;
  50831. const left2 = left - xOffset;
  50832. const right2 = right + ( ipd - xOffset );
  50833. const top2 = topFov * far / far2 * near2;
  50834. const bottom2 = bottomFov * far / far2 * near2;
  50835. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  50836. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  50837. }
  50838. }
  50839. function updateCamera( camera, parent ) {
  50840. if ( parent === null ) {
  50841. camera.matrixWorld.copy( camera.matrix );
  50842. } else {
  50843. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  50844. }
  50845. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  50846. }
  50847. /**
  50848. * Updates the state of the XR camera. Use this method on app level if you
  50849. * set `cameraAutoUpdate` to `false`. The method requires the non-XR
  50850. * camera of the scene as a parameter. The passed in camera's transformation
  50851. * is automatically adjusted to the position of the XR camera when calling
  50852. * this method.
  50853. *
  50854. * @param {Camera} camera - The camera.
  50855. */
  50856. this.updateCamera = function ( camera ) {
  50857. if ( session === null ) return;
  50858. let depthNear = camera.near;
  50859. let depthFar = camera.far;
  50860. if ( depthSensing.texture !== null ) {
  50861. if ( depthSensing.depthNear > 0 ) depthNear = depthSensing.depthNear;
  50862. if ( depthSensing.depthFar > 0 ) depthFar = depthSensing.depthFar;
  50863. }
  50864. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  50865. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  50866. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  50867. // Note that the new renderState won't apply until the next frame. See #18320
  50868. session.updateRenderState( {
  50869. depthNear: cameraXR.near,
  50870. depthFar: cameraXR.far
  50871. } );
  50872. _currentDepthNear = cameraXR.near;
  50873. _currentDepthFar = cameraXR.far;
  50874. }
  50875. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  50876. cameraXR.layers.mask = camera.layers.mask | 0b110;
  50877. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  50878. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  50879. const parent = camera.parent;
  50880. const cameras = cameraXR.cameras;
  50881. updateCamera( cameraXR, parent );
  50882. for ( let i = 0; i < cameras.length; i ++ ) {
  50883. updateCamera( cameras[ i ], parent );
  50884. }
  50885. // update projection matrix for proper view frustum culling
  50886. if ( cameras.length === 2 ) {
  50887. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  50888. } else {
  50889. // assume single camera setup (AR)
  50890. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  50891. }
  50892. // update user camera and its children
  50893. updateUserCamera( camera, cameraXR, parent );
  50894. };
  50895. function updateUserCamera( camera, cameraXR, parent ) {
  50896. if ( parent === null ) {
  50897. camera.matrix.copy( cameraXR.matrixWorld );
  50898. } else {
  50899. camera.matrix.copy( parent.matrixWorld );
  50900. camera.matrix.invert();
  50901. camera.matrix.multiply( cameraXR.matrixWorld );
  50902. }
  50903. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  50904. camera.updateMatrixWorld( true );
  50905. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  50906. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  50907. if ( camera.isPerspectiveCamera ) {
  50908. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  50909. camera.zoom = 1;
  50910. }
  50911. }
  50912. /**
  50913. * Returns an instance of {@link ArrayCamera} which represents the XR camera
  50914. * of the active XR session. For each view it holds a separate camera object.
  50915. *
  50916. * The camera's `fov` is currently not used and does not reflect the fov of
  50917. * the XR camera. If you need the fov on app level, you have to compute in
  50918. * manually from the XR camera's projection matrices.
  50919. *
  50920. * @return {ArrayCamera} The XR camera.
  50921. */
  50922. this.getCamera = function () {
  50923. return cameraXR;
  50924. };
  50925. /**
  50926. * Returns the amount of foveation used by the XR compositor for the projection layer.
  50927. *
  50928. * @return {number|undefined} The amount of foveation.
  50929. */
  50930. this.getFoveation = function () {
  50931. if ( glProjLayer === null && glBaseLayer === null ) {
  50932. return undefined;
  50933. }
  50934. return foveation;
  50935. };
  50936. /**
  50937. * Sets the foveation value.
  50938. *
  50939. * @param {number} value - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  50940. * and `1` means maximum foveation (the edges render at lower resolution).
  50941. */
  50942. this.setFoveation = function ( value ) {
  50943. // 0 = no foveation = full resolution
  50944. // 1 = maximum foveation = the edges render at lower resolution
  50945. foveation = value;
  50946. if ( glProjLayer !== null ) {
  50947. glProjLayer.fixedFoveation = value;
  50948. }
  50949. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  50950. glBaseLayer.fixedFoveation = value;
  50951. }
  50952. };
  50953. /**
  50954. * Returns `true` if depth sensing is supported.
  50955. *
  50956. * @return {boolean} Whether depth sensing is supported or not.
  50957. */
  50958. this.hasDepthSensing = function () {
  50959. return depthSensing.texture !== null;
  50960. };
  50961. /**
  50962. * Returns the depth sensing mesh.
  50963. *
  50964. * See {@link WebXRDepthSensing#getMesh}.
  50965. *
  50966. * @return {Mesh} The depth sensing mesh.
  50967. */
  50968. this.getDepthSensingMesh = function () {
  50969. return depthSensing.getMesh( cameraXR );
  50970. };
  50971. /**
  50972. * Retrieves an opaque texture from the view-aligned {@link XRCamera}.
  50973. * Only available during the current animation loop.
  50974. *
  50975. * @param {XRCamera} xrCamera - The camera to query.
  50976. * @return {?Texture} An opaque texture representing the current raw camera frame.
  50977. */
  50978. this.getCameraTexture = function ( xrCamera ) {
  50979. return cameraAccessTextures[ xrCamera ];
  50980. };
  50981. // Animation Loop
  50982. let onAnimationFrameCallback = null;
  50983. function onAnimationFrame( time, frame ) {
  50984. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  50985. xrFrame = frame;
  50986. if ( pose !== null ) {
  50987. const views = pose.views;
  50988. if ( glBaseLayer !== null ) {
  50989. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  50990. renderer.setRenderTarget( newRenderTarget );
  50991. }
  50992. let cameraXRNeedsUpdate = false;
  50993. // check if it's necessary to rebuild cameraXR's camera list
  50994. if ( views.length !== cameraXR.cameras.length ) {
  50995. cameraXR.cameras.length = 0;
  50996. cameraXRNeedsUpdate = true;
  50997. }
  50998. for ( let i = 0; i < views.length; i ++ ) {
  50999. const view = views[ i ];
  51000. let viewport = null;
  51001. if ( glBaseLayer !== null ) {
  51002. viewport = glBaseLayer.getViewport( view );
  51003. } else {
  51004. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  51005. viewport = glSubImage.viewport;
  51006. // For side-by-side projection, we only produce a single texture for both eyes.
  51007. if ( i === 0 ) {
  51008. renderer.setRenderTargetTextures(
  51009. newRenderTarget,
  51010. glSubImage.colorTexture,
  51011. glSubImage.depthStencilTexture );
  51012. renderer.setRenderTarget( newRenderTarget );
  51013. }
  51014. }
  51015. let camera = cameras[ i ];
  51016. if ( camera === undefined ) {
  51017. camera = new PerspectiveCamera();
  51018. camera.layers.enable( i );
  51019. camera.viewport = new Vector4();
  51020. cameras[ i ] = camera;
  51021. }
  51022. camera.matrix.fromArray( view.transform.matrix );
  51023. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  51024. camera.projectionMatrix.fromArray( view.projectionMatrix );
  51025. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  51026. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  51027. if ( i === 0 ) {
  51028. cameraXR.matrix.copy( camera.matrix );
  51029. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  51030. }
  51031. if ( cameraXRNeedsUpdate === true ) {
  51032. cameraXR.cameras.push( camera );
  51033. }
  51034. }
  51035. //
  51036. const enabledFeatures = session.enabledFeatures;
  51037. const gpuDepthSensingEnabled = enabledFeatures &&
  51038. enabledFeatures.includes( 'depth-sensing' ) &&
  51039. session.depthUsage == 'gpu-optimized';
  51040. if ( gpuDepthSensingEnabled && supportsGlBinding ) {
  51041. glBinding = scope.getBinding();
  51042. const depthData = glBinding.getDepthInformation( views[ 0 ] );
  51043. if ( depthData && depthData.isValid && depthData.texture ) {
  51044. depthSensing.init( depthData, session.renderState );
  51045. }
  51046. }
  51047. const cameraAccessEnabled = enabledFeatures &&
  51048. enabledFeatures.includes( 'camera-access' );
  51049. if ( cameraAccessEnabled && supportsGlBinding ) {
  51050. renderer.state.unbindTexture();
  51051. glBinding = scope.getBinding();
  51052. for ( let i = 0; i < views.length; i ++ ) {
  51053. const camera = views[ i ].camera;
  51054. if ( camera ) {
  51055. let cameraTex = cameraAccessTextures[ camera ];
  51056. if ( ! cameraTex ) {
  51057. cameraTex = new ExternalTexture();
  51058. cameraAccessTextures[ camera ] = cameraTex;
  51059. }
  51060. const glTexture = glBinding.getCameraImage( camera );
  51061. cameraTex.sourceTexture = glTexture;
  51062. }
  51063. }
  51064. }
  51065. }
  51066. //
  51067. for ( let i = 0; i < controllers.length; i ++ ) {
  51068. const inputSource = controllerInputSources[ i ];
  51069. const controller = controllers[ i ];
  51070. if ( inputSource !== null && controller !== undefined ) {
  51071. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  51072. }
  51073. }
  51074. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  51075. if ( frame.detectedPlanes ) {
  51076. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  51077. }
  51078. xrFrame = null;
  51079. }
  51080. const animation = new WebGLAnimation();
  51081. animation.setAnimationLoop( onAnimationFrame );
  51082. this.setAnimationLoop = function ( callback ) {
  51083. onAnimationFrameCallback = callback;
  51084. };
  51085. this.dispose = function () {};
  51086. }
  51087. }
  51088. const _e1 = /*@__PURE__*/ new Euler();
  51089. const _m1 = /*@__PURE__*/ new Matrix4();
  51090. function WebGLMaterials( renderer, properties ) {
  51091. function refreshTransformUniform( map, uniform ) {
  51092. if ( map.matrixAutoUpdate === true ) {
  51093. map.updateMatrix();
  51094. }
  51095. uniform.value.copy( map.matrix );
  51096. }
  51097. function refreshFogUniforms( uniforms, fog ) {
  51098. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  51099. if ( fog.isFog ) {
  51100. uniforms.fogNear.value = fog.near;
  51101. uniforms.fogFar.value = fog.far;
  51102. } else if ( fog.isFogExp2 ) {
  51103. uniforms.fogDensity.value = fog.density;
  51104. }
  51105. }
  51106. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  51107. if ( material.isMeshBasicMaterial ) {
  51108. refreshUniformsCommon( uniforms, material );
  51109. } else if ( material.isMeshLambertMaterial ) {
  51110. refreshUniformsCommon( uniforms, material );
  51111. } else if ( material.isMeshToonMaterial ) {
  51112. refreshUniformsCommon( uniforms, material );
  51113. refreshUniformsToon( uniforms, material );
  51114. } else if ( material.isMeshPhongMaterial ) {
  51115. refreshUniformsCommon( uniforms, material );
  51116. refreshUniformsPhong( uniforms, material );
  51117. } else if ( material.isMeshStandardMaterial ) {
  51118. refreshUniformsCommon( uniforms, material );
  51119. refreshUniformsStandard( uniforms, material );
  51120. if ( material.isMeshPhysicalMaterial ) {
  51121. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  51122. }
  51123. } else if ( material.isMeshMatcapMaterial ) {
  51124. refreshUniformsCommon( uniforms, material );
  51125. refreshUniformsMatcap( uniforms, material );
  51126. } else if ( material.isMeshDepthMaterial ) {
  51127. refreshUniformsCommon( uniforms, material );
  51128. } else if ( material.isMeshDistanceMaterial ) {
  51129. refreshUniformsCommon( uniforms, material );
  51130. refreshUniformsDistance( uniforms, material );
  51131. } else if ( material.isMeshNormalMaterial ) {
  51132. refreshUniformsCommon( uniforms, material );
  51133. } else if ( material.isLineBasicMaterial ) {
  51134. refreshUniformsLine( uniforms, material );
  51135. if ( material.isLineDashedMaterial ) {
  51136. refreshUniformsDash( uniforms, material );
  51137. }
  51138. } else if ( material.isPointsMaterial ) {
  51139. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  51140. } else if ( material.isSpriteMaterial ) {
  51141. refreshUniformsSprites( uniforms, material );
  51142. } else if ( material.isShadowMaterial ) {
  51143. uniforms.color.value.copy( material.color );
  51144. uniforms.opacity.value = material.opacity;
  51145. } else if ( material.isShaderMaterial ) {
  51146. material.uniformsNeedUpdate = false; // #15581
  51147. }
  51148. }
  51149. function refreshUniformsCommon( uniforms, material ) {
  51150. uniforms.opacity.value = material.opacity;
  51151. if ( material.color ) {
  51152. uniforms.diffuse.value.copy( material.color );
  51153. }
  51154. if ( material.emissive ) {
  51155. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  51156. }
  51157. if ( material.map ) {
  51158. uniforms.map.value = material.map;
  51159. refreshTransformUniform( material.map, uniforms.mapTransform );
  51160. }
  51161. if ( material.alphaMap ) {
  51162. uniforms.alphaMap.value = material.alphaMap;
  51163. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  51164. }
  51165. if ( material.bumpMap ) {
  51166. uniforms.bumpMap.value = material.bumpMap;
  51167. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  51168. uniforms.bumpScale.value = material.bumpScale;
  51169. if ( material.side === BackSide ) {
  51170. uniforms.bumpScale.value *= -1;
  51171. }
  51172. }
  51173. if ( material.normalMap ) {
  51174. uniforms.normalMap.value = material.normalMap;
  51175. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  51176. uniforms.normalScale.value.copy( material.normalScale );
  51177. if ( material.side === BackSide ) {
  51178. uniforms.normalScale.value.negate();
  51179. }
  51180. }
  51181. if ( material.displacementMap ) {
  51182. uniforms.displacementMap.value = material.displacementMap;
  51183. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  51184. uniforms.displacementScale.value = material.displacementScale;
  51185. uniforms.displacementBias.value = material.displacementBias;
  51186. }
  51187. if ( material.emissiveMap ) {
  51188. uniforms.emissiveMap.value = material.emissiveMap;
  51189. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  51190. }
  51191. if ( material.specularMap ) {
  51192. uniforms.specularMap.value = material.specularMap;
  51193. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  51194. }
  51195. if ( material.alphaTest > 0 ) {
  51196. uniforms.alphaTest.value = material.alphaTest;
  51197. }
  51198. const materialProperties = properties.get( material );
  51199. const envMap = materialProperties.envMap;
  51200. const envMapRotation = materialProperties.envMapRotation;
  51201. if ( envMap ) {
  51202. uniforms.envMap.value = envMap;
  51203. _e1.copy( envMapRotation );
  51204. // accommodate left-handed frame
  51205. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  51206. if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) {
  51207. // environment maps which are not cube render targets or PMREMs follow a different convention
  51208. _e1.y *= -1;
  51209. _e1.z *= -1;
  51210. }
  51211. uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) );
  51212. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  51213. uniforms.reflectivity.value = material.reflectivity;
  51214. uniforms.ior.value = material.ior;
  51215. uniforms.refractionRatio.value = material.refractionRatio;
  51216. }
  51217. if ( material.lightMap ) {
  51218. uniforms.lightMap.value = material.lightMap;
  51219. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  51220. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  51221. }
  51222. if ( material.aoMap ) {
  51223. uniforms.aoMap.value = material.aoMap;
  51224. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  51225. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  51226. }
  51227. }
  51228. function refreshUniformsLine( uniforms, material ) {
  51229. uniforms.diffuse.value.copy( material.color );
  51230. uniforms.opacity.value = material.opacity;
  51231. if ( material.map ) {
  51232. uniforms.map.value = material.map;
  51233. refreshTransformUniform( material.map, uniforms.mapTransform );
  51234. }
  51235. }
  51236. function refreshUniformsDash( uniforms, material ) {
  51237. uniforms.dashSize.value = material.dashSize;
  51238. uniforms.totalSize.value = material.dashSize + material.gapSize;
  51239. uniforms.scale.value = material.scale;
  51240. }
  51241. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  51242. uniforms.diffuse.value.copy( material.color );
  51243. uniforms.opacity.value = material.opacity;
  51244. uniforms.size.value = material.size * pixelRatio;
  51245. uniforms.scale.value = height * 0.5;
  51246. if ( material.map ) {
  51247. uniforms.map.value = material.map;
  51248. refreshTransformUniform( material.map, uniforms.uvTransform );
  51249. }
  51250. if ( material.alphaMap ) {
  51251. uniforms.alphaMap.value = material.alphaMap;
  51252. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  51253. }
  51254. if ( material.alphaTest > 0 ) {
  51255. uniforms.alphaTest.value = material.alphaTest;
  51256. }
  51257. }
  51258. function refreshUniformsSprites( uniforms, material ) {
  51259. uniforms.diffuse.value.copy( material.color );
  51260. uniforms.opacity.value = material.opacity;
  51261. uniforms.rotation.value = material.rotation;
  51262. if ( material.map ) {
  51263. uniforms.map.value = material.map;
  51264. refreshTransformUniform( material.map, uniforms.mapTransform );
  51265. }
  51266. if ( material.alphaMap ) {
  51267. uniforms.alphaMap.value = material.alphaMap;
  51268. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  51269. }
  51270. if ( material.alphaTest > 0 ) {
  51271. uniforms.alphaTest.value = material.alphaTest;
  51272. }
  51273. }
  51274. function refreshUniformsPhong( uniforms, material ) {
  51275. uniforms.specular.value.copy( material.specular );
  51276. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  51277. }
  51278. function refreshUniformsToon( uniforms, material ) {
  51279. if ( material.gradientMap ) {
  51280. uniforms.gradientMap.value = material.gradientMap;
  51281. }
  51282. }
  51283. function refreshUniformsStandard( uniforms, material ) {
  51284. uniforms.metalness.value = material.metalness;
  51285. if ( material.metalnessMap ) {
  51286. uniforms.metalnessMap.value = material.metalnessMap;
  51287. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  51288. }
  51289. uniforms.roughness.value = material.roughness;
  51290. if ( material.roughnessMap ) {
  51291. uniforms.roughnessMap.value = material.roughnessMap;
  51292. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  51293. }
  51294. if ( material.envMap ) {
  51295. //uniforms.envMap.value = material.envMap; // part of uniforms common
  51296. uniforms.envMapIntensity.value = material.envMapIntensity;
  51297. }
  51298. }
  51299. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  51300. uniforms.ior.value = material.ior; // also part of uniforms common
  51301. if ( material.sheen > 0 ) {
  51302. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  51303. uniforms.sheenRoughness.value = material.sheenRoughness;
  51304. if ( material.sheenColorMap ) {
  51305. uniforms.sheenColorMap.value = material.sheenColorMap;
  51306. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  51307. }
  51308. if ( material.sheenRoughnessMap ) {
  51309. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  51310. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  51311. }
  51312. }
  51313. if ( material.clearcoat > 0 ) {
  51314. uniforms.clearcoat.value = material.clearcoat;
  51315. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  51316. if ( material.clearcoatMap ) {
  51317. uniforms.clearcoatMap.value = material.clearcoatMap;
  51318. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  51319. }
  51320. if ( material.clearcoatRoughnessMap ) {
  51321. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  51322. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  51323. }
  51324. if ( material.clearcoatNormalMap ) {
  51325. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  51326. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  51327. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  51328. if ( material.side === BackSide ) {
  51329. uniforms.clearcoatNormalScale.value.negate();
  51330. }
  51331. }
  51332. }
  51333. if ( material.dispersion > 0 ) {
  51334. uniforms.dispersion.value = material.dispersion;
  51335. }
  51336. if ( material.iridescence > 0 ) {
  51337. uniforms.iridescence.value = material.iridescence;
  51338. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  51339. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  51340. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  51341. if ( material.iridescenceMap ) {
  51342. uniforms.iridescenceMap.value = material.iridescenceMap;
  51343. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  51344. }
  51345. if ( material.iridescenceThicknessMap ) {
  51346. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  51347. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  51348. }
  51349. }
  51350. if ( material.transmission > 0 ) {
  51351. uniforms.transmission.value = material.transmission;
  51352. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  51353. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  51354. if ( material.transmissionMap ) {
  51355. uniforms.transmissionMap.value = material.transmissionMap;
  51356. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  51357. }
  51358. uniforms.thickness.value = material.thickness;
  51359. if ( material.thicknessMap ) {
  51360. uniforms.thicknessMap.value = material.thicknessMap;
  51361. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  51362. }
  51363. uniforms.attenuationDistance.value = material.attenuationDistance;
  51364. uniforms.attenuationColor.value.copy( material.attenuationColor );
  51365. }
  51366. if ( material.anisotropy > 0 ) {
  51367. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  51368. if ( material.anisotropyMap ) {
  51369. uniforms.anisotropyMap.value = material.anisotropyMap;
  51370. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  51371. }
  51372. }
  51373. uniforms.specularIntensity.value = material.specularIntensity;
  51374. uniforms.specularColor.value.copy( material.specularColor );
  51375. if ( material.specularColorMap ) {
  51376. uniforms.specularColorMap.value = material.specularColorMap;
  51377. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  51378. }
  51379. if ( material.specularIntensityMap ) {
  51380. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  51381. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  51382. }
  51383. }
  51384. function refreshUniformsMatcap( uniforms, material ) {
  51385. if ( material.matcap ) {
  51386. uniforms.matcap.value = material.matcap;
  51387. }
  51388. }
  51389. function refreshUniformsDistance( uniforms, material ) {
  51390. const light = properties.get( material ).light;
  51391. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  51392. uniforms.nearDistance.value = light.shadow.camera.near;
  51393. uniforms.farDistance.value = light.shadow.camera.far;
  51394. }
  51395. return {
  51396. refreshFogUniforms: refreshFogUniforms,
  51397. refreshMaterialUniforms: refreshMaterialUniforms
  51398. };
  51399. }
  51400. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  51401. let buffers = {};
  51402. let updateList = {};
  51403. let allocatedBindingPoints = [];
  51404. const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program
  51405. function bind( uniformsGroup, program ) {
  51406. const webglProgram = program.program;
  51407. state.uniformBlockBinding( uniformsGroup, webglProgram );
  51408. }
  51409. function update( uniformsGroup, program ) {
  51410. let buffer = buffers[ uniformsGroup.id ];
  51411. if ( buffer === undefined ) {
  51412. prepareUniformsGroup( uniformsGroup );
  51413. buffer = createBuffer( uniformsGroup );
  51414. buffers[ uniformsGroup.id ] = buffer;
  51415. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  51416. }
  51417. // ensure to update the binding points/block indices mapping for this program
  51418. const webglProgram = program.program;
  51419. state.updateUBOMapping( uniformsGroup, webglProgram );
  51420. // update UBO once per frame
  51421. const frame = info.render.frame;
  51422. if ( updateList[ uniformsGroup.id ] !== frame ) {
  51423. updateBufferData( uniformsGroup );
  51424. updateList[ uniformsGroup.id ] = frame;
  51425. }
  51426. }
  51427. function createBuffer( uniformsGroup ) {
  51428. // the setup of an UBO is independent of a particular shader program but global
  51429. const bindingPointIndex = allocateBindingPointIndex();
  51430. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  51431. const buffer = gl.createBuffer();
  51432. const size = uniformsGroup.__size;
  51433. const usage = uniformsGroup.usage;
  51434. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  51435. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  51436. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  51437. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  51438. return buffer;
  51439. }
  51440. function allocateBindingPointIndex() {
  51441. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  51442. if ( allocatedBindingPoints.indexOf( i ) === -1 ) {
  51443. allocatedBindingPoints.push( i );
  51444. return i;
  51445. }
  51446. }
  51447. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  51448. return 0;
  51449. }
  51450. function updateBufferData( uniformsGroup ) {
  51451. const buffer = buffers[ uniformsGroup.id ];
  51452. const uniforms = uniformsGroup.uniforms;
  51453. const cache = uniformsGroup.__cache;
  51454. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  51455. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  51456. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  51457. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  51458. const uniform = uniformArray[ j ];
  51459. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  51460. const offset = uniform.__offset;
  51461. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  51462. let arrayOffset = 0;
  51463. for ( let k = 0; k < values.length; k ++ ) {
  51464. const value = values[ k ];
  51465. const info = getUniformSize( value );
  51466. // TODO add integer and struct support
  51467. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  51468. uniform.__data[ 0 ] = value;
  51469. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  51470. } else if ( value.isMatrix3 ) {
  51471. // manually converting 3x3 to 3x4
  51472. uniform.__data[ 0 ] = value.elements[ 0 ];
  51473. uniform.__data[ 1 ] = value.elements[ 1 ];
  51474. uniform.__data[ 2 ] = value.elements[ 2 ];
  51475. uniform.__data[ 3 ] = 0;
  51476. uniform.__data[ 4 ] = value.elements[ 3 ];
  51477. uniform.__data[ 5 ] = value.elements[ 4 ];
  51478. uniform.__data[ 6 ] = value.elements[ 5 ];
  51479. uniform.__data[ 7 ] = 0;
  51480. uniform.__data[ 8 ] = value.elements[ 6 ];
  51481. uniform.__data[ 9 ] = value.elements[ 7 ];
  51482. uniform.__data[ 10 ] = value.elements[ 8 ];
  51483. uniform.__data[ 11 ] = 0;
  51484. } else {
  51485. value.toArray( uniform.__data, arrayOffset );
  51486. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  51487. }
  51488. }
  51489. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  51490. }
  51491. }
  51492. }
  51493. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  51494. }
  51495. function hasUniformChanged( uniform, index, indexArray, cache ) {
  51496. const value = uniform.value;
  51497. const indexString = index + '_' + indexArray;
  51498. if ( cache[ indexString ] === undefined ) {
  51499. // cache entry does not exist so far
  51500. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  51501. cache[ indexString ] = value;
  51502. } else {
  51503. cache[ indexString ] = value.clone();
  51504. }
  51505. return true;
  51506. } else {
  51507. const cachedObject = cache[ indexString ];
  51508. // compare current value with cached entry
  51509. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  51510. if ( cachedObject !== value ) {
  51511. cache[ indexString ] = value;
  51512. return true;
  51513. }
  51514. } else {
  51515. if ( cachedObject.equals( value ) === false ) {
  51516. cachedObject.copy( value );
  51517. return true;
  51518. }
  51519. }
  51520. }
  51521. return false;
  51522. }
  51523. function prepareUniformsGroup( uniformsGroup ) {
  51524. // determine total buffer size according to the STD140 layout
  51525. // Hint: STD140 is the only supported layout in WebGL 2
  51526. const uniforms = uniformsGroup.uniforms;
  51527. let offset = 0; // global buffer offset in bytes
  51528. const chunkSize = 16; // size of a chunk in bytes
  51529. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  51530. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  51531. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  51532. const uniform = uniformArray[ j ];
  51533. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  51534. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  51535. const value = values[ k ];
  51536. const info = getUniformSize( value );
  51537. const chunkOffset = offset % chunkSize; // offset in the current chunk
  51538. const chunkPadding = chunkOffset % info.boundary; // required padding to match boundary
  51539. const chunkStart = chunkOffset + chunkPadding; // the start position in the current chunk for the data
  51540. offset += chunkPadding;
  51541. // Check for chunk overflow
  51542. if ( chunkStart !== 0 && ( chunkSize - chunkStart ) < info.storage ) {
  51543. // Add padding and adjust offset
  51544. offset += ( chunkSize - chunkStart );
  51545. }
  51546. // the following two properties will be used for partial buffer updates
  51547. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  51548. uniform.__offset = offset;
  51549. // Update the global offset
  51550. offset += info.storage;
  51551. }
  51552. }
  51553. }
  51554. // ensure correct final padding
  51555. const chunkOffset = offset % chunkSize;
  51556. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  51557. //
  51558. uniformsGroup.__size = offset;
  51559. uniformsGroup.__cache = {};
  51560. return this;
  51561. }
  51562. function getUniformSize( value ) {
  51563. const info = {
  51564. boundary: 0, // bytes
  51565. storage: 0 // bytes
  51566. };
  51567. // determine sizes according to STD140
  51568. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  51569. // float/int/bool
  51570. info.boundary = 4;
  51571. info.storage = 4;
  51572. } else if ( value.isVector2 ) {
  51573. // vec2
  51574. info.boundary = 8;
  51575. info.storage = 8;
  51576. } else if ( value.isVector3 || value.isColor ) {
  51577. // vec3
  51578. info.boundary = 16;
  51579. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  51580. } else if ( value.isVector4 ) {
  51581. // vec4
  51582. info.boundary = 16;
  51583. info.storage = 16;
  51584. } else if ( value.isMatrix3 ) {
  51585. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  51586. info.boundary = 48;
  51587. info.storage = 48;
  51588. } else if ( value.isMatrix4 ) {
  51589. // mat4
  51590. info.boundary = 64;
  51591. info.storage = 64;
  51592. } else if ( value.isTexture ) {
  51593. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  51594. } else {
  51595. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  51596. }
  51597. return info;
  51598. }
  51599. function onUniformsGroupsDispose( event ) {
  51600. const uniformsGroup = event.target;
  51601. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  51602. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  51603. allocatedBindingPoints.splice( index, 1 );
  51604. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  51605. delete buffers[ uniformsGroup.id ];
  51606. delete updateList[ uniformsGroup.id ];
  51607. }
  51608. function dispose() {
  51609. for ( const id in buffers ) {
  51610. gl.deleteBuffer( buffers[ id ] );
  51611. }
  51612. allocatedBindingPoints = [];
  51613. buffers = {};
  51614. updateList = {};
  51615. }
  51616. return {
  51617. bind: bind,
  51618. update: update,
  51619. dispose: dispose
  51620. };
  51621. }
  51622. /**
  51623. * This renderer uses WebGL 2 to display scenes.
  51624. *
  51625. * WebGL 1 is not supported since `r163`.
  51626. */
  51627. class WebGLRenderer {
  51628. /**
  51629. * Constructs a new WebGL renderer.
  51630. *
  51631. * @param {WebGLRenderer~Options} [parameters] - The configuration parameter.
  51632. */
  51633. constructor( parameters = {} ) {
  51634. const {
  51635. canvas = createCanvasElement(),
  51636. context = null,
  51637. depth = true,
  51638. stencil = false,
  51639. alpha = false,
  51640. antialias = false,
  51641. premultipliedAlpha = true,
  51642. preserveDrawingBuffer = false,
  51643. powerPreference = 'default',
  51644. failIfMajorPerformanceCaveat = false,
  51645. reversedDepthBuffer = false,
  51646. } = parameters;
  51647. /**
  51648. * This flag can be used for type testing.
  51649. *
  51650. * @type {boolean}
  51651. * @readonly
  51652. * @default true
  51653. */
  51654. this.isWebGLRenderer = true;
  51655. let _alpha;
  51656. if ( context !== null ) {
  51657. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  51658. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  51659. }
  51660. _alpha = context.getContextAttributes().alpha;
  51661. } else {
  51662. _alpha = alpha;
  51663. }
  51664. const uintClearColor = new Uint32Array( 4 );
  51665. const intClearColor = new Int32Array( 4 );
  51666. let currentRenderList = null;
  51667. let currentRenderState = null;
  51668. // render() can be called from within a callback triggered by another render.
  51669. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  51670. const renderListStack = [];
  51671. const renderStateStack = [];
  51672. // public properties
  51673. /**
  51674. * A canvas where the renderer draws its output.This is automatically created by the renderer
  51675. * in the constructor (if not provided already); you just need to add it to your page like so:
  51676. * ```js
  51677. * document.body.appendChild( renderer.domElement );
  51678. * ```
  51679. *
  51680. * @type {DOMElement}
  51681. */
  51682. this.domElement = canvas;
  51683. /**
  51684. * A object with debug configuration settings.
  51685. *
  51686. * - `checkShaderErrors`: If it is `true`, defines whether material shader programs are
  51687. * checked for errors during compilation and linkage process. It may be useful to disable
  51688. * this check in production for performance gain. It is strongly recommended to keep these
  51689. * checks enabled during development. If the shader does not compile and link - it will not
  51690. * work and associated material will not render.
  51691. * - `onShaderError(gl, program, glVertexShader,glFragmentShader)`: A callback function that
  51692. * can be used for custom error reporting. The callback receives the WebGL context, an instance
  51693. * of WebGLProgram as well two instances of WebGLShader representing the vertex and fragment shader.
  51694. * Assigning a custom function disables the default error reporting.
  51695. *
  51696. * @type {Object}
  51697. */
  51698. this.debug = {
  51699. /**
  51700. * Enables error checking and reporting when shader programs are being compiled.
  51701. * @type {boolean}
  51702. */
  51703. checkShaderErrors: true,
  51704. /**
  51705. * Callback for custom error reporting.
  51706. * @type {?Function}
  51707. */
  51708. onShaderError: null
  51709. };
  51710. // clearing
  51711. /**
  51712. * Whether the renderer should automatically clear its output before rendering a frame or not.
  51713. *
  51714. * @type {boolean}
  51715. * @default true
  51716. */
  51717. this.autoClear = true;
  51718. /**
  51719. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  51720. * the color buffer or not.
  51721. *
  51722. * @type {boolean}
  51723. * @default true
  51724. */
  51725. this.autoClearColor = true;
  51726. /**
  51727. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  51728. * the depth buffer or not.
  51729. *
  51730. * @type {boolean}
  51731. * @default true
  51732. */
  51733. this.autoClearDepth = true;
  51734. /**
  51735. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  51736. * the stencil buffer or not.
  51737. *
  51738. * @type {boolean}
  51739. * @default true
  51740. */
  51741. this.autoClearStencil = true;
  51742. // scene graph
  51743. /**
  51744. * Whether the renderer should sort objects or not.
  51745. *
  51746. * Note: Sorting is used to attempt to properly render objects that have some
  51747. * degree of transparency. By definition, sorting objects may not work in all
  51748. * cases. Depending on the needs of application, it may be necessary to turn
  51749. * off sorting and use other methods to deal with transparency rendering e.g.
  51750. * manually determining each object's rendering order.
  51751. *
  51752. * @type {boolean}
  51753. * @default true
  51754. */
  51755. this.sortObjects = true;
  51756. // user-defined clipping
  51757. /**
  51758. * User-defined clipping planes specified in world space. These planes apply globally.
  51759. * Points in space whose dot product with the plane is negative are cut away.
  51760. *
  51761. * @type {Array<Plane>}
  51762. */
  51763. this.clippingPlanes = [];
  51764. /**
  51765. * Whether the renderer respects object-level clipping planes or not.
  51766. *
  51767. * @type {boolean}
  51768. * @default false
  51769. */
  51770. this.localClippingEnabled = false;
  51771. // tone mapping
  51772. /**
  51773. * The tone mapping technique of the renderer.
  51774. *
  51775. * @type {(NoToneMapping|LinearToneMapping|ReinhardToneMapping|CineonToneMapping|ACESFilmicToneMapping|CustomToneMapping|AgXToneMapping|NeutralToneMapping)}
  51776. * @default NoToneMapping
  51777. */
  51778. this.toneMapping = NoToneMapping;
  51779. /**
  51780. * Exposure level of tone mapping.
  51781. *
  51782. * @type {number}
  51783. * @default 1
  51784. */
  51785. this.toneMappingExposure = 1.0;
  51786. // transmission
  51787. /**
  51788. * The normalized resolution scale for the transmission render target, measured in percentage
  51789. * of viewport dimensions. Lowering this value can result in significant performance improvements
  51790. * when using {@link MeshPhysicalMaterial#transmission}.
  51791. *
  51792. * @type {number}
  51793. * @default 1
  51794. */
  51795. this.transmissionResolutionScale = 1.0;
  51796. // internal properties
  51797. const _this = this;
  51798. let _isContextLost = false;
  51799. // internal state cache
  51800. this._outputColorSpace = SRGBColorSpace;
  51801. let _currentActiveCubeFace = 0;
  51802. let _currentActiveMipmapLevel = 0;
  51803. let _currentRenderTarget = null;
  51804. let _currentMaterialId = -1;
  51805. let _currentCamera = null;
  51806. const _currentViewport = new Vector4();
  51807. const _currentScissor = new Vector4();
  51808. let _currentScissorTest = null;
  51809. const _currentClearColor = new Color( 0x000000 );
  51810. let _currentClearAlpha = 0;
  51811. //
  51812. let _width = canvas.width;
  51813. let _height = canvas.height;
  51814. let _pixelRatio = 1;
  51815. let _opaqueSort = null;
  51816. let _transparentSort = null;
  51817. const _viewport = new Vector4( 0, 0, _width, _height );
  51818. const _scissor = new Vector4( 0, 0, _width, _height );
  51819. let _scissorTest = false;
  51820. // frustum
  51821. const _frustum = new Frustum();
  51822. // clipping
  51823. let _clippingEnabled = false;
  51824. let _localClippingEnabled = false;
  51825. // camera matrices cache
  51826. const _projScreenMatrix = new Matrix4();
  51827. const _vector3 = new Vector3();
  51828. const _vector4 = new Vector4();
  51829. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  51830. let _renderBackground = false;
  51831. function getTargetPixelRatio() {
  51832. return _currentRenderTarget === null ? _pixelRatio : 1;
  51833. }
  51834. // initialize
  51835. let _gl = context;
  51836. function getContext( contextName, contextAttributes ) {
  51837. return canvas.getContext( contextName, contextAttributes );
  51838. }
  51839. try {
  51840. const contextAttributes = {
  51841. alpha: true,
  51842. depth,
  51843. stencil,
  51844. antialias,
  51845. premultipliedAlpha,
  51846. preserveDrawingBuffer,
  51847. powerPreference,
  51848. failIfMajorPerformanceCaveat,
  51849. };
  51850. // OffscreenCanvas does not have setAttribute, see #22811
  51851. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  51852. // event listeners must be registered before WebGL context is created, see #12753
  51853. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  51854. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  51855. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  51856. if ( _gl === null ) {
  51857. const contextName = 'webgl2';
  51858. _gl = getContext( contextName, contextAttributes );
  51859. if ( _gl === null ) {
  51860. if ( getContext( contextName ) ) {
  51861. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  51862. } else {
  51863. throw new Error( 'Error creating WebGL context.' );
  51864. }
  51865. }
  51866. }
  51867. } catch ( error ) {
  51868. console.error( 'THREE.WebGLRenderer: ' + error.message );
  51869. throw error;
  51870. }
  51871. let extensions, capabilities, state, info;
  51872. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  51873. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  51874. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  51875. let utils, bindingStates, uniformsGroups;
  51876. function initGLContext() {
  51877. extensions = new WebGLExtensions( _gl );
  51878. extensions.init();
  51879. utils = new WebGLUtils( _gl, extensions );
  51880. capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils );
  51881. state = new WebGLState( _gl, extensions );
  51882. if ( capabilities.reversedDepthBuffer && reversedDepthBuffer ) {
  51883. state.buffers.depth.setReversed( true );
  51884. }
  51885. info = new WebGLInfo( _gl );
  51886. properties = new WebGLProperties();
  51887. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  51888. cubemaps = new WebGLCubeMaps( _this );
  51889. cubeuvmaps = new WebGLCubeUVMaps( _this );
  51890. attributes = new WebGLAttributes( _gl );
  51891. bindingStates = new WebGLBindingStates( _gl, attributes );
  51892. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  51893. objects = new WebGLObjects( _gl, geometries, attributes, info );
  51894. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  51895. clipping = new WebGLClipping( properties );
  51896. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  51897. materials = new WebGLMaterials( _this, properties );
  51898. renderLists = new WebGLRenderLists();
  51899. renderStates = new WebGLRenderStates( extensions );
  51900. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  51901. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  51902. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  51903. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  51904. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  51905. info.programs = programCache.programs;
  51906. /**
  51907. * Holds details about the capabilities of the current rendering context.
  51908. *
  51909. * @name WebGLRenderer#capabilities
  51910. * @type {WebGLRenderer~Capabilities}
  51911. */
  51912. _this.capabilities = capabilities;
  51913. /**
  51914. * Provides methods for retrieving and testing WebGL extensions.
  51915. *
  51916. * - `get(extensionName:string)`: Used to check whether a WebGL extension is supported
  51917. * and return the extension object if available.
  51918. * - `has(extensionName:string)`: returns `true` if the extension is supported.
  51919. *
  51920. * @name WebGLRenderer#extensions
  51921. * @type {Object}
  51922. */
  51923. _this.extensions = extensions;
  51924. /**
  51925. * Used to track properties of other objects like native WebGL objects.
  51926. *
  51927. * @name WebGLRenderer#properties
  51928. * @type {Object}
  51929. */
  51930. _this.properties = properties;
  51931. /**
  51932. * Manages the render lists of the renderer.
  51933. *
  51934. * @name WebGLRenderer#renderLists
  51935. * @type {Object}
  51936. */
  51937. _this.renderLists = renderLists;
  51938. /**
  51939. * Interface for managing shadows.
  51940. *
  51941. * @name WebGLRenderer#shadowMap
  51942. * @type {WebGLRenderer~ShadowMap}
  51943. */
  51944. _this.shadowMap = shadowMap;
  51945. /**
  51946. * Interface for managing the WebGL state.
  51947. *
  51948. * @name WebGLRenderer#state
  51949. * @type {Object}
  51950. */
  51951. _this.state = state;
  51952. /**
  51953. * Holds a series of statistical information about the GPU memory
  51954. * and the rendering process. Useful for debugging and monitoring.
  51955. *
  51956. * By default these data are reset at each render call but when having
  51957. * multiple render passes per frame (e.g. when using post processing) it can
  51958. * be preferred to reset with a custom pattern. First, set `autoReset` to
  51959. * `false`.
  51960. * ```js
  51961. * renderer.info.autoReset = false;
  51962. * ```
  51963. * Call `reset()` whenever you have finished to render a single frame.
  51964. * ```js
  51965. * renderer.info.reset();
  51966. * ```
  51967. *
  51968. * @name WebGLRenderer#info
  51969. * @type {WebGLRenderer~Info}
  51970. */
  51971. _this.info = info;
  51972. }
  51973. initGLContext();
  51974. // xr
  51975. const xr = new WebXRManager( _this, _gl );
  51976. /**
  51977. * A reference to the XR manager.
  51978. *
  51979. * @type {WebXRManager}
  51980. */
  51981. this.xr = xr;
  51982. /**
  51983. * Returns the rendering context.
  51984. *
  51985. * @return {WebGL2RenderingContext} The rendering context.
  51986. */
  51987. this.getContext = function () {
  51988. return _gl;
  51989. };
  51990. /**
  51991. * Returns the rendering context attributes.
  51992. *
  51993. * @return {WebGLContextAttributes} The rendering context attributes.
  51994. */
  51995. this.getContextAttributes = function () {
  51996. return _gl.getContextAttributes();
  51997. };
  51998. /**
  51999. * Simulates a loss of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  52000. */
  52001. this.forceContextLoss = function () {
  52002. const extension = extensions.get( 'WEBGL_lose_context' );
  52003. if ( extension ) extension.loseContext();
  52004. };
  52005. /**
  52006. * Simulates a restore of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  52007. */
  52008. this.forceContextRestore = function () {
  52009. const extension = extensions.get( 'WEBGL_lose_context' );
  52010. if ( extension ) extension.restoreContext();
  52011. };
  52012. /**
  52013. * Returns the pixel ratio.
  52014. *
  52015. * @return {number} The pixel ratio.
  52016. */
  52017. this.getPixelRatio = function () {
  52018. return _pixelRatio;
  52019. };
  52020. /**
  52021. * Sets the given pixel ratio and resizes the canvas if necessary.
  52022. *
  52023. * @param {number} value - The pixel ratio.
  52024. */
  52025. this.setPixelRatio = function ( value ) {
  52026. if ( value === undefined ) return;
  52027. _pixelRatio = value;
  52028. this.setSize( _width, _height, false );
  52029. };
  52030. /**
  52031. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  52032. *
  52033. * @param {Vector2} target - The method writes the result in this target object.
  52034. * @return {Vector2} The renderer's size in logical pixels.
  52035. */
  52036. this.getSize = function ( target ) {
  52037. return target.set( _width, _height );
  52038. };
  52039. /**
  52040. * Resizes the output canvas to (width, height) with device pixel ratio taken
  52041. * into account, and also sets the viewport to fit that size, starting in (0,
  52042. * 0). Setting `updateStyle` to false prevents any style changes to the output canvas.
  52043. *
  52044. * @param {number} width - The width in logical pixels.
  52045. * @param {number} height - The height in logical pixels.
  52046. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  52047. */
  52048. this.setSize = function ( width, height, updateStyle = true ) {
  52049. if ( xr.isPresenting ) {
  52050. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  52051. return;
  52052. }
  52053. _width = width;
  52054. _height = height;
  52055. canvas.width = Math.floor( width * _pixelRatio );
  52056. canvas.height = Math.floor( height * _pixelRatio );
  52057. if ( updateStyle === true ) {
  52058. canvas.style.width = width + 'px';
  52059. canvas.style.height = height + 'px';
  52060. }
  52061. this.setViewport( 0, 0, width, height );
  52062. };
  52063. /**
  52064. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  52065. *
  52066. * @param {Vector2} target - The method writes the result in this target object.
  52067. * @return {Vector2} The drawing buffer size.
  52068. */
  52069. this.getDrawingBufferSize = function ( target ) {
  52070. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  52071. };
  52072. /**
  52073. * This method allows to define the drawing buffer size by specifying
  52074. * width, height and pixel ratio all at once. The size of the drawing
  52075. * buffer is computed with this formula:
  52076. * ```js
  52077. * size.x = width * pixelRatio;
  52078. * size.y = height * pixelRatio;
  52079. * ```
  52080. *
  52081. * @param {number} width - The width in logical pixels.
  52082. * @param {number} height - The height in logical pixels.
  52083. * @param {number} pixelRatio - The pixel ratio.
  52084. */
  52085. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  52086. _width = width;
  52087. _height = height;
  52088. _pixelRatio = pixelRatio;
  52089. canvas.width = Math.floor( width * pixelRatio );
  52090. canvas.height = Math.floor( height * pixelRatio );
  52091. this.setViewport( 0, 0, width, height );
  52092. };
  52093. /**
  52094. * Returns the current viewport definition.
  52095. *
  52096. * @param {Vector2} target - The method writes the result in this target object.
  52097. * @return {Vector2} The current viewport definition.
  52098. */
  52099. this.getCurrentViewport = function ( target ) {
  52100. return target.copy( _currentViewport );
  52101. };
  52102. /**
  52103. * Returns the viewport definition.
  52104. *
  52105. * @param {Vector4} target - The method writes the result in this target object.
  52106. * @return {Vector4} The viewport definition.
  52107. */
  52108. this.getViewport = function ( target ) {
  52109. return target.copy( _viewport );
  52110. };
  52111. /**
  52112. * Sets the viewport to render from `(x, y)` to `(x + width, y + height)`.
  52113. *
  52114. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  52115. * Or alternatively a four-component vector specifying all the parameters of the viewport.
  52116. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  52117. * @param {number} width - The width of the viewport in logical pixel unit.
  52118. * @param {number} height - The height of the viewport in logical pixel unit.
  52119. */
  52120. this.setViewport = function ( x, y, width, height ) {
  52121. if ( x.isVector4 ) {
  52122. _viewport.set( x.x, x.y, x.z, x.w );
  52123. } else {
  52124. _viewport.set( x, y, width, height );
  52125. }
  52126. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  52127. };
  52128. /**
  52129. * Returns the scissor region.
  52130. *
  52131. * @param {Vector4} target - The method writes the result in this target object.
  52132. * @return {Vector4} The scissor region.
  52133. */
  52134. this.getScissor = function ( target ) {
  52135. return target.copy( _scissor );
  52136. };
  52137. /**
  52138. * Sets the scissor region to render from `(x, y)` to `(x + width, y + height)`.
  52139. *
  52140. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  52141. * Or alternatively a four-component vector specifying all the parameters of the scissor region.
  52142. * @param {number} y - The vertical coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  52143. * @param {number} width - The width of the scissor region in logical pixel unit.
  52144. * @param {number} height - The height of the scissor region in logical pixel unit.
  52145. */
  52146. this.setScissor = function ( x, y, width, height ) {
  52147. if ( x.isVector4 ) {
  52148. _scissor.set( x.x, x.y, x.z, x.w );
  52149. } else {
  52150. _scissor.set( x, y, width, height );
  52151. }
  52152. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  52153. };
  52154. /**
  52155. * Returns `true` if the scissor test is enabled.
  52156. *
  52157. * @return {boolean} Whether the scissor test is enabled or not.
  52158. */
  52159. this.getScissorTest = function () {
  52160. return _scissorTest;
  52161. };
  52162. /**
  52163. * Enable or disable the scissor test. When this is enabled, only the pixels
  52164. * within the defined scissor area will be affected by further renderer
  52165. * actions.
  52166. *
  52167. * @param {boolean} boolean - Whether the scissor test is enabled or not.
  52168. */
  52169. this.setScissorTest = function ( boolean ) {
  52170. state.setScissorTest( _scissorTest = boolean );
  52171. };
  52172. /**
  52173. * Sets a custom opaque sort function for the render lists. Pass `null`
  52174. * to use the default `painterSortStable` function.
  52175. *
  52176. * @param {?Function} method - The opaque sort function.
  52177. */
  52178. this.setOpaqueSort = function ( method ) {
  52179. _opaqueSort = method;
  52180. };
  52181. /**
  52182. * Sets a custom transparent sort function for the render lists. Pass `null`
  52183. * to use the default `reversePainterSortStable` function.
  52184. *
  52185. * @param {?Function} method - The opaque sort function.
  52186. */
  52187. this.setTransparentSort = function ( method ) {
  52188. _transparentSort = method;
  52189. };
  52190. // Clearing
  52191. /**
  52192. * Returns the clear color.
  52193. *
  52194. * @param {Color} target - The method writes the result in this target object.
  52195. * @return {Color} The clear color.
  52196. */
  52197. this.getClearColor = function ( target ) {
  52198. return target.copy( background.getClearColor() );
  52199. };
  52200. /**
  52201. * Sets the clear color and alpha.
  52202. *
  52203. * @param {Color} color - The clear color.
  52204. * @param {number} [alpha=1] - The clear alpha.
  52205. */
  52206. this.setClearColor = function () {
  52207. background.setClearColor( ...arguments );
  52208. };
  52209. /**
  52210. * Returns the clear alpha. Ranges within `[0,1]`.
  52211. *
  52212. * @return {number} The clear alpha.
  52213. */
  52214. this.getClearAlpha = function () {
  52215. return background.getClearAlpha();
  52216. };
  52217. /**
  52218. * Sets the clear alpha.
  52219. *
  52220. * @param {number} alpha - The clear alpha.
  52221. */
  52222. this.setClearAlpha = function () {
  52223. background.setClearAlpha( ...arguments );
  52224. };
  52225. /**
  52226. * Tells the renderer to clear its color, depth or stencil drawing buffer(s).
  52227. * This method initializes the buffers to the current clear color values.
  52228. *
  52229. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  52230. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  52231. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  52232. */
  52233. this.clear = function ( color = true, depth = true, stencil = true ) {
  52234. let bits = 0;
  52235. if ( color ) {
  52236. // check if we're trying to clear an integer target
  52237. let isIntegerFormat = false;
  52238. if ( _currentRenderTarget !== null ) {
  52239. const targetFormat = _currentRenderTarget.texture.format;
  52240. isIntegerFormat = targetFormat === RGBAIntegerFormat ||
  52241. targetFormat === RGIntegerFormat ||
  52242. targetFormat === RedIntegerFormat;
  52243. }
  52244. // use the appropriate clear functions to clear the target if it's a signed
  52245. // or unsigned integer target
  52246. if ( isIntegerFormat ) {
  52247. const targetType = _currentRenderTarget.texture.type;
  52248. const isUnsignedType = targetType === UnsignedByteType ||
  52249. targetType === UnsignedIntType ||
  52250. targetType === UnsignedShortType ||
  52251. targetType === UnsignedInt248Type ||
  52252. targetType === UnsignedShort4444Type ||
  52253. targetType === UnsignedShort5551Type;
  52254. const clearColor = background.getClearColor();
  52255. const a = background.getClearAlpha();
  52256. const r = clearColor.r;
  52257. const g = clearColor.g;
  52258. const b = clearColor.b;
  52259. if ( isUnsignedType ) {
  52260. uintClearColor[ 0 ] = r;
  52261. uintClearColor[ 1 ] = g;
  52262. uintClearColor[ 2 ] = b;
  52263. uintClearColor[ 3 ] = a;
  52264. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  52265. } else {
  52266. intClearColor[ 0 ] = r;
  52267. intClearColor[ 1 ] = g;
  52268. intClearColor[ 2 ] = b;
  52269. intClearColor[ 3 ] = a;
  52270. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  52271. }
  52272. } else {
  52273. bits |= _gl.COLOR_BUFFER_BIT;
  52274. }
  52275. }
  52276. if ( depth ) {
  52277. bits |= _gl.DEPTH_BUFFER_BIT;
  52278. }
  52279. if ( stencil ) {
  52280. bits |= _gl.STENCIL_BUFFER_BIT;
  52281. this.state.buffers.stencil.setMask( 0xffffffff );
  52282. }
  52283. _gl.clear( bits );
  52284. };
  52285. /**
  52286. * Clears the color buffer. Equivalent to calling `renderer.clear( true, false, false )`.
  52287. */
  52288. this.clearColor = function () {
  52289. this.clear( true, false, false );
  52290. };
  52291. /**
  52292. * Clears the depth buffer. Equivalent to calling `renderer.clear( false, true, false )`.
  52293. */
  52294. this.clearDepth = function () {
  52295. this.clear( false, true, false );
  52296. };
  52297. /**
  52298. * Clears the stencil buffer. Equivalent to calling `renderer.clear( false, false, true )`.
  52299. */
  52300. this.clearStencil = function () {
  52301. this.clear( false, false, true );
  52302. };
  52303. /**
  52304. * Frees the GPU-related resources allocated by this instance. Call this
  52305. * method whenever this instance is no longer used in your app.
  52306. */
  52307. this.dispose = function () {
  52308. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  52309. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  52310. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  52311. background.dispose();
  52312. renderLists.dispose();
  52313. renderStates.dispose();
  52314. properties.dispose();
  52315. cubemaps.dispose();
  52316. cubeuvmaps.dispose();
  52317. objects.dispose();
  52318. bindingStates.dispose();
  52319. uniformsGroups.dispose();
  52320. programCache.dispose();
  52321. xr.dispose();
  52322. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  52323. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  52324. animation.stop();
  52325. };
  52326. // Events
  52327. function onContextLost( event ) {
  52328. event.preventDefault();
  52329. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  52330. _isContextLost = true;
  52331. }
  52332. function onContextRestore( /* event */ ) {
  52333. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  52334. _isContextLost = false;
  52335. const infoAutoReset = info.autoReset;
  52336. const shadowMapEnabled = shadowMap.enabled;
  52337. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  52338. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  52339. const shadowMapType = shadowMap.type;
  52340. initGLContext();
  52341. info.autoReset = infoAutoReset;
  52342. shadowMap.enabled = shadowMapEnabled;
  52343. shadowMap.autoUpdate = shadowMapAutoUpdate;
  52344. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  52345. shadowMap.type = shadowMapType;
  52346. }
  52347. function onContextCreationError( event ) {
  52348. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  52349. }
  52350. function onMaterialDispose( event ) {
  52351. const material = event.target;
  52352. material.removeEventListener( 'dispose', onMaterialDispose );
  52353. deallocateMaterial( material );
  52354. }
  52355. // Buffer deallocation
  52356. function deallocateMaterial( material ) {
  52357. releaseMaterialProgramReferences( material );
  52358. properties.remove( material );
  52359. }
  52360. function releaseMaterialProgramReferences( material ) {
  52361. const programs = properties.get( material ).programs;
  52362. if ( programs !== undefined ) {
  52363. programs.forEach( function ( program ) {
  52364. programCache.releaseProgram( program );
  52365. } );
  52366. if ( material.isShaderMaterial ) {
  52367. programCache.releaseShaderCache( material );
  52368. }
  52369. }
  52370. }
  52371. // Buffer rendering
  52372. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  52373. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  52374. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  52375. const program = setProgram( camera, scene, geometry, material, object );
  52376. state.setMaterial( material, frontFaceCW );
  52377. //
  52378. let index = geometry.index;
  52379. let rangeFactor = 1;
  52380. if ( material.wireframe === true ) {
  52381. index = geometries.getWireframeAttribute( geometry );
  52382. if ( index === undefined ) return;
  52383. rangeFactor = 2;
  52384. }
  52385. //
  52386. const drawRange = geometry.drawRange;
  52387. const position = geometry.attributes.position;
  52388. let drawStart = drawRange.start * rangeFactor;
  52389. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  52390. if ( group !== null ) {
  52391. drawStart = Math.max( drawStart, group.start * rangeFactor );
  52392. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  52393. }
  52394. if ( index !== null ) {
  52395. drawStart = Math.max( drawStart, 0 );
  52396. drawEnd = Math.min( drawEnd, index.count );
  52397. } else if ( position !== undefined && position !== null ) {
  52398. drawStart = Math.max( drawStart, 0 );
  52399. drawEnd = Math.min( drawEnd, position.count );
  52400. }
  52401. const drawCount = drawEnd - drawStart;
  52402. if ( drawCount < 0 || drawCount === Infinity ) return;
  52403. //
  52404. bindingStates.setup( object, material, program, geometry, index );
  52405. let attribute;
  52406. let renderer = bufferRenderer;
  52407. if ( index !== null ) {
  52408. attribute = attributes.get( index );
  52409. renderer = indexedBufferRenderer;
  52410. renderer.setIndex( attribute );
  52411. }
  52412. //
  52413. if ( object.isMesh ) {
  52414. if ( material.wireframe === true ) {
  52415. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  52416. renderer.setMode( _gl.LINES );
  52417. } else {
  52418. renderer.setMode( _gl.TRIANGLES );
  52419. }
  52420. } else if ( object.isLine ) {
  52421. let lineWidth = material.linewidth;
  52422. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  52423. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  52424. if ( object.isLineSegments ) {
  52425. renderer.setMode( _gl.LINES );
  52426. } else if ( object.isLineLoop ) {
  52427. renderer.setMode( _gl.LINE_LOOP );
  52428. } else {
  52429. renderer.setMode( _gl.LINE_STRIP );
  52430. }
  52431. } else if ( object.isPoints ) {
  52432. renderer.setMode( _gl.POINTS );
  52433. } else if ( object.isSprite ) {
  52434. renderer.setMode( _gl.TRIANGLES );
  52435. }
  52436. if ( object.isBatchedMesh ) {
  52437. if ( object._multiDrawInstances !== null ) {
  52438. // @deprecated, r174
  52439. warnOnce( 'THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  52440. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  52441. } else {
  52442. if ( ! extensions.get( 'WEBGL_multi_draw' ) ) {
  52443. const starts = object._multiDrawStarts;
  52444. const counts = object._multiDrawCounts;
  52445. const drawCount = object._multiDrawCount;
  52446. const bytesPerElement = index ? attributes.get( index ).bytesPerElement : 1;
  52447. const uniforms = properties.get( material ).currentProgram.getUniforms();
  52448. for ( let i = 0; i < drawCount; i ++ ) {
  52449. uniforms.setValue( _gl, '_gl_DrawID', i );
  52450. renderer.render( starts[ i ] / bytesPerElement, counts[ i ] );
  52451. }
  52452. } else {
  52453. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  52454. }
  52455. }
  52456. } else if ( object.isInstancedMesh ) {
  52457. renderer.renderInstances( drawStart, drawCount, object.count );
  52458. } else if ( geometry.isInstancedBufferGeometry ) {
  52459. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  52460. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  52461. renderer.renderInstances( drawStart, drawCount, instanceCount );
  52462. } else {
  52463. renderer.render( drawStart, drawCount );
  52464. }
  52465. };
  52466. // Compile
  52467. function prepareMaterial( material, scene, object ) {
  52468. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  52469. material.side = BackSide;
  52470. material.needsUpdate = true;
  52471. getProgram( material, scene, object );
  52472. material.side = FrontSide;
  52473. material.needsUpdate = true;
  52474. getProgram( material, scene, object );
  52475. material.side = DoubleSide;
  52476. } else {
  52477. getProgram( material, scene, object );
  52478. }
  52479. }
  52480. /**
  52481. * Compiles all materials in the scene with the camera. This is useful to precompile shaders
  52482. * before the first rendering. If you want to add a 3D object to an existing scene, use the third
  52483. * optional parameter for applying the target scene.
  52484. *
  52485. * Note that the (target) scene's lighting and environment must be configured before calling this method.
  52486. *
  52487. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  52488. * @param {Camera} camera - The camera.
  52489. * @param {?Scene} [targetScene=null] - The target scene.
  52490. * @return {Set<Material>} The precompiled materials.
  52491. */
  52492. this.compile = function ( scene, camera, targetScene = null ) {
  52493. if ( targetScene === null ) targetScene = scene;
  52494. currentRenderState = renderStates.get( targetScene );
  52495. currentRenderState.init( camera );
  52496. renderStateStack.push( currentRenderState );
  52497. // gather lights from both the target scene and the new object that will be added to the scene.
  52498. targetScene.traverseVisible( function ( object ) {
  52499. if ( object.isLight && object.layers.test( camera.layers ) ) {
  52500. currentRenderState.pushLight( object );
  52501. if ( object.castShadow ) {
  52502. currentRenderState.pushShadow( object );
  52503. }
  52504. }
  52505. } );
  52506. if ( scene !== targetScene ) {
  52507. scene.traverseVisible( function ( object ) {
  52508. if ( object.isLight && object.layers.test( camera.layers ) ) {
  52509. currentRenderState.pushLight( object );
  52510. if ( object.castShadow ) {
  52511. currentRenderState.pushShadow( object );
  52512. }
  52513. }
  52514. } );
  52515. }
  52516. currentRenderState.setupLights();
  52517. // Only initialize materials in the new scene, not the targetScene.
  52518. const materials = new Set();
  52519. scene.traverse( function ( object ) {
  52520. if ( ! ( object.isMesh || object.isPoints || object.isLine || object.isSprite ) ) {
  52521. return;
  52522. }
  52523. const material = object.material;
  52524. if ( material ) {
  52525. if ( Array.isArray( material ) ) {
  52526. for ( let i = 0; i < material.length; i ++ ) {
  52527. const material2 = material[ i ];
  52528. prepareMaterial( material2, targetScene, object );
  52529. materials.add( material2 );
  52530. }
  52531. } else {
  52532. prepareMaterial( material, targetScene, object );
  52533. materials.add( material );
  52534. }
  52535. }
  52536. } );
  52537. currentRenderState = renderStateStack.pop();
  52538. return materials;
  52539. };
  52540. // compileAsync
  52541. /**
  52542. * Asynchronous version of {@link WebGLRenderer#compile}.
  52543. *
  52544. * This method makes use of the `KHR_parallel_shader_compile` WebGL extension. Hence,
  52545. * it is recommended to use this version of `compile()` whenever possible.
  52546. *
  52547. * @async
  52548. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  52549. * @param {Camera} camera - The camera.
  52550. * @param {?Scene} [targetScene=null] - The target scene.
  52551. * @return {Promise} A Promise that resolves when the given scene can be rendered without unnecessary stalling due to shader compilation.
  52552. */
  52553. this.compileAsync = function ( scene, camera, targetScene = null ) {
  52554. const materials = this.compile( scene, camera, targetScene );
  52555. // Wait for all the materials in the new object to indicate that they're
  52556. // ready to be used before resolving the promise.
  52557. return new Promise( ( resolve ) => {
  52558. function checkMaterialsReady() {
  52559. materials.forEach( function ( material ) {
  52560. const materialProperties = properties.get( material );
  52561. const program = materialProperties.currentProgram;
  52562. if ( program.isReady() ) {
  52563. // remove any programs that report they're ready to use from the list
  52564. materials.delete( material );
  52565. }
  52566. } );
  52567. // once the list of compiling materials is empty, call the callback
  52568. if ( materials.size === 0 ) {
  52569. resolve( scene );
  52570. return;
  52571. }
  52572. // if some materials are still not ready, wait a bit and check again
  52573. setTimeout( checkMaterialsReady, 10 );
  52574. }
  52575. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  52576. // If we can check the compilation status of the materials without
  52577. // blocking then do so right away.
  52578. checkMaterialsReady();
  52579. } else {
  52580. // Otherwise start by waiting a bit to give the materials we just
  52581. // initialized a chance to finish.
  52582. setTimeout( checkMaterialsReady, 10 );
  52583. }
  52584. } );
  52585. };
  52586. // Animation Loop
  52587. let onAnimationFrameCallback = null;
  52588. function onAnimationFrame( time ) {
  52589. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  52590. }
  52591. function onXRSessionStart() {
  52592. animation.stop();
  52593. }
  52594. function onXRSessionEnd() {
  52595. animation.start();
  52596. }
  52597. const animation = new WebGLAnimation();
  52598. animation.setAnimationLoop( onAnimationFrame );
  52599. if ( typeof self !== 'undefined' ) animation.setContext( self );
  52600. this.setAnimationLoop = function ( callback ) {
  52601. onAnimationFrameCallback = callback;
  52602. xr.setAnimationLoop( callback );
  52603. ( callback === null ) ? animation.stop() : animation.start();
  52604. };
  52605. xr.addEventListener( 'sessionstart', onXRSessionStart );
  52606. xr.addEventListener( 'sessionend', onXRSessionEnd );
  52607. // Rendering
  52608. /**
  52609. * Renders the given scene (or other type of 3D object) using the given camera.
  52610. *
  52611. * The render is done to a previously specified render target set by calling {@link WebGLRenderer#setRenderTarget}
  52612. * or to the canvas as usual.
  52613. *
  52614. * By default render buffers are cleared before rendering but you can prevent
  52615. * this by setting the property `autoClear` to `false`. If you want to prevent
  52616. * only certain buffers being cleared you can `autoClearColor`, `autoClearDepth`
  52617. * or `autoClearStencil` to `false`. To force a clear, use {@link WebGLRenderer#clear}.
  52618. *
  52619. * @param {Object3D} scene - The scene to render.
  52620. * @param {Camera} camera - The camera.
  52621. */
  52622. this.render = function ( scene, camera ) {
  52623. if ( camera !== undefined && camera.isCamera !== true ) {
  52624. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  52625. return;
  52626. }
  52627. if ( _isContextLost === true ) return;
  52628. // update scene graph
  52629. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  52630. // update camera matrices and frustum
  52631. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  52632. if ( xr.enabled === true && xr.isPresenting === true ) {
  52633. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  52634. camera = xr.getCamera(); // use XR camera for rendering
  52635. }
  52636. //
  52637. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  52638. currentRenderState = renderStates.get( scene, renderStateStack.length );
  52639. currentRenderState.init( camera );
  52640. renderStateStack.push( currentRenderState );
  52641. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  52642. _frustum.setFromProjectionMatrix( _projScreenMatrix, WebGLCoordinateSystem, camera.reversedDepth );
  52643. _localClippingEnabled = this.localClippingEnabled;
  52644. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  52645. currentRenderList = renderLists.get( scene, renderListStack.length );
  52646. currentRenderList.init();
  52647. renderListStack.push( currentRenderList );
  52648. if ( xr.enabled === true && xr.isPresenting === true ) {
  52649. const depthSensingMesh = _this.xr.getDepthSensingMesh();
  52650. if ( depthSensingMesh !== null ) {
  52651. projectObject( depthSensingMesh, camera, - Infinity, _this.sortObjects );
  52652. }
  52653. }
  52654. projectObject( scene, camera, 0, _this.sortObjects );
  52655. currentRenderList.finish();
  52656. if ( _this.sortObjects === true ) {
  52657. currentRenderList.sort( _opaqueSort, _transparentSort );
  52658. }
  52659. _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  52660. if ( _renderBackground ) {
  52661. background.addToRenderList( currentRenderList, scene );
  52662. }
  52663. //
  52664. this.info.render.frame ++;
  52665. if ( _clippingEnabled === true ) clipping.beginShadows();
  52666. const shadowsArray = currentRenderState.state.shadowsArray;
  52667. shadowMap.render( shadowsArray, scene, camera );
  52668. if ( _clippingEnabled === true ) clipping.endShadows();
  52669. //
  52670. if ( this.info.autoReset === true ) this.info.reset();
  52671. // render scene
  52672. const opaqueObjects = currentRenderList.opaque;
  52673. const transmissiveObjects = currentRenderList.transmissive;
  52674. currentRenderState.setupLights();
  52675. if ( camera.isArrayCamera ) {
  52676. const cameras = camera.cameras;
  52677. if ( transmissiveObjects.length > 0 ) {
  52678. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  52679. const camera2 = cameras[ i ];
  52680. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  52681. }
  52682. }
  52683. if ( _renderBackground ) background.render( scene );
  52684. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  52685. const camera2 = cameras[ i ];
  52686. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  52687. }
  52688. } else {
  52689. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  52690. if ( _renderBackground ) background.render( scene );
  52691. renderScene( currentRenderList, scene, camera );
  52692. }
  52693. //
  52694. if ( _currentRenderTarget !== null && _currentActiveMipmapLevel === 0 ) {
  52695. // resolve multisample renderbuffers to a single-sample texture if necessary
  52696. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  52697. // Generate mipmap if we're using any kind of mipmap filtering
  52698. textures.updateRenderTargetMipmap( _currentRenderTarget );
  52699. }
  52700. //
  52701. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  52702. // _gl.finish();
  52703. bindingStates.resetDefaultState();
  52704. _currentMaterialId = -1;
  52705. _currentCamera = null;
  52706. renderStateStack.pop();
  52707. if ( renderStateStack.length > 0 ) {
  52708. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  52709. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  52710. } else {
  52711. currentRenderState = null;
  52712. }
  52713. renderListStack.pop();
  52714. if ( renderListStack.length > 0 ) {
  52715. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  52716. } else {
  52717. currentRenderList = null;
  52718. }
  52719. };
  52720. function projectObject( object, camera, groupOrder, sortObjects ) {
  52721. if ( object.visible === false ) return;
  52722. const visible = object.layers.test( camera.layers );
  52723. if ( visible ) {
  52724. if ( object.isGroup ) {
  52725. groupOrder = object.renderOrder;
  52726. } else if ( object.isLOD ) {
  52727. if ( object.autoUpdate === true ) object.update( camera );
  52728. } else if ( object.isLight ) {
  52729. currentRenderState.pushLight( object );
  52730. if ( object.castShadow ) {
  52731. currentRenderState.pushShadow( object );
  52732. }
  52733. } else if ( object.isSprite ) {
  52734. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  52735. if ( sortObjects ) {
  52736. _vector4.setFromMatrixPosition( object.matrixWorld )
  52737. .applyMatrix4( _projScreenMatrix );
  52738. }
  52739. const geometry = objects.update( object );
  52740. const material = object.material;
  52741. if ( material.visible ) {
  52742. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  52743. }
  52744. }
  52745. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  52746. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  52747. const geometry = objects.update( object );
  52748. const material = object.material;
  52749. if ( sortObjects ) {
  52750. if ( object.boundingSphere !== undefined ) {
  52751. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  52752. _vector4.copy( object.boundingSphere.center );
  52753. } else {
  52754. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  52755. _vector4.copy( geometry.boundingSphere.center );
  52756. }
  52757. _vector4
  52758. .applyMatrix4( object.matrixWorld )
  52759. .applyMatrix4( _projScreenMatrix );
  52760. }
  52761. if ( Array.isArray( material ) ) {
  52762. const groups = geometry.groups;
  52763. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  52764. const group = groups[ i ];
  52765. const groupMaterial = material[ group.materialIndex ];
  52766. if ( groupMaterial && groupMaterial.visible ) {
  52767. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  52768. }
  52769. }
  52770. } else if ( material.visible ) {
  52771. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  52772. }
  52773. }
  52774. }
  52775. }
  52776. const children = object.children;
  52777. for ( let i = 0, l = children.length; i < l; i ++ ) {
  52778. projectObject( children[ i ], camera, groupOrder, sortObjects );
  52779. }
  52780. }
  52781. function renderScene( currentRenderList, scene, camera, viewport ) {
  52782. const opaqueObjects = currentRenderList.opaque;
  52783. const transmissiveObjects = currentRenderList.transmissive;
  52784. const transparentObjects = currentRenderList.transparent;
  52785. currentRenderState.setupLightsView( camera );
  52786. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  52787. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  52788. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  52789. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  52790. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  52791. // Ensure depth buffer writing is enabled so it can be cleared on next render
  52792. state.buffers.depth.setTest( true );
  52793. state.buffers.depth.setMask( true );
  52794. state.buffers.color.setMask( true );
  52795. state.setPolygonOffset( false );
  52796. }
  52797. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  52798. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  52799. if ( overrideMaterial !== null ) {
  52800. return;
  52801. }
  52802. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  52803. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  52804. generateMipmaps: true,
  52805. type: ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) ) ? HalfFloatType : UnsignedByteType,
  52806. minFilter: LinearMipmapLinearFilter,
  52807. samples: 4,
  52808. stencilBuffer: stencil,
  52809. resolveDepthBuffer: false,
  52810. resolveStencilBuffer: false,
  52811. colorSpace: ColorManagement.workingColorSpace,
  52812. } );
  52813. // debug
  52814. /*
  52815. const geometry = new PlaneGeometry();
  52816. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  52817. const mesh = new Mesh( geometry, material );
  52818. scene.add( mesh );
  52819. */
  52820. }
  52821. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  52822. const activeViewport = camera.viewport || _currentViewport;
  52823. transmissionRenderTarget.setSize( activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale );
  52824. //
  52825. const currentRenderTarget = _this.getRenderTarget();
  52826. const currentActiveCubeFace = _this.getActiveCubeFace();
  52827. const currentActiveMipmapLevel = _this.getActiveMipmapLevel();
  52828. _this.setRenderTarget( transmissionRenderTarget );
  52829. _this.getClearColor( _currentClearColor );
  52830. _currentClearAlpha = _this.getClearAlpha();
  52831. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  52832. _this.clear();
  52833. if ( _renderBackground ) background.render( scene );
  52834. // Turn off the features which can affect the frag color for opaque objects pass.
  52835. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  52836. const currentToneMapping = _this.toneMapping;
  52837. _this.toneMapping = NoToneMapping;
  52838. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  52839. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  52840. const currentCameraViewport = camera.viewport;
  52841. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  52842. currentRenderState.setupLightsView( camera );
  52843. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  52844. renderObjects( opaqueObjects, scene, camera );
  52845. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  52846. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  52847. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  52848. let renderTargetNeedsUpdate = false;
  52849. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  52850. const renderItem = transmissiveObjects[ i ];
  52851. const object = renderItem.object;
  52852. const geometry = renderItem.geometry;
  52853. const material = renderItem.material;
  52854. const group = renderItem.group;
  52855. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  52856. const currentSide = material.side;
  52857. material.side = BackSide;
  52858. material.needsUpdate = true;
  52859. renderObject( object, scene, camera, geometry, material, group );
  52860. material.side = currentSide;
  52861. material.needsUpdate = true;
  52862. renderTargetNeedsUpdate = true;
  52863. }
  52864. }
  52865. if ( renderTargetNeedsUpdate === true ) {
  52866. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  52867. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  52868. }
  52869. }
  52870. _this.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  52871. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  52872. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  52873. _this.toneMapping = currentToneMapping;
  52874. }
  52875. function renderObjects( renderList, scene, camera ) {
  52876. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  52877. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  52878. const renderItem = renderList[ i ];
  52879. const object = renderItem.object;
  52880. const geometry = renderItem.geometry;
  52881. const group = renderItem.group;
  52882. let material = renderItem.material;
  52883. if ( material.allowOverride === true && overrideMaterial !== null ) {
  52884. material = overrideMaterial;
  52885. }
  52886. if ( object.layers.test( camera.layers ) ) {
  52887. renderObject( object, scene, camera, geometry, material, group );
  52888. }
  52889. }
  52890. }
  52891. function renderObject( object, scene, camera, geometry, material, group ) {
  52892. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  52893. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  52894. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  52895. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  52896. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  52897. material.side = BackSide;
  52898. material.needsUpdate = true;
  52899. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  52900. material.side = FrontSide;
  52901. material.needsUpdate = true;
  52902. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  52903. material.side = DoubleSide;
  52904. } else {
  52905. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  52906. }
  52907. object.onAfterRender( _this, scene, camera, geometry, material, group );
  52908. }
  52909. function getProgram( material, scene, object ) {
  52910. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  52911. const materialProperties = properties.get( material );
  52912. const lights = currentRenderState.state.lights;
  52913. const shadowsArray = currentRenderState.state.shadowsArray;
  52914. const lightsStateVersion = lights.state.version;
  52915. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  52916. const programCacheKey = programCache.getProgramCacheKey( parameters );
  52917. let programs = materialProperties.programs;
  52918. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  52919. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  52920. materialProperties.fog = scene.fog;
  52921. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  52922. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  52923. if ( programs === undefined ) {
  52924. // new material
  52925. material.addEventListener( 'dispose', onMaterialDispose );
  52926. programs = new Map();
  52927. materialProperties.programs = programs;
  52928. }
  52929. let program = programs.get( programCacheKey );
  52930. if ( program !== undefined ) {
  52931. // early out if program and light state is identical
  52932. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  52933. updateCommonMaterialProperties( material, parameters );
  52934. return program;
  52935. }
  52936. } else {
  52937. parameters.uniforms = programCache.getUniforms( material );
  52938. material.onBeforeCompile( parameters, _this );
  52939. program = programCache.acquireProgram( parameters, programCacheKey );
  52940. programs.set( programCacheKey, program );
  52941. materialProperties.uniforms = parameters.uniforms;
  52942. }
  52943. const uniforms = materialProperties.uniforms;
  52944. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  52945. uniforms.clippingPlanes = clipping.uniform;
  52946. }
  52947. updateCommonMaterialProperties( material, parameters );
  52948. // store the light setup it was created for
  52949. materialProperties.needsLights = materialNeedsLights( material );
  52950. materialProperties.lightsStateVersion = lightsStateVersion;
  52951. if ( materialProperties.needsLights ) {
  52952. // wire up the material to this renderer's lighting state
  52953. uniforms.ambientLightColor.value = lights.state.ambient;
  52954. uniforms.lightProbe.value = lights.state.probe;
  52955. uniforms.directionalLights.value = lights.state.directional;
  52956. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  52957. uniforms.spotLights.value = lights.state.spot;
  52958. uniforms.spotLightShadows.value = lights.state.spotShadow;
  52959. uniforms.rectAreaLights.value = lights.state.rectArea;
  52960. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  52961. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  52962. uniforms.pointLights.value = lights.state.point;
  52963. uniforms.pointLightShadows.value = lights.state.pointShadow;
  52964. uniforms.hemisphereLights.value = lights.state.hemi;
  52965. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  52966. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  52967. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  52968. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  52969. uniforms.spotLightMap.value = lights.state.spotLightMap;
  52970. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  52971. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  52972. // TODO (abelnation): add area lights shadow info to uniforms
  52973. }
  52974. materialProperties.currentProgram = program;
  52975. materialProperties.uniformsList = null;
  52976. return program;
  52977. }
  52978. function getUniformList( materialProperties ) {
  52979. if ( materialProperties.uniformsList === null ) {
  52980. const progUniforms = materialProperties.currentProgram.getUniforms();
  52981. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  52982. }
  52983. return materialProperties.uniformsList;
  52984. }
  52985. function updateCommonMaterialProperties( material, parameters ) {
  52986. const materialProperties = properties.get( material );
  52987. materialProperties.outputColorSpace = parameters.outputColorSpace;
  52988. materialProperties.batching = parameters.batching;
  52989. materialProperties.batchingColor = parameters.batchingColor;
  52990. materialProperties.instancing = parameters.instancing;
  52991. materialProperties.instancingColor = parameters.instancingColor;
  52992. materialProperties.instancingMorph = parameters.instancingMorph;
  52993. materialProperties.skinning = parameters.skinning;
  52994. materialProperties.morphTargets = parameters.morphTargets;
  52995. materialProperties.morphNormals = parameters.morphNormals;
  52996. materialProperties.morphColors = parameters.morphColors;
  52997. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  52998. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  52999. materialProperties.numIntersection = parameters.numClipIntersection;
  53000. materialProperties.vertexAlphas = parameters.vertexAlphas;
  53001. materialProperties.vertexTangents = parameters.vertexTangents;
  53002. materialProperties.toneMapping = parameters.toneMapping;
  53003. }
  53004. function setProgram( camera, scene, geometry, material, object ) {
  53005. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  53006. textures.resetTextureUnits();
  53007. const fog = scene.fog;
  53008. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  53009. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  53010. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  53011. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  53012. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  53013. const morphTargets = !! geometry.morphAttributes.position;
  53014. const morphNormals = !! geometry.morphAttributes.normal;
  53015. const morphColors = !! geometry.morphAttributes.color;
  53016. let toneMapping = NoToneMapping;
  53017. if ( material.toneMapped ) {
  53018. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  53019. toneMapping = _this.toneMapping;
  53020. }
  53021. }
  53022. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  53023. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  53024. const materialProperties = properties.get( material );
  53025. const lights = currentRenderState.state.lights;
  53026. if ( _clippingEnabled === true ) {
  53027. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  53028. const useCache =
  53029. camera === _currentCamera &&
  53030. material.id === _currentMaterialId;
  53031. // we might want to call this function with some ClippingGroup
  53032. // object instead of the material, once it becomes feasible
  53033. // (#8465, #8379)
  53034. clipping.setState( material, camera, useCache );
  53035. }
  53036. }
  53037. //
  53038. let needsProgramChange = false;
  53039. if ( material.version === materialProperties.__version ) {
  53040. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  53041. needsProgramChange = true;
  53042. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  53043. needsProgramChange = true;
  53044. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  53045. needsProgramChange = true;
  53046. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  53047. needsProgramChange = true;
  53048. } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null ) {
  53049. needsProgramChange = true;
  53050. } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null ) {
  53051. needsProgramChange = true;
  53052. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  53053. needsProgramChange = true;
  53054. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  53055. needsProgramChange = true;
  53056. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  53057. needsProgramChange = true;
  53058. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  53059. needsProgramChange = true;
  53060. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  53061. needsProgramChange = true;
  53062. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  53063. needsProgramChange = true;
  53064. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  53065. needsProgramChange = true;
  53066. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  53067. needsProgramChange = true;
  53068. } else if ( materialProperties.envMap !== envMap ) {
  53069. needsProgramChange = true;
  53070. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  53071. needsProgramChange = true;
  53072. } else if ( materialProperties.numClippingPlanes !== undefined &&
  53073. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  53074. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  53075. needsProgramChange = true;
  53076. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  53077. needsProgramChange = true;
  53078. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  53079. needsProgramChange = true;
  53080. } else if ( materialProperties.morphTargets !== morphTargets ) {
  53081. needsProgramChange = true;
  53082. } else if ( materialProperties.morphNormals !== morphNormals ) {
  53083. needsProgramChange = true;
  53084. } else if ( materialProperties.morphColors !== morphColors ) {
  53085. needsProgramChange = true;
  53086. } else if ( materialProperties.toneMapping !== toneMapping ) {
  53087. needsProgramChange = true;
  53088. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  53089. needsProgramChange = true;
  53090. }
  53091. } else {
  53092. needsProgramChange = true;
  53093. materialProperties.__version = material.version;
  53094. }
  53095. //
  53096. let program = materialProperties.currentProgram;
  53097. if ( needsProgramChange === true ) {
  53098. program = getProgram( material, scene, object );
  53099. }
  53100. let refreshProgram = false;
  53101. let refreshMaterial = false;
  53102. let refreshLights = false;
  53103. const p_uniforms = program.getUniforms(),
  53104. m_uniforms = materialProperties.uniforms;
  53105. if ( state.useProgram( program.program ) ) {
  53106. refreshProgram = true;
  53107. refreshMaterial = true;
  53108. refreshLights = true;
  53109. }
  53110. if ( material.id !== _currentMaterialId ) {
  53111. _currentMaterialId = material.id;
  53112. refreshMaterial = true;
  53113. }
  53114. if ( refreshProgram || _currentCamera !== camera ) {
  53115. // common camera uniforms
  53116. const reversedDepthBuffer = state.buffers.depth.getReversed();
  53117. if ( reversedDepthBuffer && camera.reversedDepth !== true ) {
  53118. camera._reversedDepth = true;
  53119. camera.updateProjectionMatrix();
  53120. }
  53121. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  53122. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  53123. const uCamPos = p_uniforms.map.cameraPosition;
  53124. if ( uCamPos !== undefined ) {
  53125. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  53126. }
  53127. if ( capabilities.logarithmicDepthBuffer ) {
  53128. p_uniforms.setValue( _gl, 'logDepthBufFC',
  53129. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  53130. }
  53131. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  53132. if ( material.isMeshPhongMaterial ||
  53133. material.isMeshToonMaterial ||
  53134. material.isMeshLambertMaterial ||
  53135. material.isMeshBasicMaterial ||
  53136. material.isMeshStandardMaterial ||
  53137. material.isShaderMaterial ) {
  53138. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  53139. }
  53140. if ( _currentCamera !== camera ) {
  53141. _currentCamera = camera;
  53142. // lighting uniforms depend on the camera so enforce an update
  53143. // now, in case this material supports lights - or later, when
  53144. // the next material that does gets activated:
  53145. refreshMaterial = true; // set to true on material change
  53146. refreshLights = true; // remains set until update done
  53147. }
  53148. }
  53149. // skinning and morph target uniforms must be set even if material didn't change
  53150. // auto-setting of texture unit for bone and morph texture must go before other textures
  53151. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  53152. if ( object.isSkinnedMesh ) {
  53153. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  53154. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  53155. const skeleton = object.skeleton;
  53156. if ( skeleton ) {
  53157. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  53158. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  53159. }
  53160. }
  53161. if ( object.isBatchedMesh ) {
  53162. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  53163. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  53164. p_uniforms.setOptional( _gl, object, 'batchingIdTexture' );
  53165. p_uniforms.setValue( _gl, 'batchingIdTexture', object._indirectTexture, textures );
  53166. p_uniforms.setOptional( _gl, object, 'batchingColorTexture' );
  53167. if ( object._colorsTexture !== null ) {
  53168. p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures );
  53169. }
  53170. }
  53171. const morphAttributes = geometry.morphAttributes;
  53172. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  53173. morphtargets.update( object, geometry, program );
  53174. }
  53175. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  53176. materialProperties.receiveShadow = object.receiveShadow;
  53177. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  53178. }
  53179. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  53180. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  53181. m_uniforms.envMap.value = envMap;
  53182. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  53183. }
  53184. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  53185. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  53186. }
  53187. if ( refreshMaterial ) {
  53188. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  53189. if ( materialProperties.needsLights ) {
  53190. // the current material requires lighting info
  53191. // note: all lighting uniforms are always set correctly
  53192. // they simply reference the renderer's state for their
  53193. // values
  53194. //
  53195. // use the current material's .needsUpdate flags to set
  53196. // the GL state when required
  53197. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  53198. }
  53199. // refresh uniforms common to several materials
  53200. if ( fog && material.fog === true ) {
  53201. materials.refreshFogUniforms( m_uniforms, fog );
  53202. }
  53203. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  53204. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  53205. }
  53206. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  53207. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  53208. material.uniformsNeedUpdate = false;
  53209. }
  53210. if ( material.isSpriteMaterial ) {
  53211. p_uniforms.setValue( _gl, 'center', object.center );
  53212. }
  53213. // common matrices
  53214. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  53215. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  53216. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  53217. // UBOs
  53218. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  53219. const groups = material.uniformsGroups;
  53220. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  53221. const group = groups[ i ];
  53222. uniformsGroups.update( group, program );
  53223. uniformsGroups.bind( group, program );
  53224. }
  53225. }
  53226. return program;
  53227. }
  53228. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  53229. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  53230. uniforms.ambientLightColor.needsUpdate = value;
  53231. uniforms.lightProbe.needsUpdate = value;
  53232. uniforms.directionalLights.needsUpdate = value;
  53233. uniforms.directionalLightShadows.needsUpdate = value;
  53234. uniforms.pointLights.needsUpdate = value;
  53235. uniforms.pointLightShadows.needsUpdate = value;
  53236. uniforms.spotLights.needsUpdate = value;
  53237. uniforms.spotLightShadows.needsUpdate = value;
  53238. uniforms.rectAreaLights.needsUpdate = value;
  53239. uniforms.hemisphereLights.needsUpdate = value;
  53240. }
  53241. function materialNeedsLights( material ) {
  53242. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  53243. material.isMeshStandardMaterial || material.isShadowMaterial ||
  53244. ( material.isShaderMaterial && material.lights === true );
  53245. }
  53246. /**
  53247. * Returns the active cube face.
  53248. *
  53249. * @return {number} The active cube face.
  53250. */
  53251. this.getActiveCubeFace = function () {
  53252. return _currentActiveCubeFace;
  53253. };
  53254. /**
  53255. * Returns the active mipmap level.
  53256. *
  53257. * @return {number} The active mipmap level.
  53258. */
  53259. this.getActiveMipmapLevel = function () {
  53260. return _currentActiveMipmapLevel;
  53261. };
  53262. /**
  53263. * Returns the active render target.
  53264. *
  53265. * @return {?WebGLRenderTarget} The active render target. Returns `null` if no render target
  53266. * is currently set.
  53267. */
  53268. this.getRenderTarget = function () {
  53269. return _currentRenderTarget;
  53270. };
  53271. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  53272. const renderTargetProperties = properties.get( renderTarget );
  53273. renderTargetProperties.__autoAllocateDepthBuffer = renderTarget.resolveDepthBuffer === false;
  53274. if ( renderTargetProperties.__autoAllocateDepthBuffer === false ) {
  53275. // The multisample_render_to_texture extension doesn't work properly if there
  53276. // are midframe flushes and an external depth buffer. Disable use of the extension.
  53277. renderTargetProperties.__useRenderToTexture = false;
  53278. }
  53279. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  53280. properties.get( renderTarget.depthTexture ).__webglTexture = renderTargetProperties.__autoAllocateDepthBuffer ? undefined : depthTexture;
  53281. renderTargetProperties.__hasExternalTextures = true;
  53282. };
  53283. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  53284. const renderTargetProperties = properties.get( renderTarget );
  53285. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  53286. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  53287. };
  53288. const _scratchFrameBuffer = _gl.createFramebuffer();
  53289. /**
  53290. * Sets the active rendertarget.
  53291. *
  53292. * @param {?WebGLRenderTarget} renderTarget - The render target to set. When `null` is given,
  53293. * the canvas is set as the active render target instead.
  53294. * @param {number} [activeCubeFace=0] - The active cube face when using a cube render target.
  53295. * Indicates the z layer to render in to when using 3D or array render targets.
  53296. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  53297. */
  53298. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  53299. _currentRenderTarget = renderTarget;
  53300. _currentActiveCubeFace = activeCubeFace;
  53301. _currentActiveMipmapLevel = activeMipmapLevel;
  53302. let useDefaultFramebuffer = true;
  53303. let framebuffer = null;
  53304. let isCube = false;
  53305. let isRenderTarget3D = false;
  53306. if ( renderTarget ) {
  53307. const renderTargetProperties = properties.get( renderTarget );
  53308. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  53309. // We need to make sure to rebind the framebuffer.
  53310. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  53311. useDefaultFramebuffer = false;
  53312. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  53313. textures.setupRenderTarget( renderTarget );
  53314. } else if ( renderTargetProperties.__hasExternalTextures ) {
  53315. // Color and depth texture must be rebound in order for the swapchain to update.
  53316. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  53317. } else if ( renderTarget.depthBuffer ) {
  53318. // check if the depth texture is already bound to the frame buffer and that it's been initialized
  53319. const depthTexture = renderTarget.depthTexture;
  53320. if ( renderTargetProperties.__boundDepthTexture !== depthTexture ) {
  53321. // check if the depth texture is compatible
  53322. if (
  53323. depthTexture !== null &&
  53324. properties.has( depthTexture ) &&
  53325. ( renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height )
  53326. ) {
  53327. throw new Error( 'WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.' );
  53328. }
  53329. // Swap the depth buffer to the currently attached one
  53330. textures.setupDepthRenderbuffer( renderTarget );
  53331. }
  53332. }
  53333. const texture = renderTarget.texture;
  53334. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  53335. isRenderTarget3D = true;
  53336. }
  53337. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  53338. if ( renderTarget.isWebGLCubeRenderTarget ) {
  53339. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  53340. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  53341. } else {
  53342. framebuffer = __webglFramebuffer[ activeCubeFace ];
  53343. }
  53344. isCube = true;
  53345. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  53346. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  53347. } else {
  53348. if ( Array.isArray( __webglFramebuffer ) ) {
  53349. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  53350. } else {
  53351. framebuffer = __webglFramebuffer;
  53352. }
  53353. }
  53354. _currentViewport.copy( renderTarget.viewport );
  53355. _currentScissor.copy( renderTarget.scissor );
  53356. _currentScissorTest = renderTarget.scissorTest;
  53357. } else {
  53358. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  53359. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  53360. _currentScissorTest = _scissorTest;
  53361. }
  53362. // Use a scratch frame buffer if rendering to a mip level to avoid depth buffers
  53363. // being bound that are different sizes.
  53364. if ( activeMipmapLevel !== 0 ) {
  53365. framebuffer = _scratchFrameBuffer;
  53366. }
  53367. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  53368. if ( framebufferBound && useDefaultFramebuffer ) {
  53369. state.drawBuffers( renderTarget, framebuffer );
  53370. }
  53371. state.viewport( _currentViewport );
  53372. state.scissor( _currentScissor );
  53373. state.setScissorTest( _currentScissorTest );
  53374. if ( isCube ) {
  53375. const textureProperties = properties.get( renderTarget.texture );
  53376. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  53377. } else if ( isRenderTarget3D ) {
  53378. const layer = activeCubeFace;
  53379. for ( let i = 0; i < renderTarget.textures.length; i ++ ) {
  53380. const textureProperties = properties.get( renderTarget.textures[ i ] );
  53381. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, textureProperties.__webglTexture, activeMipmapLevel, layer );
  53382. }
  53383. } else if ( renderTarget !== null && activeMipmapLevel !== 0 ) {
  53384. // Only bind the frame buffer if we are using a scratch frame buffer to render to a mipmap.
  53385. // If we rebind the texture when using a multi sample buffer then an error about inconsistent samples will be thrown.
  53386. const textureProperties = properties.get( renderTarget.texture );
  53387. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel );
  53388. }
  53389. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  53390. };
  53391. /**
  53392. * Reads the pixel data from the given render target into the given buffer.
  53393. *
  53394. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  53395. * @param {number} x - The `x` coordinate of the copy region's origin.
  53396. * @param {number} y - The `y` coordinate of the copy region's origin.
  53397. * @param {number} width - The width of the copy region.
  53398. * @param {number} height - The height of the copy region.
  53399. * @param {TypedArray} buffer - The result buffer.
  53400. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  53401. * @param {number} [textureIndex=0] - The texture index of an MRT render target.
  53402. */
  53403. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) {
  53404. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  53405. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  53406. return;
  53407. }
  53408. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  53409. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  53410. framebuffer = framebuffer[ activeCubeFaceIndex ];
  53411. }
  53412. if ( framebuffer ) {
  53413. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  53414. try {
  53415. const texture = renderTarget.textures[ textureIndex ];
  53416. const textureFormat = texture.format;
  53417. const textureType = texture.type;
  53418. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  53419. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  53420. return;
  53421. }
  53422. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  53423. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  53424. return;
  53425. }
  53426. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  53427. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  53428. // when using MRT, select the correct color buffer for the subsequent read command
  53429. if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex );
  53430. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  53431. }
  53432. } finally {
  53433. // restore framebuffer of current render target if necessary
  53434. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  53435. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  53436. }
  53437. }
  53438. };
  53439. /**
  53440. * Asynchronous, non-blocking version of {@link WebGLRenderer#readRenderTargetPixels}.
  53441. *
  53442. * It is recommended to use this version of `readRenderTargetPixels()` whenever possible.
  53443. *
  53444. * @async
  53445. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  53446. * @param {number} x - The `x` coordinate of the copy region's origin.
  53447. * @param {number} y - The `y` coordinate of the copy region's origin.
  53448. * @param {number} width - The width of the copy region.
  53449. * @param {number} height - The height of the copy region.
  53450. * @param {TypedArray} buffer - The result buffer.
  53451. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  53452. * @param {number} [textureIndex=0] - The texture index of an MRT render target.
  53453. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  53454. */
  53455. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) {
  53456. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  53457. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  53458. }
  53459. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  53460. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  53461. framebuffer = framebuffer[ activeCubeFaceIndex ];
  53462. }
  53463. if ( framebuffer ) {
  53464. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  53465. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  53466. // set the active frame buffer to the one we want to read
  53467. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  53468. const texture = renderTarget.textures[ textureIndex ];
  53469. const textureFormat = texture.format;
  53470. const textureType = texture.type;
  53471. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  53472. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  53473. }
  53474. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  53475. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  53476. }
  53477. const glBuffer = _gl.createBuffer();
  53478. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  53479. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  53480. // when using MRT, select the correct color buffer for the subsequent read command
  53481. if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex );
  53482. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  53483. // reset the frame buffer to the currently set buffer before waiting
  53484. const currFramebuffer = _currentRenderTarget !== null ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  53485. state.bindFramebuffer( _gl.FRAMEBUFFER, currFramebuffer );
  53486. // check if the commands have finished every 8 ms
  53487. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  53488. _gl.flush();
  53489. await probeAsync( _gl, sync, 4 );
  53490. // read the data and delete the buffer
  53491. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  53492. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  53493. _gl.deleteBuffer( glBuffer );
  53494. _gl.deleteSync( sync );
  53495. return buffer;
  53496. } else {
  53497. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.' );
  53498. }
  53499. }
  53500. };
  53501. /**
  53502. * Copies pixels from the current bound framebuffer into the given texture.
  53503. *
  53504. * @param {FramebufferTexture} texture - The texture.
  53505. * @param {?Vector2} [position=null] - The start position of the copy operation.
  53506. * @param {number} [level=0] - The mip level. The default represents the base mip.
  53507. */
  53508. this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) {
  53509. const levelScale = Math.pow( 2, - level );
  53510. const width = Math.floor( texture.image.width * levelScale );
  53511. const height = Math.floor( texture.image.height * levelScale );
  53512. const x = position !== null ? position.x : 0;
  53513. const y = position !== null ? position.y : 0;
  53514. textures.setTexture2D( texture, 0 );
  53515. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height );
  53516. state.unbindTexture();
  53517. };
  53518. const _srcFramebuffer = _gl.createFramebuffer();
  53519. const _dstFramebuffer = _gl.createFramebuffer();
  53520. /**
  53521. * Copies data of the given source texture into a destination texture.
  53522. *
  53523. * When using render target textures as `srcTexture` and `dstTexture`, you must make sure both render targets are initialized
  53524. * {@link WebGLRenderer#initRenderTarget}.
  53525. *
  53526. * @param {Texture} srcTexture - The source texture.
  53527. * @param {Texture} dstTexture - The destination texture.
  53528. * @param {?(Box2|Box3)} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  53529. * @param {?(Vector2|Vector3)} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  53530. * @param {number} [srcLevel=0] - The source mipmap level to copy.
  53531. * @param {?number} [dstLevel=null] - The destination mipmap level.
  53532. */
  53533. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = null ) {
  53534. // support the previous signature with just a single dst mipmap level
  53535. if ( dstLevel === null ) {
  53536. if ( srcLevel !== 0 ) {
  53537. // @deprecated, r171
  53538. warnOnce( 'WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels.' );
  53539. dstLevel = srcLevel;
  53540. srcLevel = 0;
  53541. } else {
  53542. dstLevel = 0;
  53543. }
  53544. }
  53545. // gather the necessary dimensions to copy
  53546. let width, height, depth, minX, minY, minZ;
  53547. let dstX, dstY, dstZ;
  53548. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  53549. if ( srcRegion !== null ) {
  53550. width = srcRegion.max.x - srcRegion.min.x;
  53551. height = srcRegion.max.y - srcRegion.min.y;
  53552. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  53553. minX = srcRegion.min.x;
  53554. minY = srcRegion.min.y;
  53555. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  53556. } else {
  53557. const levelScale = Math.pow( 2, - srcLevel );
  53558. width = Math.floor( image.width * levelScale );
  53559. height = Math.floor( image.height * levelScale );
  53560. if ( srcTexture.isDataArrayTexture ) {
  53561. depth = image.depth;
  53562. } else if ( srcTexture.isData3DTexture ) {
  53563. depth = Math.floor( image.depth * levelScale );
  53564. } else {
  53565. depth = 1;
  53566. }
  53567. minX = 0;
  53568. minY = 0;
  53569. minZ = 0;
  53570. }
  53571. if ( dstPosition !== null ) {
  53572. dstX = dstPosition.x;
  53573. dstY = dstPosition.y;
  53574. dstZ = dstPosition.z;
  53575. } else {
  53576. dstX = 0;
  53577. dstY = 0;
  53578. dstZ = 0;
  53579. }
  53580. // Set up the destination target
  53581. const glFormat = utils.convert( dstTexture.format );
  53582. const glType = utils.convert( dstTexture.type );
  53583. let glTarget;
  53584. if ( dstTexture.isData3DTexture ) {
  53585. textures.setTexture3D( dstTexture, 0 );
  53586. glTarget = _gl.TEXTURE_3D;
  53587. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  53588. textures.setTexture2DArray( dstTexture, 0 );
  53589. glTarget = _gl.TEXTURE_2D_ARRAY;
  53590. } else {
  53591. textures.setTexture2D( dstTexture, 0 );
  53592. glTarget = _gl.TEXTURE_2D;
  53593. }
  53594. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  53595. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  53596. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  53597. // used for copying data from cpu
  53598. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  53599. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  53600. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  53601. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  53602. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  53603. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  53604. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  53605. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  53606. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  53607. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  53608. // set up the src texture
  53609. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture;
  53610. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture;
  53611. if ( srcTexture.isDepthTexture ) {
  53612. const srcTextureProperties = properties.get( srcTexture );
  53613. const dstTextureProperties = properties.get( dstTexture );
  53614. const srcRenderTargetProperties = properties.get( srcTextureProperties.__renderTarget );
  53615. const dstRenderTargetProperties = properties.get( dstTextureProperties.__renderTarget );
  53616. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer );
  53617. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer );
  53618. for ( let i = 0; i < depth; i ++ ) {
  53619. // if the source or destination are a 3d target then a layer needs to be bound
  53620. if ( isSrc3D ) {
  53621. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( srcTexture ).__webglTexture, srcLevel, minZ + i );
  53622. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( dstTexture ).__webglTexture, dstLevel, dstZ + i );
  53623. }
  53624. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST );
  53625. }
  53626. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  53627. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  53628. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has( srcTexture ) ) {
  53629. // get the appropriate frame buffers
  53630. const srcTextureProperties = properties.get( srcTexture );
  53631. const dstTextureProperties = properties.get( dstTexture );
  53632. // bind the frame buffer targets
  53633. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, _srcFramebuffer );
  53634. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, _dstFramebuffer );
  53635. for ( let i = 0; i < depth; i ++ ) {
  53636. // assign the correct layers and mip maps to the frame buffers
  53637. if ( isSrc3D ) {
  53638. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i );
  53639. } else {
  53640. _gl.framebufferTexture2D( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel );
  53641. }
  53642. if ( isDst3D ) {
  53643. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i );
  53644. } else {
  53645. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel );
  53646. }
  53647. // copy the data using the fastest function that can achieve the copy
  53648. if ( srcLevel !== 0 ) {
  53649. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.COLOR_BUFFER_BIT, _gl.NEAREST );
  53650. } else if ( isDst3D ) {
  53651. _gl.copyTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  53652. } else {
  53653. _gl.copyTexSubImage2D( glTarget, dstLevel, dstX, dstY, minX, minY, width, height );
  53654. }
  53655. }
  53656. // unbind read, draw buffers
  53657. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  53658. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  53659. } else {
  53660. if ( isDst3D ) {
  53661. // copy data into the 3d texture
  53662. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  53663. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  53664. } else if ( dstTexture.isCompressedArrayTexture ) {
  53665. _gl.compressedTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  53666. } else {
  53667. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  53668. }
  53669. } else {
  53670. // copy data into the 2d texture
  53671. if ( srcTexture.isDataTexture ) {
  53672. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  53673. } else if ( srcTexture.isCompressedTexture ) {
  53674. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  53675. } else {
  53676. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  53677. }
  53678. }
  53679. }
  53680. // reset values
  53681. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  53682. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  53683. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  53684. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  53685. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  53686. // Generate mipmaps only when copying level 0
  53687. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  53688. _gl.generateMipmap( glTarget );
  53689. }
  53690. state.unbindTexture();
  53691. };
  53692. /**
  53693. * Initializes the given WebGLRenderTarget memory. Useful for initializing a render target so data
  53694. * can be copied into it using {@link WebGLRenderer#copyTextureToTexture} before it has been
  53695. * rendered to.
  53696. *
  53697. * @param {WebGLRenderTarget} target - The render target.
  53698. */
  53699. this.initRenderTarget = function ( target ) {
  53700. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  53701. textures.setupRenderTarget( target );
  53702. }
  53703. };
  53704. /**
  53705. * Initializes the given texture. Useful for preloading a texture rather than waiting until first
  53706. * render (which can cause noticeable lags due to decode and GPU upload overhead).
  53707. *
  53708. * @param {Texture} texture - The texture.
  53709. */
  53710. this.initTexture = function ( texture ) {
  53711. if ( texture.isCubeTexture ) {
  53712. textures.setTextureCube( texture, 0 );
  53713. } else if ( texture.isData3DTexture ) {
  53714. textures.setTexture3D( texture, 0 );
  53715. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  53716. textures.setTexture2DArray( texture, 0 );
  53717. } else {
  53718. textures.setTexture2D( texture, 0 );
  53719. }
  53720. state.unbindTexture();
  53721. };
  53722. /**
  53723. * Can be used to reset the internal WebGL state. This method is mostly
  53724. * relevant for applications which share a single WebGL context across
  53725. * multiple WebGL libraries.
  53726. */
  53727. this.resetState = function () {
  53728. _currentActiveCubeFace = 0;
  53729. _currentActiveMipmapLevel = 0;
  53730. _currentRenderTarget = null;
  53731. state.reset();
  53732. bindingStates.reset();
  53733. };
  53734. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  53735. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  53736. }
  53737. }
  53738. /**
  53739. * Defines the coordinate system of the renderer.
  53740. *
  53741. * In `WebGLRenderer`, the value is always `WebGLCoordinateSystem`.
  53742. *
  53743. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  53744. * @default WebGLCoordinateSystem
  53745. * @readonly
  53746. */
  53747. get coordinateSystem() {
  53748. return WebGLCoordinateSystem;
  53749. }
  53750. /**
  53751. * Defines the output color space of the renderer.
  53752. *
  53753. * @type {SRGBColorSpace|LinearSRGBColorSpace}
  53754. * @default SRGBColorSpace
  53755. */
  53756. get outputColorSpace() {
  53757. return this._outputColorSpace;
  53758. }
  53759. set outputColorSpace( colorSpace ) {
  53760. this._outputColorSpace = colorSpace;
  53761. const gl = this.getContext();
  53762. gl.drawingBufferColorSpace = ColorManagement._getDrawingBufferColorSpace( colorSpace );
  53763. gl.unpackColorSpace = ColorManagement._getUnpackColorSpace();
  53764. }
  53765. }
  53766. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  53767. exports.AddEquation = AddEquation;
  53768. exports.AddOperation = AddOperation;
  53769. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  53770. exports.AdditiveBlending = AdditiveBlending;
  53771. exports.AgXToneMapping = AgXToneMapping;
  53772. exports.AlphaFormat = AlphaFormat;
  53773. exports.AlwaysCompare = AlwaysCompare;
  53774. exports.AlwaysDepth = AlwaysDepth;
  53775. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  53776. exports.AmbientLight = AmbientLight;
  53777. exports.AnimationAction = AnimationAction;
  53778. exports.AnimationClip = AnimationClip;
  53779. exports.AnimationLoader = AnimationLoader;
  53780. exports.AnimationMixer = AnimationMixer;
  53781. exports.AnimationObjectGroup = AnimationObjectGroup;
  53782. exports.AnimationUtils = AnimationUtils;
  53783. exports.ArcCurve = ArcCurve;
  53784. exports.ArrayCamera = ArrayCamera;
  53785. exports.ArrowHelper = ArrowHelper;
  53786. exports.AttachedBindMode = AttachedBindMode;
  53787. exports.Audio = Audio;
  53788. exports.AudioAnalyser = AudioAnalyser;
  53789. exports.AudioContext = AudioContext;
  53790. exports.AudioListener = AudioListener;
  53791. exports.AudioLoader = AudioLoader;
  53792. exports.AxesHelper = AxesHelper;
  53793. exports.BackSide = BackSide;
  53794. exports.BasicDepthPacking = BasicDepthPacking;
  53795. exports.BasicShadowMap = BasicShadowMap;
  53796. exports.BatchedMesh = BatchedMesh;
  53797. exports.Bone = Bone;
  53798. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  53799. exports.Box2 = Box2;
  53800. exports.Box3 = Box3;
  53801. exports.Box3Helper = Box3Helper;
  53802. exports.BoxGeometry = BoxGeometry;
  53803. exports.BoxHelper = BoxHelper;
  53804. exports.BufferAttribute = BufferAttribute;
  53805. exports.BufferGeometry = BufferGeometry;
  53806. exports.BufferGeometryLoader = BufferGeometryLoader;
  53807. exports.ByteType = ByteType;
  53808. exports.Cache = Cache;
  53809. exports.Camera = Camera;
  53810. exports.CameraHelper = CameraHelper;
  53811. exports.CanvasTexture = CanvasTexture;
  53812. exports.CapsuleGeometry = CapsuleGeometry;
  53813. exports.CatmullRomCurve3 = CatmullRomCurve3;
  53814. exports.CineonToneMapping = CineonToneMapping;
  53815. exports.CircleGeometry = CircleGeometry;
  53816. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  53817. exports.Clock = Clock;
  53818. exports.Color = Color;
  53819. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  53820. exports.ColorManagement = ColorManagement;
  53821. exports.CompressedArrayTexture = CompressedArrayTexture;
  53822. exports.CompressedCubeTexture = CompressedCubeTexture;
  53823. exports.CompressedTexture = CompressedTexture;
  53824. exports.CompressedTextureLoader = CompressedTextureLoader;
  53825. exports.ConeGeometry = ConeGeometry;
  53826. exports.ConstantAlphaFactor = ConstantAlphaFactor;
  53827. exports.ConstantColorFactor = ConstantColorFactor;
  53828. exports.Controls = Controls;
  53829. exports.CubeCamera = CubeCamera;
  53830. exports.CubeReflectionMapping = CubeReflectionMapping;
  53831. exports.CubeRefractionMapping = CubeRefractionMapping;
  53832. exports.CubeTexture = CubeTexture;
  53833. exports.CubeTextureLoader = CubeTextureLoader;
  53834. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  53835. exports.CubicBezierCurve = CubicBezierCurve;
  53836. exports.CubicBezierCurve3 = CubicBezierCurve3;
  53837. exports.CubicInterpolant = CubicInterpolant;
  53838. exports.CullFaceBack = CullFaceBack;
  53839. exports.CullFaceFront = CullFaceFront;
  53840. exports.CullFaceFrontBack = CullFaceFrontBack;
  53841. exports.CullFaceNone = CullFaceNone;
  53842. exports.Curve = Curve;
  53843. exports.CurvePath = CurvePath;
  53844. exports.CustomBlending = CustomBlending;
  53845. exports.CustomToneMapping = CustomToneMapping;
  53846. exports.CylinderGeometry = CylinderGeometry;
  53847. exports.Cylindrical = Cylindrical;
  53848. exports.Data3DTexture = Data3DTexture;
  53849. exports.DataArrayTexture = DataArrayTexture;
  53850. exports.DataTexture = DataTexture;
  53851. exports.DataTextureLoader = DataTextureLoader;
  53852. exports.DataUtils = DataUtils;
  53853. exports.DecrementStencilOp = DecrementStencilOp;
  53854. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  53855. exports.DefaultLoadingManager = DefaultLoadingManager;
  53856. exports.DepthFormat = DepthFormat;
  53857. exports.DepthStencilFormat = DepthStencilFormat;
  53858. exports.DepthTexture = DepthTexture;
  53859. exports.DetachedBindMode = DetachedBindMode;
  53860. exports.DirectionalLight = DirectionalLight;
  53861. exports.DirectionalLightHelper = DirectionalLightHelper;
  53862. exports.DiscreteInterpolant = DiscreteInterpolant;
  53863. exports.DodecahedronGeometry = DodecahedronGeometry;
  53864. exports.DoubleSide = DoubleSide;
  53865. exports.DstAlphaFactor = DstAlphaFactor;
  53866. exports.DstColorFactor = DstColorFactor;
  53867. exports.DynamicCopyUsage = DynamicCopyUsage;
  53868. exports.DynamicDrawUsage = DynamicDrawUsage;
  53869. exports.DynamicReadUsage = DynamicReadUsage;
  53870. exports.EdgesGeometry = EdgesGeometry;
  53871. exports.EllipseCurve = EllipseCurve;
  53872. exports.EqualCompare = EqualCompare;
  53873. exports.EqualDepth = EqualDepth;
  53874. exports.EqualStencilFunc = EqualStencilFunc;
  53875. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  53876. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  53877. exports.Euler = Euler;
  53878. exports.EventDispatcher = EventDispatcher;
  53879. exports.ExternalTexture = ExternalTexture;
  53880. exports.ExtrudeGeometry = ExtrudeGeometry;
  53881. exports.FileLoader = FileLoader;
  53882. exports.Float16BufferAttribute = Float16BufferAttribute;
  53883. exports.Float32BufferAttribute = Float32BufferAttribute;
  53884. exports.FloatType = FloatType;
  53885. exports.Fog = Fog;
  53886. exports.FogExp2 = FogExp2;
  53887. exports.FramebufferTexture = FramebufferTexture;
  53888. exports.FrontSide = FrontSide;
  53889. exports.Frustum = Frustum;
  53890. exports.FrustumArray = FrustumArray;
  53891. exports.GLBufferAttribute = GLBufferAttribute;
  53892. exports.GLSL1 = GLSL1;
  53893. exports.GLSL3 = GLSL3;
  53894. exports.GreaterCompare = GreaterCompare;
  53895. exports.GreaterDepth = GreaterDepth;
  53896. exports.GreaterEqualCompare = GreaterEqualCompare;
  53897. exports.GreaterEqualDepth = GreaterEqualDepth;
  53898. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  53899. exports.GreaterStencilFunc = GreaterStencilFunc;
  53900. exports.GridHelper = GridHelper;
  53901. exports.Group = Group;
  53902. exports.HalfFloatType = HalfFloatType;
  53903. exports.HemisphereLight = HemisphereLight;
  53904. exports.HemisphereLightHelper = HemisphereLightHelper;
  53905. exports.IcosahedronGeometry = IcosahedronGeometry;
  53906. exports.ImageBitmapLoader = ImageBitmapLoader;
  53907. exports.ImageLoader = ImageLoader;
  53908. exports.ImageUtils = ImageUtils;
  53909. exports.IncrementStencilOp = IncrementStencilOp;
  53910. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  53911. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  53912. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  53913. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  53914. exports.InstancedMesh = InstancedMesh;
  53915. exports.Int16BufferAttribute = Int16BufferAttribute;
  53916. exports.Int32BufferAttribute = Int32BufferAttribute;
  53917. exports.Int8BufferAttribute = Int8BufferAttribute;
  53918. exports.IntType = IntType;
  53919. exports.InterleavedBuffer = InterleavedBuffer;
  53920. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  53921. exports.Interpolant = Interpolant;
  53922. exports.InterpolateDiscrete = InterpolateDiscrete;
  53923. exports.InterpolateLinear = InterpolateLinear;
  53924. exports.InterpolateSmooth = InterpolateSmooth;
  53925. exports.InterpolationSamplingMode = InterpolationSamplingMode;
  53926. exports.InterpolationSamplingType = InterpolationSamplingType;
  53927. exports.InvertStencilOp = InvertStencilOp;
  53928. exports.KeepStencilOp = KeepStencilOp;
  53929. exports.KeyframeTrack = KeyframeTrack;
  53930. exports.LOD = LOD;
  53931. exports.LatheGeometry = LatheGeometry;
  53932. exports.Layers = Layers;
  53933. exports.LessCompare = LessCompare;
  53934. exports.LessDepth = LessDepth;
  53935. exports.LessEqualCompare = LessEqualCompare;
  53936. exports.LessEqualDepth = LessEqualDepth;
  53937. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  53938. exports.LessStencilFunc = LessStencilFunc;
  53939. exports.Light = Light;
  53940. exports.LightProbe = LightProbe;
  53941. exports.Line = Line;
  53942. exports.Line3 = Line3;
  53943. exports.LineBasicMaterial = LineBasicMaterial;
  53944. exports.LineCurve = LineCurve;
  53945. exports.LineCurve3 = LineCurve3;
  53946. exports.LineDashedMaterial = LineDashedMaterial;
  53947. exports.LineLoop = LineLoop;
  53948. exports.LineSegments = LineSegments;
  53949. exports.LinearFilter = LinearFilter;
  53950. exports.LinearInterpolant = LinearInterpolant;
  53951. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  53952. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  53953. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  53954. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  53955. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  53956. exports.LinearToneMapping = LinearToneMapping;
  53957. exports.LinearTransfer = LinearTransfer;
  53958. exports.Loader = Loader;
  53959. exports.LoaderUtils = LoaderUtils;
  53960. exports.LoadingManager = LoadingManager;
  53961. exports.LoopOnce = LoopOnce;
  53962. exports.LoopPingPong = LoopPingPong;
  53963. exports.LoopRepeat = LoopRepeat;
  53964. exports.MOUSE = MOUSE;
  53965. exports.Material = Material;
  53966. exports.MaterialLoader = MaterialLoader;
  53967. exports.MathUtils = MathUtils;
  53968. exports.Matrix2 = Matrix2;
  53969. exports.Matrix3 = Matrix3;
  53970. exports.Matrix4 = Matrix4;
  53971. exports.MaxEquation = MaxEquation;
  53972. exports.Mesh = Mesh;
  53973. exports.MeshBasicMaterial = MeshBasicMaterial;
  53974. exports.MeshDepthMaterial = MeshDepthMaterial;
  53975. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  53976. exports.MeshLambertMaterial = MeshLambertMaterial;
  53977. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  53978. exports.MeshNormalMaterial = MeshNormalMaterial;
  53979. exports.MeshPhongMaterial = MeshPhongMaterial;
  53980. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  53981. exports.MeshStandardMaterial = MeshStandardMaterial;
  53982. exports.MeshToonMaterial = MeshToonMaterial;
  53983. exports.MinEquation = MinEquation;
  53984. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  53985. exports.MixOperation = MixOperation;
  53986. exports.MultiplyBlending = MultiplyBlending;
  53987. exports.MultiplyOperation = MultiplyOperation;
  53988. exports.NearestFilter = NearestFilter;
  53989. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  53990. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  53991. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  53992. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  53993. exports.NeutralToneMapping = NeutralToneMapping;
  53994. exports.NeverCompare = NeverCompare;
  53995. exports.NeverDepth = NeverDepth;
  53996. exports.NeverStencilFunc = NeverStencilFunc;
  53997. exports.NoBlending = NoBlending;
  53998. exports.NoColorSpace = NoColorSpace;
  53999. exports.NoToneMapping = NoToneMapping;
  54000. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  54001. exports.NormalBlending = NormalBlending;
  54002. exports.NotEqualCompare = NotEqualCompare;
  54003. exports.NotEqualDepth = NotEqualDepth;
  54004. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  54005. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  54006. exports.Object3D = Object3D;
  54007. exports.ObjectLoader = ObjectLoader;
  54008. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  54009. exports.OctahedronGeometry = OctahedronGeometry;
  54010. exports.OneFactor = OneFactor;
  54011. exports.OneMinusConstantAlphaFactor = OneMinusConstantAlphaFactor;
  54012. exports.OneMinusConstantColorFactor = OneMinusConstantColorFactor;
  54013. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  54014. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  54015. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  54016. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  54017. exports.OrthographicCamera = OrthographicCamera;
  54018. exports.PCFShadowMap = PCFShadowMap;
  54019. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  54020. exports.PMREMGenerator = PMREMGenerator;
  54021. exports.Path = Path;
  54022. exports.PerspectiveCamera = PerspectiveCamera;
  54023. exports.Plane = Plane;
  54024. exports.PlaneGeometry = PlaneGeometry;
  54025. exports.PlaneHelper = PlaneHelper;
  54026. exports.PointLight = PointLight;
  54027. exports.PointLightHelper = PointLightHelper;
  54028. exports.Points = Points;
  54029. exports.PointsMaterial = PointsMaterial;
  54030. exports.PolarGridHelper = PolarGridHelper;
  54031. exports.PolyhedronGeometry = PolyhedronGeometry;
  54032. exports.PositionalAudio = PositionalAudio;
  54033. exports.PropertyBinding = PropertyBinding;
  54034. exports.PropertyMixer = PropertyMixer;
  54035. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  54036. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  54037. exports.Quaternion = Quaternion;
  54038. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  54039. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  54040. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  54041. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  54042. exports.REVISION = REVISION;
  54043. exports.RGBADepthPacking = RGBADepthPacking;
  54044. exports.RGBAFormat = RGBAFormat;
  54045. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  54046. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  54047. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  54048. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  54049. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  54050. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  54051. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  54052. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  54053. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  54054. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  54055. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  54056. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  54057. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  54058. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  54059. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  54060. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  54061. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  54062. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  54063. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  54064. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  54065. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  54066. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  54067. exports.RGBDepthPacking = RGBDepthPacking;
  54068. exports.RGBFormat = RGBFormat;
  54069. exports.RGBIntegerFormat = RGBIntegerFormat;
  54070. exports.RGB_BPTC_SIGNED_Format = RGB_BPTC_SIGNED_Format;
  54071. exports.RGB_BPTC_UNSIGNED_Format = RGB_BPTC_UNSIGNED_Format;
  54072. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  54073. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  54074. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  54075. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  54076. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  54077. exports.RGDepthPacking = RGDepthPacking;
  54078. exports.RGFormat = RGFormat;
  54079. exports.RGIntegerFormat = RGIntegerFormat;
  54080. exports.RawShaderMaterial = RawShaderMaterial;
  54081. exports.Ray = Ray;
  54082. exports.Raycaster = Raycaster;
  54083. exports.RectAreaLight = RectAreaLight;
  54084. exports.RedFormat = RedFormat;
  54085. exports.RedIntegerFormat = RedIntegerFormat;
  54086. exports.ReinhardToneMapping = ReinhardToneMapping;
  54087. exports.RenderTarget = RenderTarget;
  54088. exports.RenderTarget3D = RenderTarget3D;
  54089. exports.RepeatWrapping = RepeatWrapping;
  54090. exports.ReplaceStencilOp = ReplaceStencilOp;
  54091. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  54092. exports.RingGeometry = RingGeometry;
  54093. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  54094. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  54095. exports.SRGBColorSpace = SRGBColorSpace;
  54096. exports.SRGBTransfer = SRGBTransfer;
  54097. exports.Scene = Scene;
  54098. exports.ShaderChunk = ShaderChunk;
  54099. exports.ShaderLib = ShaderLib;
  54100. exports.ShaderMaterial = ShaderMaterial;
  54101. exports.ShadowMaterial = ShadowMaterial;
  54102. exports.Shape = Shape;
  54103. exports.ShapeGeometry = ShapeGeometry;
  54104. exports.ShapePath = ShapePath;
  54105. exports.ShapeUtils = ShapeUtils;
  54106. exports.ShortType = ShortType;
  54107. exports.Skeleton = Skeleton;
  54108. exports.SkeletonHelper = SkeletonHelper;
  54109. exports.SkinnedMesh = SkinnedMesh;
  54110. exports.Source = Source;
  54111. exports.Sphere = Sphere;
  54112. exports.SphereGeometry = SphereGeometry;
  54113. exports.Spherical = Spherical;
  54114. exports.SphericalHarmonics3 = SphericalHarmonics3;
  54115. exports.SplineCurve = SplineCurve;
  54116. exports.SpotLight = SpotLight;
  54117. exports.SpotLightHelper = SpotLightHelper;
  54118. exports.Sprite = Sprite;
  54119. exports.SpriteMaterial = SpriteMaterial;
  54120. exports.SrcAlphaFactor = SrcAlphaFactor;
  54121. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  54122. exports.SrcColorFactor = SrcColorFactor;
  54123. exports.StaticCopyUsage = StaticCopyUsage;
  54124. exports.StaticDrawUsage = StaticDrawUsage;
  54125. exports.StaticReadUsage = StaticReadUsage;
  54126. exports.StereoCamera = StereoCamera;
  54127. exports.StreamCopyUsage = StreamCopyUsage;
  54128. exports.StreamDrawUsage = StreamDrawUsage;
  54129. exports.StreamReadUsage = StreamReadUsage;
  54130. exports.StringKeyframeTrack = StringKeyframeTrack;
  54131. exports.SubtractEquation = SubtractEquation;
  54132. exports.SubtractiveBlending = SubtractiveBlending;
  54133. exports.TOUCH = TOUCH;
  54134. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  54135. exports.TetrahedronGeometry = TetrahedronGeometry;
  54136. exports.Texture = Texture;
  54137. exports.TextureLoader = TextureLoader;
  54138. exports.TextureUtils = TextureUtils;
  54139. exports.Timer = Timer;
  54140. exports.TimestampQuery = TimestampQuery;
  54141. exports.TorusGeometry = TorusGeometry;
  54142. exports.TorusKnotGeometry = TorusKnotGeometry;
  54143. exports.Triangle = Triangle;
  54144. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  54145. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  54146. exports.TrianglesDrawMode = TrianglesDrawMode;
  54147. exports.TubeGeometry = TubeGeometry;
  54148. exports.UVMapping = UVMapping;
  54149. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  54150. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  54151. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  54152. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  54153. exports.Uniform = Uniform;
  54154. exports.UniformsGroup = UniformsGroup;
  54155. exports.UniformsLib = UniformsLib;
  54156. exports.UniformsUtils = UniformsUtils;
  54157. exports.UnsignedByteType = UnsignedByteType;
  54158. exports.UnsignedInt101111Type = UnsignedInt101111Type;
  54159. exports.UnsignedInt248Type = UnsignedInt248Type;
  54160. exports.UnsignedInt5999Type = UnsignedInt5999Type;
  54161. exports.UnsignedIntType = UnsignedIntType;
  54162. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  54163. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  54164. exports.UnsignedShortType = UnsignedShortType;
  54165. exports.VSMShadowMap = VSMShadowMap;
  54166. exports.Vector2 = Vector2;
  54167. exports.Vector3 = Vector3;
  54168. exports.Vector4 = Vector4;
  54169. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  54170. exports.VideoFrameTexture = VideoFrameTexture;
  54171. exports.VideoTexture = VideoTexture;
  54172. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  54173. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  54174. exports.WebGLCoordinateSystem = WebGLCoordinateSystem;
  54175. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  54176. exports.WebGLRenderTarget = WebGLRenderTarget;
  54177. exports.WebGLRenderer = WebGLRenderer;
  54178. exports.WebGLUtils = WebGLUtils;
  54179. exports.WebGPUCoordinateSystem = WebGPUCoordinateSystem;
  54180. exports.WebXRController = WebXRController;
  54181. exports.WireframeGeometry = WireframeGeometry;
  54182. exports.WrapAroundEnding = WrapAroundEnding;
  54183. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  54184. exports.ZeroFactor = ZeroFactor;
  54185. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  54186. exports.ZeroStencilOp = ZeroStencilOp;
  54187. exports.createCanvasElement = createCanvasElement;
粤ICP备19079148号