three.cjs 1.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387
  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. * Discards the red, green and blue components and reads just the alpha component.
  644. *
  645. * @type {number}
  646. * @constant
  647. */
  648. const AlphaFormat = 1021;
  649. /**
  650. * Discards the alpha component and reads the red, green and blue component.
  651. *
  652. * @type {number}
  653. * @constant
  654. */
  655. const RGBFormat = 1022;
  656. /**
  657. * Reads the red, green, blue and alpha components.
  658. *
  659. * @type {number}
  660. * @constant
  661. */
  662. const RGBAFormat = 1023;
  663. /**
  664. * Reads each element as a single depth value, converts it to floating point, and clamps to the range `[0,1]`.
  665. *
  666. * @type {number}
  667. * @constant
  668. */
  669. const DepthFormat = 1026;
  670. /**
  671. * Reads each element is a pair of depth and stencil values. The depth component of the pair is interpreted as
  672. * in `DepthFormat`. The stencil component is interpreted based on the depth + stencil internal format.
  673. *
  674. * @type {number}
  675. * @constant
  676. */
  677. const DepthStencilFormat = 1027;
  678. /**
  679. * Discards the green, blue and alpha components and reads just the red component.
  680. *
  681. * @type {number}
  682. * @constant
  683. */
  684. const RedFormat = 1028;
  685. /**
  686. * Discards the green, blue and alpha components and reads just the red component. The texels are read as integers instead of floating point.
  687. *
  688. * @type {number}
  689. * @constant
  690. */
  691. const RedIntegerFormat = 1029;
  692. /**
  693. * Discards the alpha, and blue components and reads the red, and green components.
  694. *
  695. * @type {number}
  696. * @constant
  697. */
  698. const RGFormat = 1030;
  699. /**
  700. * Discards the alpha, and blue components and reads the red, and green components. The texels are read as integers instead of floating point.
  701. *
  702. * @type {number}
  703. * @constant
  704. */
  705. const RGIntegerFormat = 1031;
  706. /**
  707. * Discards the alpha component and reads the red, green and blue component. The texels are read as integers instead of floating point.
  708. *
  709. * @type {number}
  710. * @constant
  711. */
  712. const RGBIntegerFormat = 1032;
  713. /**
  714. * Reads the red, green, blue and alpha components. The texels are read as integers instead of floating point.
  715. *
  716. * @type {number}
  717. * @constant
  718. */
  719. const RGBAIntegerFormat = 1033;
  720. /**
  721. * A DXT1-compressed image in an RGB image format.
  722. *
  723. * @type {number}
  724. * @constant
  725. */
  726. const RGB_S3TC_DXT1_Format = 33776;
  727. /**
  728. * A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
  729. *
  730. * @type {number}
  731. * @constant
  732. */
  733. const RGBA_S3TC_DXT1_Format = 33777;
  734. /**
  735. * A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
  736. *
  737. * @type {number}
  738. * @constant
  739. */
  740. const RGBA_S3TC_DXT3_Format = 33778;
  741. /**
  742. * A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3
  743. * compression in how the alpha compression is done.
  744. *
  745. * @type {number}
  746. * @constant
  747. */
  748. const RGBA_S3TC_DXT5_Format = 33779;
  749. /**
  750. * PVRTC RGB compression in 4-bit mode. One block for each 4×4 pixels.
  751. *
  752. * @type {number}
  753. * @constant
  754. */
  755. const RGB_PVRTC_4BPPV1_Format = 35840;
  756. /**
  757. * PVRTC RGB compression in 2-bit mode. One block for each 8×4 pixels.
  758. *
  759. * @type {number}
  760. * @constant
  761. */
  762. const RGB_PVRTC_2BPPV1_Format = 35841;
  763. /**
  764. * PVRTC RGBA compression in 4-bit mode. One block for each 4×4 pixels.
  765. *
  766. * @type {number}
  767. * @constant
  768. */
  769. const RGBA_PVRTC_4BPPV1_Format = 35842;
  770. /**
  771. * PVRTC RGBA compression in 2-bit mode. One block for each 8×4 pixels.
  772. *
  773. * @type {number}
  774. * @constant
  775. */
  776. const RGBA_PVRTC_2BPPV1_Format = 35843;
  777. /**
  778. * ETC1 RGB format.
  779. *
  780. * @type {number}
  781. * @constant
  782. */
  783. const RGB_ETC1_Format = 36196;
  784. /**
  785. * ETC2 RGB format.
  786. *
  787. * @type {number}
  788. * @constant
  789. */
  790. const RGB_ETC2_Format = 37492;
  791. /**
  792. * ETC2 RGBA format.
  793. *
  794. * @type {number}
  795. * @constant
  796. */
  797. const RGBA_ETC2_EAC_Format = 37496;
  798. /**
  799. * ASTC RGBA 4x4 format.
  800. *
  801. * @type {number}
  802. * @constant
  803. */
  804. const RGBA_ASTC_4x4_Format = 37808;
  805. /**
  806. * ASTC RGBA 5x4 format.
  807. *
  808. * @type {number}
  809. * @constant
  810. */
  811. const RGBA_ASTC_5x4_Format = 37809;
  812. /**
  813. * ASTC RGBA 5x5 format.
  814. *
  815. * @type {number}
  816. * @constant
  817. */
  818. const RGBA_ASTC_5x5_Format = 37810;
  819. /**
  820. * ASTC RGBA 6x5 format.
  821. *
  822. * @type {number}
  823. * @constant
  824. */
  825. const RGBA_ASTC_6x5_Format = 37811;
  826. /**
  827. * ASTC RGBA 6x6 format.
  828. *
  829. * @type {number}
  830. * @constant
  831. */
  832. const RGBA_ASTC_6x6_Format = 37812;
  833. /**
  834. * ASTC RGBA 8x5 format.
  835. *
  836. * @type {number}
  837. * @constant
  838. */
  839. const RGBA_ASTC_8x5_Format = 37813;
  840. /**
  841. * ASTC RGBA 8x6 format.
  842. *
  843. * @type {number}
  844. * @constant
  845. */
  846. const RGBA_ASTC_8x6_Format = 37814;
  847. /**
  848. * ASTC RGBA 8x8 format.
  849. *
  850. * @type {number}
  851. * @constant
  852. */
  853. const RGBA_ASTC_8x8_Format = 37815;
  854. /**
  855. * ASTC RGBA 10x5 format.
  856. *
  857. * @type {number}
  858. * @constant
  859. */
  860. const RGBA_ASTC_10x5_Format = 37816;
  861. /**
  862. * ASTC RGBA 10x6 format.
  863. *
  864. * @type {number}
  865. * @constant
  866. */
  867. const RGBA_ASTC_10x6_Format = 37817;
  868. /**
  869. * ASTC RGBA 10x8 format.
  870. *
  871. * @type {number}
  872. * @constant
  873. */
  874. const RGBA_ASTC_10x8_Format = 37818;
  875. /**
  876. * ASTC RGBA 10x10 format.
  877. *
  878. * @type {number}
  879. * @constant
  880. */
  881. const RGBA_ASTC_10x10_Format = 37819;
  882. /**
  883. * ASTC RGBA 12x10 format.
  884. *
  885. * @type {number}
  886. * @constant
  887. */
  888. const RGBA_ASTC_12x10_Format = 37820;
  889. /**
  890. * ASTC RGBA 12x12 format.
  891. *
  892. * @type {number}
  893. * @constant
  894. */
  895. const RGBA_ASTC_12x12_Format = 37821;
  896. /**
  897. * BPTC RGBA format.
  898. *
  899. * @type {number}
  900. * @constant
  901. */
  902. const RGBA_BPTC_Format = 36492;
  903. /**
  904. * BPTC Signed RGB format.
  905. *
  906. * @type {number}
  907. * @constant
  908. */
  909. const RGB_BPTC_SIGNED_Format = 36494;
  910. /**
  911. * BPTC Unsigned RGB format.
  912. *
  913. * @type {number}
  914. * @constant
  915. */
  916. const RGB_BPTC_UNSIGNED_Format = 36495;
  917. /**
  918. * RGTC1 Red format.
  919. *
  920. * @type {number}
  921. * @constant
  922. */
  923. const RED_RGTC1_Format = 36283;
  924. /**
  925. * RGTC1 Signed Red format.
  926. *
  927. * @type {number}
  928. * @constant
  929. */
  930. const SIGNED_RED_RGTC1_Format = 36284;
  931. /**
  932. * RGTC2 Red Green format.
  933. *
  934. * @type {number}
  935. * @constant
  936. */
  937. const RED_GREEN_RGTC2_Format = 36285;
  938. /**
  939. * RGTC2 Signed Red Green format.
  940. *
  941. * @type {number}
  942. * @constant
  943. */
  944. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  945. /**
  946. * Animations are played once.
  947. *
  948. * @type {number}
  949. * @constant
  950. */
  951. const LoopOnce = 2200;
  952. /**
  953. * Animations are played with a chosen number of repetitions, each time jumping from
  954. * the end of the clip directly to its beginning.
  955. *
  956. * @type {number}
  957. * @constant
  958. */
  959. const LoopRepeat = 2201;
  960. /**
  961. * Animations are played with a chosen number of repetitions, alternately playing forward
  962. * and backward.
  963. *
  964. * @type {number}
  965. * @constant
  966. */
  967. const LoopPingPong = 2202;
  968. /**
  969. * Discrete interpolation mode for keyframe tracks.
  970. *
  971. * @type {number}
  972. * @constant
  973. */
  974. const InterpolateDiscrete = 2300;
  975. /**
  976. * Linear interpolation mode for keyframe tracks.
  977. *
  978. * @type {number}
  979. * @constant
  980. */
  981. const InterpolateLinear = 2301;
  982. /**
  983. * Smooth interpolation mode for keyframe tracks.
  984. *
  985. * @type {number}
  986. * @constant
  987. */
  988. const InterpolateSmooth = 2302;
  989. /**
  990. * Zero curvature ending for animations.
  991. *
  992. * @type {number}
  993. * @constant
  994. */
  995. const ZeroCurvatureEnding = 2400;
  996. /**
  997. * Zero slope ending for animations.
  998. *
  999. * @type {number}
  1000. * @constant
  1001. */
  1002. const ZeroSlopeEnding = 2401;
  1003. /**
  1004. * Wrap around ending for animations.
  1005. *
  1006. * @type {number}
  1007. * @constant
  1008. */
  1009. const WrapAroundEnding = 2402;
  1010. /**
  1011. * Default animation blend mode.
  1012. *
  1013. * @type {number}
  1014. * @constant
  1015. */
  1016. const NormalAnimationBlendMode = 2500;
  1017. /**
  1018. * Additive animation blend mode. Can be used to layer motions on top of
  1019. * each other to build complex performances from smaller re-usable assets.
  1020. *
  1021. * @type {number}
  1022. * @constant
  1023. */
  1024. const AdditiveAnimationBlendMode = 2501;
  1025. /**
  1026. * For every three vertices draw a single triangle.
  1027. *
  1028. * @type {number}
  1029. * @constant
  1030. */
  1031. const TrianglesDrawMode = 0;
  1032. /**
  1033. * For each vertex draw a triangle from the last three vertices.
  1034. *
  1035. * @type {number}
  1036. * @constant
  1037. */
  1038. const TriangleStripDrawMode = 1;
  1039. /**
  1040. * For each vertex draw a triangle from the first vertex and the last two vertices.
  1041. *
  1042. * @type {number}
  1043. * @constant
  1044. */
  1045. const TriangleFanDrawMode = 2;
  1046. /**
  1047. * Basic depth packing.
  1048. *
  1049. * @type {number}
  1050. * @constant
  1051. */
  1052. const BasicDepthPacking = 3200;
  1053. /**
  1054. * A depth value is packed into 32 bit RGBA.
  1055. *
  1056. * @type {number}
  1057. * @constant
  1058. */
  1059. const RGBADepthPacking = 3201;
  1060. /**
  1061. * A depth value is packed into 24 bit RGB.
  1062. *
  1063. * @type {number}
  1064. * @constant
  1065. */
  1066. const RGBDepthPacking = 3202;
  1067. /**
  1068. * A depth value is packed into 16 bit RG.
  1069. *
  1070. * @type {number}
  1071. * @constant
  1072. */
  1073. const RGDepthPacking = 3203;
  1074. /**
  1075. * Normal information is relative to the underlying surface.
  1076. *
  1077. * @type {number}
  1078. * @constant
  1079. */
  1080. const TangentSpaceNormalMap = 0;
  1081. /**
  1082. * Normal information is relative to the object orientation.
  1083. *
  1084. * @type {number}
  1085. * @constant
  1086. */
  1087. const ObjectSpaceNormalMap = 1;
  1088. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  1089. /**
  1090. * No color space.
  1091. *
  1092. * @type {string}
  1093. * @constant
  1094. */
  1095. const NoColorSpace = '';
  1096. /**
  1097. * sRGB color space.
  1098. *
  1099. * @type {string}
  1100. * @constant
  1101. */
  1102. const SRGBColorSpace = 'srgb';
  1103. /**
  1104. * sRGB-linear color space.
  1105. *
  1106. * @type {string}
  1107. * @constant
  1108. */
  1109. const LinearSRGBColorSpace = 'srgb-linear';
  1110. /**
  1111. * Linear transfer function.
  1112. *
  1113. * @type {string}
  1114. * @constant
  1115. */
  1116. const LinearTransfer = 'linear';
  1117. /**
  1118. * sRGB transfer function.
  1119. *
  1120. * @type {string}
  1121. * @constant
  1122. */
  1123. const SRGBTransfer = 'srgb';
  1124. /**
  1125. * Sets the stencil buffer value to `0`.
  1126. *
  1127. * @type {number}
  1128. * @constant
  1129. */
  1130. const ZeroStencilOp = 0;
  1131. /**
  1132. * Keeps the current value.
  1133. *
  1134. * @type {number}
  1135. * @constant
  1136. */
  1137. const KeepStencilOp = 7680;
  1138. /**
  1139. * Sets the stencil buffer value to the specified reference value.
  1140. *
  1141. * @type {number}
  1142. * @constant
  1143. */
  1144. const ReplaceStencilOp = 7681;
  1145. /**
  1146. * Increments the current stencil buffer value. Clamps to the maximum representable unsigned value.
  1147. *
  1148. * @type {number}
  1149. * @constant
  1150. */
  1151. const IncrementStencilOp = 7682;
  1152. /**
  1153. * Decrements the current stencil buffer value. Clamps to `0`.
  1154. *
  1155. * @type {number}
  1156. * @constant
  1157. */
  1158. const DecrementStencilOp = 7683;
  1159. /**
  1160. * Increments the current stencil buffer value. Wraps stencil buffer value to zero when incrementing
  1161. * the maximum representable unsigned value.
  1162. *
  1163. * @type {number}
  1164. * @constant
  1165. */
  1166. const IncrementWrapStencilOp = 34055;
  1167. /**
  1168. * Decrements the current stencil buffer value. Wraps stencil buffer value to the maximum representable
  1169. * unsigned value when decrementing a stencil buffer value of `0`.
  1170. *
  1171. * @type {number}
  1172. * @constant
  1173. */
  1174. const DecrementWrapStencilOp = 34056;
  1175. /**
  1176. * Inverts the current stencil buffer value bitwise.
  1177. *
  1178. * @type {number}
  1179. * @constant
  1180. */
  1181. const InvertStencilOp = 5386;
  1182. /**
  1183. * Will never return true.
  1184. *
  1185. * @type {number}
  1186. * @constant
  1187. */
  1188. const NeverStencilFunc = 512;
  1189. /**
  1190. * Will return true if the stencil reference value is less than the current stencil value.
  1191. *
  1192. * @type {number}
  1193. * @constant
  1194. */
  1195. const LessStencilFunc = 513;
  1196. /**
  1197. * Will return true if the stencil reference value is equal to the current stencil value.
  1198. *
  1199. * @type {number}
  1200. * @constant
  1201. */
  1202. const EqualStencilFunc = 514;
  1203. /**
  1204. * Will return true if the stencil reference value is less than or equal to the current stencil value.
  1205. *
  1206. * @type {number}
  1207. * @constant
  1208. */
  1209. const LessEqualStencilFunc = 515;
  1210. /**
  1211. * Will return true if the stencil reference value is greater than the current stencil value.
  1212. *
  1213. * @type {number}
  1214. * @constant
  1215. */
  1216. const GreaterStencilFunc = 516;
  1217. /**
  1218. * Will return true if the stencil reference value is not equal to the current stencil value.
  1219. *
  1220. * @type {number}
  1221. * @constant
  1222. */
  1223. const NotEqualStencilFunc = 517;
  1224. /**
  1225. * Will return true if the stencil reference value is greater than or equal to the current stencil value.
  1226. *
  1227. * @type {number}
  1228. * @constant
  1229. */
  1230. const GreaterEqualStencilFunc = 518;
  1231. /**
  1232. * Will always return true.
  1233. *
  1234. * @type {number}
  1235. * @constant
  1236. */
  1237. const AlwaysStencilFunc = 519;
  1238. /**
  1239. * Never pass.
  1240. *
  1241. * @type {number}
  1242. * @constant
  1243. */
  1244. const NeverCompare = 512;
  1245. /**
  1246. * Pass if the incoming value is less than the texture value.
  1247. *
  1248. * @type {number}
  1249. * @constant
  1250. */
  1251. const LessCompare = 513;
  1252. /**
  1253. * Pass if the incoming value equals the texture value.
  1254. *
  1255. * @type {number}
  1256. * @constant
  1257. */
  1258. const EqualCompare = 514;
  1259. /**
  1260. * Pass if the incoming value is less than or equal to the texture value.
  1261. *
  1262. * @type {number}
  1263. * @constant
  1264. */
  1265. const LessEqualCompare = 515;
  1266. /**
  1267. * Pass if the incoming value is greater than the texture value.
  1268. *
  1269. * @type {number}
  1270. * @constant
  1271. */
  1272. const GreaterCompare = 516;
  1273. /**
  1274. * Pass if the incoming value is not equal to the texture value.
  1275. *
  1276. * @type {number}
  1277. * @constant
  1278. */
  1279. const NotEqualCompare = 517;
  1280. /**
  1281. * Pass if the incoming value is greater than or equal to the texture value.
  1282. *
  1283. * @type {number}
  1284. * @constant
  1285. */
  1286. const GreaterEqualCompare = 518;
  1287. /**
  1288. * Always pass.
  1289. *
  1290. * @type {number}
  1291. * @constant
  1292. */
  1293. const AlwaysCompare = 519;
  1294. /**
  1295. * The contents are intended to be specified once by the application, and used many
  1296. * times as the source for drawing and image specification commands.
  1297. *
  1298. * @type {number}
  1299. * @constant
  1300. */
  1301. const StaticDrawUsage = 35044;
  1302. /**
  1303. * The contents are intended to be respecified repeatedly by the application, and
  1304. * used many times as the source for drawing and image specification commands.
  1305. *
  1306. * @type {number}
  1307. * @constant
  1308. */
  1309. const DynamicDrawUsage = 35048;
  1310. /**
  1311. * The contents are intended to be specified once by the application, and used at most
  1312. * a few times as the source for drawing and image specification commands.
  1313. *
  1314. * @type {number}
  1315. * @constant
  1316. */
  1317. const StreamDrawUsage = 35040;
  1318. /**
  1319. * The contents are intended to be specified once by reading data from the 3D API, and queried
  1320. * many times by the application.
  1321. *
  1322. * @type {number}
  1323. * @constant
  1324. */
  1325. const StaticReadUsage = 35045;
  1326. /**
  1327. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and queried
  1328. * many times by the application.
  1329. *
  1330. * @type {number}
  1331. * @constant
  1332. */
  1333. const DynamicReadUsage = 35049;
  1334. /**
  1335. * The contents are intended to be specified once by reading data from the 3D API, and queried at most
  1336. * a few times by the application
  1337. *
  1338. * @type {number}
  1339. * @constant
  1340. */
  1341. const StreamReadUsage = 35041;
  1342. /**
  1343. * The contents are intended to be specified once by reading data from the 3D API, and used many times as
  1344. * the source for WebGL drawing and image specification commands.
  1345. *
  1346. * @type {number}
  1347. * @constant
  1348. */
  1349. const StaticCopyUsage = 35046;
  1350. /**
  1351. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and used many times
  1352. * as the source for WebGL drawing and image specification commands.
  1353. *
  1354. * @type {number}
  1355. * @constant
  1356. */
  1357. const DynamicCopyUsage = 35050;
  1358. /**
  1359. * The contents are intended to be specified once by reading data from the 3D API, and used at most a few times
  1360. * as the source for WebGL drawing and image specification commands.
  1361. *
  1362. * @type {number}
  1363. * @constant
  1364. */
  1365. const StreamCopyUsage = 35042;
  1366. /**
  1367. * GLSL 1 shader code.
  1368. *
  1369. * @type {string}
  1370. * @constant
  1371. */
  1372. const GLSL1 = '100';
  1373. /**
  1374. * GLSL 3 shader code.
  1375. *
  1376. * @type {string}
  1377. * @constant
  1378. */
  1379. const GLSL3 = '300 es';
  1380. /**
  1381. * WebGL coordinate system.
  1382. *
  1383. * @type {number}
  1384. * @constant
  1385. */
  1386. const WebGLCoordinateSystem = 2000;
  1387. /**
  1388. * WebGPU coordinate system.
  1389. *
  1390. * @type {number}
  1391. * @constant
  1392. */
  1393. const WebGPUCoordinateSystem = 2001;
  1394. /**
  1395. * Represents the different timestamp query types.
  1396. *
  1397. * @type {ConstantsTimestampQuery}
  1398. * @constant
  1399. */
  1400. const TimestampQuery = {
  1401. COMPUTE: 'compute',
  1402. RENDER: 'render'
  1403. };
  1404. /**
  1405. * Represents mouse buttons and interaction types in context of controls.
  1406. *
  1407. * @type {ConstantsInterpolationSamplingType}
  1408. * @constant
  1409. */
  1410. const InterpolationSamplingType = {
  1411. PERSPECTIVE: 'perspective',
  1412. LINEAR: 'linear',
  1413. FLAT: 'flat'
  1414. };
  1415. /**
  1416. * Represents the different interpolation sampling modes.
  1417. *
  1418. * @type {ConstantsInterpolationSamplingMode}
  1419. * @constant
  1420. */
  1421. const InterpolationSamplingMode = {
  1422. NORMAL: 'normal',
  1423. CENTROID: 'centroid',
  1424. SAMPLE: 'sample',
  1425. FIRST: 'first',
  1426. EITHER: 'either'
  1427. };
  1428. /**
  1429. * This type represents mouse buttons and interaction types in context of controls.
  1430. *
  1431. * @typedef {Object} ConstantsMouse
  1432. * @property {number} MIDDLE - The left mouse button.
  1433. * @property {number} LEFT - The middle mouse button.
  1434. * @property {number} RIGHT - The right mouse button.
  1435. * @property {number} ROTATE - A rotate interaction.
  1436. * @property {number} DOLLY - A dolly interaction.
  1437. * @property {number} PAN - A pan interaction.
  1438. **/
  1439. /**
  1440. * This type represents touch interaction types in context of controls.
  1441. *
  1442. * @typedef {Object} ConstantsTouch
  1443. * @property {number} ROTATE - A rotate interaction.
  1444. * @property {number} PAN - A pan interaction.
  1445. * @property {number} DOLLY_PAN - The dolly-pan interaction.
  1446. * @property {number} DOLLY_ROTATE - A dolly-rotate interaction.
  1447. **/
  1448. /**
  1449. * This type represents the different timestamp query types.
  1450. *
  1451. * @typedef {Object} ConstantsTimestampQuery
  1452. * @property {string} COMPUTE - A `compute` timestamp query.
  1453. * @property {string} RENDER - A `render` timestamp query.
  1454. **/
  1455. /**
  1456. * Represents the different interpolation sampling types.
  1457. *
  1458. * @typedef {Object} ConstantsInterpolationSamplingType
  1459. * @property {string} PERSPECTIVE - Perspective-correct interpolation.
  1460. * @property {string} LINEAR - Linear interpolation.
  1461. * @property {string} FLAT - Flat interpolation.
  1462. */
  1463. /**
  1464. * Represents the different interpolation sampling modes.
  1465. *
  1466. * @typedef {Object} ConstantsInterpolationSamplingMode
  1467. * @property {string} NORMAL - Normal sampling mode.
  1468. * @property {string} CENTROID - Centroid sampling mode.
  1469. * @property {string} SAMPLE - Sample-specific sampling mode.
  1470. * @property {string} FLAT_FIRST - Flat interpolation using the first vertex.
  1471. * @property {string} FLAT_EITHER - Flat interpolation using either vertex.
  1472. */
  1473. /**
  1474. * This modules allows to dispatch event objects on custom JavaScript objects.
  1475. *
  1476. * Main repository: [eventdispatcher.js]{@link https://github.com/mrdoob/eventdispatcher.js/}
  1477. *
  1478. * Code Example:
  1479. * ```js
  1480. * class Car extends EventDispatcher {
  1481. * start() {
  1482. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  1483. * }
  1484. *};
  1485. *
  1486. * // Using events with the custom object
  1487. * const car = new Car();
  1488. * car.addEventListener( 'start', function ( event ) {
  1489. * alert( event.message );
  1490. * } );
  1491. *
  1492. * car.start();
  1493. * ```
  1494. */
  1495. class EventDispatcher {
  1496. /**
  1497. * Adds the given event listener to the given event type.
  1498. *
  1499. * @param {string} type - The type of event to listen to.
  1500. * @param {Function} listener - The function that gets called when the event is fired.
  1501. */
  1502. addEventListener( type, listener ) {
  1503. if ( this._listeners === undefined ) this._listeners = {};
  1504. const listeners = this._listeners;
  1505. if ( listeners[ type ] === undefined ) {
  1506. listeners[ type ] = [];
  1507. }
  1508. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  1509. listeners[ type ].push( listener );
  1510. }
  1511. }
  1512. /**
  1513. * Returns `true` if the given event listener has been added to the given event type.
  1514. *
  1515. * @param {string} type - The type of event.
  1516. * @param {Function} listener - The listener to check.
  1517. * @return {boolean} Whether the given event listener has been added to the given event type.
  1518. */
  1519. hasEventListener( type, listener ) {
  1520. const listeners = this._listeners;
  1521. if ( listeners === undefined ) return false;
  1522. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  1523. }
  1524. /**
  1525. * Removes the given event listener from the given event type.
  1526. *
  1527. * @param {string} type - The type of event.
  1528. * @param {Function} listener - The listener to remove.
  1529. */
  1530. removeEventListener( type, listener ) {
  1531. const listeners = this._listeners;
  1532. if ( listeners === undefined ) return;
  1533. const listenerArray = listeners[ type ];
  1534. if ( listenerArray !== undefined ) {
  1535. const index = listenerArray.indexOf( listener );
  1536. if ( index !== -1 ) {
  1537. listenerArray.splice( index, 1 );
  1538. }
  1539. }
  1540. }
  1541. /**
  1542. * Dispatches an event object.
  1543. *
  1544. * @param {Object} event - The event that gets fired.
  1545. */
  1546. dispatchEvent( event ) {
  1547. const listeners = this._listeners;
  1548. if ( listeners === undefined ) return;
  1549. const listenerArray = listeners[ event.type ];
  1550. if ( listenerArray !== undefined ) {
  1551. event.target = this;
  1552. // Make a copy, in case listeners are removed while iterating.
  1553. const array = listenerArray.slice( 0 );
  1554. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1555. array[ i ].call( this, event );
  1556. }
  1557. event.target = null;
  1558. }
  1559. }
  1560. }
  1561. 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' ];
  1562. let _seed = 1234567;
  1563. const DEG2RAD = Math.PI / 180;
  1564. const RAD2DEG = 180 / Math.PI;
  1565. /**
  1566. * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
  1567. * (universally unique identifier).
  1568. *
  1569. * @return {string} The UUID.
  1570. */
  1571. function generateUUID() {
  1572. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1573. const d0 = Math.random() * 0xffffffff | 0;
  1574. const d1 = Math.random() * 0xffffffff | 0;
  1575. const d2 = Math.random() * 0xffffffff | 0;
  1576. const d3 = Math.random() * 0xffffffff | 0;
  1577. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1578. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1579. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1580. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1581. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  1582. return uuid.toLowerCase();
  1583. }
  1584. /**
  1585. * Clamps the given value between min and max.
  1586. *
  1587. * @param {number} value - The value to clamp.
  1588. * @param {number} min - The min value.
  1589. * @param {number} max - The max value.
  1590. * @return {number} The clamped value.
  1591. */
  1592. function clamp( value, min, max ) {
  1593. return Math.max( min, Math.min( max, value ) );
  1594. }
  1595. /**
  1596. * Computes the Euclidean modulo of the given parameters that
  1597. * is `( ( n % m ) + m ) % m`.
  1598. *
  1599. * @param {number} n - The first parameter.
  1600. * @param {number} m - The second parameter.
  1601. * @return {number} The Euclidean modulo.
  1602. */
  1603. function euclideanModulo( n, m ) {
  1604. // https://en.wikipedia.org/wiki/Modulo_operation
  1605. return ( ( n % m ) + m ) % m;
  1606. }
  1607. /**
  1608. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1609. * for the given value.
  1610. *
  1611. * @param {number} x - The value to be mapped.
  1612. * @param {number} a1 - Minimum value for range A.
  1613. * @param {number} a2 - Maximum value for range A.
  1614. * @param {number} b1 - Minimum value for range B.
  1615. * @param {number} b2 - Maximum value for range B.
  1616. * @return {number} The mapped value.
  1617. */
  1618. function mapLinear( x, a1, a2, b1, b2 ) {
  1619. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1620. }
  1621. /**
  1622. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1623. * between the start and end point.
  1624. *
  1625. * @param {number} x - The start point
  1626. * @param {number} y - The end point.
  1627. * @param {number} value - A value between start and end.
  1628. * @return {number} The interpolation factor.
  1629. */
  1630. function inverseLerp( x, y, value ) {
  1631. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1632. if ( x !== y ) {
  1633. return ( value - x ) / ( y - x );
  1634. } else {
  1635. return 0;
  1636. }
  1637. }
  1638. /**
  1639. * Returns a value linearly interpolated from two known points based on the given interval -
  1640. * `t = 0` will return `x` and `t = 1` will return `y`.
  1641. *
  1642. * @param {number} x - The start point
  1643. * @param {number} y - The end point.
  1644. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1645. * @return {number} The interpolated value.
  1646. */
  1647. function lerp( x, y, t ) {
  1648. return ( 1 - t ) * x + t * y;
  1649. }
  1650. /**
  1651. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1652. * time to maintain frame rate independent movement. For details, see
  1653. * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
  1654. *
  1655. * @param {number} x - The current point.
  1656. * @param {number} y - The target point.
  1657. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1658. * and a lower value will make the movement more gradual.
  1659. * @param {number} dt - Delta time in seconds.
  1660. * @return {number} The interpolated value.
  1661. */
  1662. function damp( x, y, lambda, dt ) {
  1663. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  1664. }
  1665. /**
  1666. * Returns a value that alternates between `0` and the given `length` parameter.
  1667. *
  1668. * @param {number} x - The value to pingpong.
  1669. * @param {number} [length=1] - The positive value the function will pingpong to.
  1670. * @return {number} The alternated value.
  1671. */
  1672. function pingpong( x, length = 1 ) {
  1673. // https://www.desmos.com/calculator/vcsjnyz7x4
  1674. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  1675. }
  1676. /**
  1677. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  1678. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  1679. * the `min` and `max`.
  1680. *
  1681. * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
  1682. *
  1683. * @param {number} x - The value to evaluate based on its position between min and max.
  1684. * @param {number} min - The min value. Any x value below min will be `0`.
  1685. * @param {number} max - The max value. Any x value above max will be `1`.
  1686. * @return {number} The alternated value.
  1687. */
  1688. function smoothstep( x, min, max ) {
  1689. if ( x <= min ) return 0;
  1690. if ( x >= max ) return 1;
  1691. x = ( x - min ) / ( max - min );
  1692. return x * x * ( 3 - 2 * x );
  1693. }
  1694. /**
  1695. * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
  1696. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  1697. *
  1698. * @param {number} x - The value to evaluate based on its position between min and max.
  1699. * @param {number} min - The min value. Any x value below min will be `0`.
  1700. * @param {number} max - The max value. Any x value above max will be `1`.
  1701. * @return {number} The alternated value.
  1702. */
  1703. function smootherstep( x, min, max ) {
  1704. if ( x <= min ) return 0;
  1705. if ( x >= max ) return 1;
  1706. x = ( x - min ) / ( max - min );
  1707. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  1708. }
  1709. /**
  1710. * Returns a random integer from `<low, high>` interval.
  1711. *
  1712. * @param {number} low - The lower value boundary.
  1713. * @param {number} high - The upper value boundary
  1714. * @return {number} A random integer.
  1715. */
  1716. function randInt( low, high ) {
  1717. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  1718. }
  1719. /**
  1720. * Returns a random float from `<low, high>` interval.
  1721. *
  1722. * @param {number} low - The lower value boundary.
  1723. * @param {number} high - The upper value boundary
  1724. * @return {number} A random float.
  1725. */
  1726. function randFloat( low, high ) {
  1727. return low + Math.random() * ( high - low );
  1728. }
  1729. /**
  1730. * Returns a random integer from `<-range/2, range/2>` interval.
  1731. *
  1732. * @param {number} range - Defines the value range.
  1733. * @return {number} A random float.
  1734. */
  1735. function randFloatSpread( range ) {
  1736. return range * ( 0.5 - Math.random() );
  1737. }
  1738. /**
  1739. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  1740. *
  1741. * @param {number} [s] - The integer seed.
  1742. * @return {number} A random float.
  1743. */
  1744. function seededRandom( s ) {
  1745. if ( s !== undefined ) _seed = s;
  1746. // Mulberry32 generator
  1747. let t = _seed += 0x6D2B79F5;
  1748. t = Math.imul( t ^ t >>> 15, t | 1 );
  1749. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  1750. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  1751. }
  1752. /**
  1753. * Converts degrees to radians.
  1754. *
  1755. * @param {number} degrees - A value in degrees.
  1756. * @return {number} The converted value in radians.
  1757. */
  1758. function degToRad( degrees ) {
  1759. return degrees * DEG2RAD;
  1760. }
  1761. /**
  1762. * Converts radians to degrees.
  1763. *
  1764. * @param {number} radians - A value in radians.
  1765. * @return {number} The converted value in degrees.
  1766. */
  1767. function radToDeg( radians ) {
  1768. return radians * RAD2DEG;
  1769. }
  1770. /**
  1771. * Returns `true` if the given number is a power of two.
  1772. *
  1773. * @param {number} value - The value to check.
  1774. * @return {boolean} Whether the given number is a power of two or not.
  1775. */
  1776. function isPowerOfTwo( value ) {
  1777. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  1778. }
  1779. /**
  1780. * Returns the smallest power of two that is greater than or equal to the given number.
  1781. *
  1782. * @param {number} value - The value to find a POT for.
  1783. * @return {number} The smallest power of two that is greater than or equal to the given number.
  1784. */
  1785. function ceilPowerOfTwo( value ) {
  1786. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  1787. }
  1788. /**
  1789. * Returns the largest power of two that is less than or equal to the given number.
  1790. *
  1791. * @param {number} value - The value to find a POT for.
  1792. * @return {number} The largest power of two that is less than or equal to the given number.
  1793. */
  1794. function floorPowerOfTwo( value ) {
  1795. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  1796. }
  1797. /**
  1798. * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
  1799. * defined by the given angles and order.
  1800. *
  1801. * Rotations are applied to the axes in the order specified by order:
  1802. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  1803. *
  1804. * @param {Quaternion} q - The quaternion to set.
  1805. * @param {number} a - The rotation applied to the first axis, in radians.
  1806. * @param {number} b - The rotation applied to the second axis, in radians.
  1807. * @param {number} c - The rotation applied to the third axis, in radians.
  1808. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  1809. */
  1810. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  1811. const cos = Math.cos;
  1812. const sin = Math.sin;
  1813. const c2 = cos( b / 2 );
  1814. const s2 = sin( b / 2 );
  1815. const c13 = cos( ( a + c ) / 2 );
  1816. const s13 = sin( ( a + c ) / 2 );
  1817. const c1_3 = cos( ( a - c ) / 2 );
  1818. const s1_3 = sin( ( a - c ) / 2 );
  1819. const c3_1 = cos( ( c - a ) / 2 );
  1820. const s3_1 = sin( ( c - a ) / 2 );
  1821. switch ( order ) {
  1822. case 'XYX':
  1823. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  1824. break;
  1825. case 'YZY':
  1826. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  1827. break;
  1828. case 'ZXZ':
  1829. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  1830. break;
  1831. case 'XZX':
  1832. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  1833. break;
  1834. case 'YXY':
  1835. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  1836. break;
  1837. case 'ZYZ':
  1838. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  1839. break;
  1840. default:
  1841. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  1842. }
  1843. }
  1844. /**
  1845. * Denormalizes the given value according to the given typed array.
  1846. *
  1847. * @param {number} value - The value to denormalize.
  1848. * @param {TypedArray} array - The typed array that defines the data type of the value.
  1849. * @return {number} The denormalize (float) value in the range `[0,1]`.
  1850. */
  1851. function denormalize( value, array ) {
  1852. switch ( array.constructor ) {
  1853. case Float32Array:
  1854. return value;
  1855. case Uint32Array:
  1856. return value / 4294967295.0;
  1857. case Uint16Array:
  1858. return value / 65535.0;
  1859. case Uint8Array:
  1860. return value / 255.0;
  1861. case Int32Array:
  1862. return Math.max( value / 2147483647.0, -1 );
  1863. case Int16Array:
  1864. return Math.max( value / 32767.0, -1 );
  1865. case Int8Array:
  1866. return Math.max( value / 127.0, -1 );
  1867. default:
  1868. throw new Error( 'Invalid component type.' );
  1869. }
  1870. }
  1871. /**
  1872. * Normalizes the given value according to the given typed array.
  1873. *
  1874. * @param {number} value - The float value in the range `[0,1]` to normalize.
  1875. * @param {TypedArray} array - The typed array that defines the data type of the value.
  1876. * @return {number} The normalize value.
  1877. */
  1878. function normalize( value, array ) {
  1879. switch ( array.constructor ) {
  1880. case Float32Array:
  1881. return value;
  1882. case Uint32Array:
  1883. return Math.round( value * 4294967295.0 );
  1884. case Uint16Array:
  1885. return Math.round( value * 65535.0 );
  1886. case Uint8Array:
  1887. return Math.round( value * 255.0 );
  1888. case Int32Array:
  1889. return Math.round( value * 2147483647.0 );
  1890. case Int16Array:
  1891. return Math.round( value * 32767.0 );
  1892. case Int8Array:
  1893. return Math.round( value * 127.0 );
  1894. default:
  1895. throw new Error( 'Invalid component type.' );
  1896. }
  1897. }
  1898. /**
  1899. * @class
  1900. * @classdesc A collection of math utility functions.
  1901. * @hideconstructor
  1902. */
  1903. const MathUtils = {
  1904. DEG2RAD: DEG2RAD,
  1905. RAD2DEG: RAD2DEG,
  1906. /**
  1907. * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
  1908. * (universally unique identifier).
  1909. *
  1910. * @static
  1911. * @method
  1912. * @return {string} The UUID.
  1913. */
  1914. generateUUID: generateUUID,
  1915. /**
  1916. * Clamps the given value between min and max.
  1917. *
  1918. * @static
  1919. * @method
  1920. * @param {number} value - The value to clamp.
  1921. * @param {number} min - The min value.
  1922. * @param {number} max - The max value.
  1923. * @return {number} The clamped value.
  1924. */
  1925. clamp: clamp,
  1926. /**
  1927. * Computes the Euclidean modulo of the given parameters that
  1928. * is `( ( n % m ) + m ) % m`.
  1929. *
  1930. * @static
  1931. * @method
  1932. * @param {number} n - The first parameter.
  1933. * @param {number} m - The second parameter.
  1934. * @return {number} The Euclidean modulo.
  1935. */
  1936. euclideanModulo: euclideanModulo,
  1937. /**
  1938. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1939. * for the given value.
  1940. *
  1941. * @static
  1942. * @method
  1943. * @param {number} x - The value to be mapped.
  1944. * @param {number} a1 - Minimum value for range A.
  1945. * @param {number} a2 - Maximum value for range A.
  1946. * @param {number} b1 - Minimum value for range B.
  1947. * @param {number} b2 - Maximum value for range B.
  1948. * @return {number} The mapped value.
  1949. */
  1950. mapLinear: mapLinear,
  1951. /**
  1952. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1953. * between the start and end point.
  1954. *
  1955. * @static
  1956. * @method
  1957. * @param {number} x - The start point
  1958. * @param {number} y - The end point.
  1959. * @param {number} value - A value between start and end.
  1960. * @return {number} The interpolation factor.
  1961. */
  1962. inverseLerp: inverseLerp,
  1963. /**
  1964. * Returns a value linearly interpolated from two known points based on the given interval -
  1965. * `t = 0` will return `x` and `t = 1` will return `y`.
  1966. *
  1967. * @static
  1968. * @method
  1969. * @param {number} x - The start point
  1970. * @param {number} y - The end point.
  1971. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1972. * @return {number} The interpolated value.
  1973. */
  1974. lerp: lerp,
  1975. /**
  1976. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1977. * time to maintain frame rate independent movement. For details, see
  1978. * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
  1979. *
  1980. * @static
  1981. * @method
  1982. * @param {number} x - The current point.
  1983. * @param {number} y - The target point.
  1984. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1985. * and a lower value will make the movement more gradual.
  1986. * @param {number} dt - Delta time in seconds.
  1987. * @return {number} The interpolated value.
  1988. */
  1989. damp: damp,
  1990. /**
  1991. * Returns a value that alternates between `0` and the given `length` parameter.
  1992. *
  1993. * @static
  1994. * @method
  1995. * @param {number} x - The value to pingpong.
  1996. * @param {number} [length=1] - The positive value the function will pingpong to.
  1997. * @return {number} The alternated value.
  1998. */
  1999. pingpong: pingpong,
  2000. /**
  2001. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2002. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2003. * the `min` and `max`.
  2004. *
  2005. * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
  2006. *
  2007. * @static
  2008. * @method
  2009. * @param {number} x - The value to evaluate based on its position between min and max.
  2010. * @param {number} min - The min value. Any x value below min will be `0`.
  2011. * @param {number} max - The max value. Any x value above max will be `1`.
  2012. * @return {number} The alternated value.
  2013. */
  2014. smoothstep: smoothstep,
  2015. /**
  2016. * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
  2017. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  2018. *
  2019. * @static
  2020. * @method
  2021. * @param {number} x - The value to evaluate based on its position between min and max.
  2022. * @param {number} min - The min value. Any x value below min will be `0`.
  2023. * @param {number} max - The max value. Any x value above max will be `1`.
  2024. * @return {number} The alternated value.
  2025. */
  2026. smootherstep: smootherstep,
  2027. /**
  2028. * Returns a random integer from `<low, high>` interval.
  2029. *
  2030. * @static
  2031. * @method
  2032. * @param {number} low - The lower value boundary.
  2033. * @param {number} high - The upper value boundary
  2034. * @return {number} A random integer.
  2035. */
  2036. randInt: randInt,
  2037. /**
  2038. * Returns a random float from `<low, high>` interval.
  2039. *
  2040. * @static
  2041. * @method
  2042. * @param {number} low - The lower value boundary.
  2043. * @param {number} high - The upper value boundary
  2044. * @return {number} A random float.
  2045. */
  2046. randFloat: randFloat,
  2047. /**
  2048. * Returns a random integer from `<-range/2, range/2>` interval.
  2049. *
  2050. * @static
  2051. * @method
  2052. * @param {number} range - Defines the value range.
  2053. * @return {number} A random float.
  2054. */
  2055. randFloatSpread: randFloatSpread,
  2056. /**
  2057. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2058. *
  2059. * @static
  2060. * @method
  2061. * @param {number} [s] - The integer seed.
  2062. * @return {number} A random float.
  2063. */
  2064. seededRandom: seededRandom,
  2065. /**
  2066. * Converts degrees to radians.
  2067. *
  2068. * @static
  2069. * @method
  2070. * @param {number} degrees - A value in degrees.
  2071. * @return {number} The converted value in radians.
  2072. */
  2073. degToRad: degToRad,
  2074. /**
  2075. * Converts radians to degrees.
  2076. *
  2077. * @static
  2078. * @method
  2079. * @param {number} radians - A value in radians.
  2080. * @return {number} The converted value in degrees.
  2081. */
  2082. radToDeg: radToDeg,
  2083. /**
  2084. * Returns `true` if the given number is a power of two.
  2085. *
  2086. * @static
  2087. * @method
  2088. * @param {number} value - The value to check.
  2089. * @return {boolean} Whether the given number is a power of two or not.
  2090. */
  2091. isPowerOfTwo: isPowerOfTwo,
  2092. /**
  2093. * Returns the smallest power of two that is greater than or equal to the given number.
  2094. *
  2095. * @static
  2096. * @method
  2097. * @param {number} value - The value to find a POT for.
  2098. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2099. */
  2100. ceilPowerOfTwo: ceilPowerOfTwo,
  2101. /**
  2102. * Returns the largest power of two that is less than or equal to the given number.
  2103. *
  2104. * @static
  2105. * @method
  2106. * @param {number} value - The value to find a POT for.
  2107. * @return {number} The largest power of two that is less than or equal to the given number.
  2108. */
  2109. floorPowerOfTwo: floorPowerOfTwo,
  2110. /**
  2111. * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
  2112. * defined by the given angles and order.
  2113. *
  2114. * Rotations are applied to the axes in the order specified by order:
  2115. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2116. *
  2117. * @static
  2118. * @method
  2119. * @param {Quaternion} q - The quaternion to set.
  2120. * @param {number} a - The rotation applied to the first axis, in radians.
  2121. * @param {number} b - The rotation applied to the second axis, in radians.
  2122. * @param {number} c - The rotation applied to the third axis, in radians.
  2123. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2124. */
  2125. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  2126. /**
  2127. * Normalizes the given value according to the given typed array.
  2128. *
  2129. * @static
  2130. * @method
  2131. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2132. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2133. * @return {number} The normalize value.
  2134. */
  2135. normalize: normalize,
  2136. /**
  2137. * Denormalizes the given value according to the given typed array.
  2138. *
  2139. * @static
  2140. * @method
  2141. * @param {number} value - The value to denormalize.
  2142. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2143. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2144. */
  2145. denormalize: denormalize
  2146. };
  2147. /**
  2148. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  2149. * (labeled x and y), which can be used to represent a number of things, such as:
  2150. *
  2151. * - A point in 2D space (i.e. a position on a plane).
  2152. * - A direction and length across a plane. In three.js the length will
  2153. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  2154. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  2155. * - Any arbitrary ordered pair of numbers.
  2156. *
  2157. * There are other things a 2D vector can be used to represent, such as
  2158. * momentum vectors, complex numbers and so on, however these are the most
  2159. * common uses in three.js.
  2160. *
  2161. * Iterating through a vector instance will yield its components `(x, y)` in
  2162. * the corresponding order.
  2163. * ```js
  2164. * const a = new THREE.Vector2( 0, 1 );
  2165. *
  2166. * //no arguments; will be initialised to (0, 0)
  2167. * const b = new THREE.Vector2( );
  2168. *
  2169. * const d = a.distanceTo( b );
  2170. * ```
  2171. */
  2172. class Vector2 {
  2173. /**
  2174. * Constructs a new 2D vector.
  2175. *
  2176. * @param {number} [x=0] - The x value of this vector.
  2177. * @param {number} [y=0] - The y value of this vector.
  2178. */
  2179. constructor( x = 0, y = 0 ) {
  2180. /**
  2181. * This flag can be used for type testing.
  2182. *
  2183. * @type {boolean}
  2184. * @readonly
  2185. * @default true
  2186. */
  2187. Vector2.prototype.isVector2 = true;
  2188. /**
  2189. * The x value of this vector.
  2190. *
  2191. * @type {number}
  2192. */
  2193. this.x = x;
  2194. /**
  2195. * The y value of this vector.
  2196. *
  2197. * @type {number}
  2198. */
  2199. this.y = y;
  2200. }
  2201. /**
  2202. * Alias for {@link Vector2#x}.
  2203. *
  2204. * @type {number}
  2205. */
  2206. get width() {
  2207. return this.x;
  2208. }
  2209. set width( value ) {
  2210. this.x = value;
  2211. }
  2212. /**
  2213. * Alias for {@link Vector2#y}.
  2214. *
  2215. * @type {number}
  2216. */
  2217. get height() {
  2218. return this.y;
  2219. }
  2220. set height( value ) {
  2221. this.y = value;
  2222. }
  2223. /**
  2224. * Sets the vector components.
  2225. *
  2226. * @param {number} x - The value of the x component.
  2227. * @param {number} y - The value of the y component.
  2228. * @return {Vector2} A reference to this vector.
  2229. */
  2230. set( x, y ) {
  2231. this.x = x;
  2232. this.y = y;
  2233. return this;
  2234. }
  2235. /**
  2236. * Sets the vector components to the same value.
  2237. *
  2238. * @param {number} scalar - The value to set for all vector components.
  2239. * @return {Vector2} A reference to this vector.
  2240. */
  2241. setScalar( scalar ) {
  2242. this.x = scalar;
  2243. this.y = scalar;
  2244. return this;
  2245. }
  2246. /**
  2247. * Sets the vector's x component to the given value
  2248. *
  2249. * @param {number} x - The value to set.
  2250. * @return {Vector2} A reference to this vector.
  2251. */
  2252. setX( x ) {
  2253. this.x = x;
  2254. return this;
  2255. }
  2256. /**
  2257. * Sets the vector's y component to the given value
  2258. *
  2259. * @param {number} y - The value to set.
  2260. * @return {Vector2} A reference to this vector.
  2261. */
  2262. setY( y ) {
  2263. this.y = y;
  2264. return this;
  2265. }
  2266. /**
  2267. * Allows to set a vector component with an index.
  2268. *
  2269. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2270. * @param {number} value - The value to set.
  2271. * @return {Vector2} A reference to this vector.
  2272. */
  2273. setComponent( index, value ) {
  2274. switch ( index ) {
  2275. case 0: this.x = value; break;
  2276. case 1: this.y = value; break;
  2277. default: throw new Error( 'index is out of range: ' + index );
  2278. }
  2279. return this;
  2280. }
  2281. /**
  2282. * Returns the value of the vector component which matches the given index.
  2283. *
  2284. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2285. * @return {number} A vector component value.
  2286. */
  2287. getComponent( index ) {
  2288. switch ( index ) {
  2289. case 0: return this.x;
  2290. case 1: return this.y;
  2291. default: throw new Error( 'index is out of range: ' + index );
  2292. }
  2293. }
  2294. /**
  2295. * Returns a new vector with copied values from this instance.
  2296. *
  2297. * @return {Vector2} A clone of this instance.
  2298. */
  2299. clone() {
  2300. return new this.constructor( this.x, this.y );
  2301. }
  2302. /**
  2303. * Copies the values of the given vector to this instance.
  2304. *
  2305. * @param {Vector2} v - The vector to copy.
  2306. * @return {Vector2} A reference to this vector.
  2307. */
  2308. copy( v ) {
  2309. this.x = v.x;
  2310. this.y = v.y;
  2311. return this;
  2312. }
  2313. /**
  2314. * Adds the given vector to this instance.
  2315. *
  2316. * @param {Vector2} v - The vector to add.
  2317. * @return {Vector2} A reference to this vector.
  2318. */
  2319. add( v ) {
  2320. this.x += v.x;
  2321. this.y += v.y;
  2322. return this;
  2323. }
  2324. /**
  2325. * Adds the given scalar value to all components of this instance.
  2326. *
  2327. * @param {number} s - The scalar to add.
  2328. * @return {Vector2} A reference to this vector.
  2329. */
  2330. addScalar( s ) {
  2331. this.x += s;
  2332. this.y += s;
  2333. return this;
  2334. }
  2335. /**
  2336. * Adds the given vectors and stores the result in this instance.
  2337. *
  2338. * @param {Vector2} a - The first vector.
  2339. * @param {Vector2} b - The second vector.
  2340. * @return {Vector2} A reference to this vector.
  2341. */
  2342. addVectors( a, b ) {
  2343. this.x = a.x + b.x;
  2344. this.y = a.y + b.y;
  2345. return this;
  2346. }
  2347. /**
  2348. * Adds the given vector scaled by the given factor to this instance.
  2349. *
  2350. * @param {Vector2} v - The vector.
  2351. * @param {number} s - The factor that scales `v`.
  2352. * @return {Vector2} A reference to this vector.
  2353. */
  2354. addScaledVector( v, s ) {
  2355. this.x += v.x * s;
  2356. this.y += v.y * s;
  2357. return this;
  2358. }
  2359. /**
  2360. * Subtracts the given vector from this instance.
  2361. *
  2362. * @param {Vector2} v - The vector to subtract.
  2363. * @return {Vector2} A reference to this vector.
  2364. */
  2365. sub( v ) {
  2366. this.x -= v.x;
  2367. this.y -= v.y;
  2368. return this;
  2369. }
  2370. /**
  2371. * Subtracts the given scalar value from all components of this instance.
  2372. *
  2373. * @param {number} s - The scalar to subtract.
  2374. * @return {Vector2} A reference to this vector.
  2375. */
  2376. subScalar( s ) {
  2377. this.x -= s;
  2378. this.y -= s;
  2379. return this;
  2380. }
  2381. /**
  2382. * Subtracts the given vectors and stores the result in this instance.
  2383. *
  2384. * @param {Vector2} a - The first vector.
  2385. * @param {Vector2} b - The second vector.
  2386. * @return {Vector2} A reference to this vector.
  2387. */
  2388. subVectors( a, b ) {
  2389. this.x = a.x - b.x;
  2390. this.y = a.y - b.y;
  2391. return this;
  2392. }
  2393. /**
  2394. * Multiplies the given vector with this instance.
  2395. *
  2396. * @param {Vector2} v - The vector to multiply.
  2397. * @return {Vector2} A reference to this vector.
  2398. */
  2399. multiply( v ) {
  2400. this.x *= v.x;
  2401. this.y *= v.y;
  2402. return this;
  2403. }
  2404. /**
  2405. * Multiplies the given scalar value with all components of this instance.
  2406. *
  2407. * @param {number} scalar - The scalar to multiply.
  2408. * @return {Vector2} A reference to this vector.
  2409. */
  2410. multiplyScalar( scalar ) {
  2411. this.x *= scalar;
  2412. this.y *= scalar;
  2413. return this;
  2414. }
  2415. /**
  2416. * Divides this instance by the given vector.
  2417. *
  2418. * @param {Vector2} v - The vector to divide.
  2419. * @return {Vector2} A reference to this vector.
  2420. */
  2421. divide( v ) {
  2422. this.x /= v.x;
  2423. this.y /= v.y;
  2424. return this;
  2425. }
  2426. /**
  2427. * Divides this vector by the given scalar.
  2428. *
  2429. * @param {number} scalar - The scalar to divide.
  2430. * @return {Vector2} A reference to this vector.
  2431. */
  2432. divideScalar( scalar ) {
  2433. return this.multiplyScalar( 1 / scalar );
  2434. }
  2435. /**
  2436. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  2437. * the given 3x3 matrix.
  2438. *
  2439. * @param {Matrix3} m - The matrix to apply.
  2440. * @return {Vector2} A reference to this vector.
  2441. */
  2442. applyMatrix3( m ) {
  2443. const x = this.x, y = this.y;
  2444. const e = m.elements;
  2445. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  2446. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  2447. return this;
  2448. }
  2449. /**
  2450. * If this vector's x or y value is greater than the given vector's x or y
  2451. * value, replace that value with the corresponding min value.
  2452. *
  2453. * @param {Vector2} v - The vector.
  2454. * @return {Vector2} A reference to this vector.
  2455. */
  2456. min( v ) {
  2457. this.x = Math.min( this.x, v.x );
  2458. this.y = Math.min( this.y, v.y );
  2459. return this;
  2460. }
  2461. /**
  2462. * If this vector's x or y value is less than the given vector's x or y
  2463. * value, replace that value with the corresponding max value.
  2464. *
  2465. * @param {Vector2} v - The vector.
  2466. * @return {Vector2} A reference to this vector.
  2467. */
  2468. max( v ) {
  2469. this.x = Math.max( this.x, v.x );
  2470. this.y = Math.max( this.y, v.y );
  2471. return this;
  2472. }
  2473. /**
  2474. * If this vector's x or y value is greater than the max vector's x or y
  2475. * value, it is replaced by the corresponding value.
  2476. * If this vector's x or y value is less than the min vector's x or y value,
  2477. * it is replaced by the corresponding value.
  2478. *
  2479. * @param {Vector2} min - The minimum x and y values.
  2480. * @param {Vector2} max - The maximum x and y values in the desired range.
  2481. * @return {Vector2} A reference to this vector.
  2482. */
  2483. clamp( min, max ) {
  2484. // assumes min < max, componentwise
  2485. this.x = clamp( this.x, min.x, max.x );
  2486. this.y = clamp( this.y, min.y, max.y );
  2487. return this;
  2488. }
  2489. /**
  2490. * If this vector's x or y values are greater than the max value, they are
  2491. * replaced by the max value.
  2492. * If this vector's x or y values are less than the min value, they are
  2493. * replaced by the min value.
  2494. *
  2495. * @param {number} minVal - The minimum value the components will be clamped to.
  2496. * @param {number} maxVal - The maximum value the components will be clamped to.
  2497. * @return {Vector2} A reference to this vector.
  2498. */
  2499. clampScalar( minVal, maxVal ) {
  2500. this.x = clamp( this.x, minVal, maxVal );
  2501. this.y = clamp( this.y, minVal, maxVal );
  2502. return this;
  2503. }
  2504. /**
  2505. * If this vector's length is greater than the max value, it is replaced by
  2506. * the max value.
  2507. * If this vector's length is less than the min value, it is replaced by the
  2508. * min value.
  2509. *
  2510. * @param {number} min - The minimum value the vector length will be clamped to.
  2511. * @param {number} max - The maximum value the vector length will be clamped to.
  2512. * @return {Vector2} A reference to this vector.
  2513. */
  2514. clampLength( min, max ) {
  2515. const length = this.length();
  2516. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2517. }
  2518. /**
  2519. * The components of this vector are rounded down to the nearest integer value.
  2520. *
  2521. * @return {Vector2} A reference to this vector.
  2522. */
  2523. floor() {
  2524. this.x = Math.floor( this.x );
  2525. this.y = Math.floor( this.y );
  2526. return this;
  2527. }
  2528. /**
  2529. * The components of this vector are rounded up to the nearest integer value.
  2530. *
  2531. * @return {Vector2} A reference to this vector.
  2532. */
  2533. ceil() {
  2534. this.x = Math.ceil( this.x );
  2535. this.y = Math.ceil( this.y );
  2536. return this;
  2537. }
  2538. /**
  2539. * The components of this vector are rounded to the nearest integer value
  2540. *
  2541. * @return {Vector2} A reference to this vector.
  2542. */
  2543. round() {
  2544. this.x = Math.round( this.x );
  2545. this.y = Math.round( this.y );
  2546. return this;
  2547. }
  2548. /**
  2549. * The components of this vector are rounded towards zero (up if negative,
  2550. * down if positive) to an integer value.
  2551. *
  2552. * @return {Vector2} A reference to this vector.
  2553. */
  2554. roundToZero() {
  2555. this.x = Math.trunc( this.x );
  2556. this.y = Math.trunc( this.y );
  2557. return this;
  2558. }
  2559. /**
  2560. * Inverts this vector - i.e. sets x = -x and y = -y.
  2561. *
  2562. * @return {Vector2} A reference to this vector.
  2563. */
  2564. negate() {
  2565. this.x = - this.x;
  2566. this.y = - this.y;
  2567. return this;
  2568. }
  2569. /**
  2570. * Calculates the dot product of the given vector with this instance.
  2571. *
  2572. * @param {Vector2} v - The vector to compute the dot product with.
  2573. * @return {number} The result of the dot product.
  2574. */
  2575. dot( v ) {
  2576. return this.x * v.x + this.y * v.y;
  2577. }
  2578. /**
  2579. * Calculates the cross product of the given vector with this instance.
  2580. *
  2581. * @param {Vector2} v - The vector to compute the cross product with.
  2582. * @return {number} The result of the cross product.
  2583. */
  2584. cross( v ) {
  2585. return this.x * v.y - this.y * v.x;
  2586. }
  2587. /**
  2588. * Computes the square of the Euclidean length (straight-line length) from
  2589. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  2590. * compare the length squared instead as it is slightly more efficient to calculate.
  2591. *
  2592. * @return {number} The square length of this vector.
  2593. */
  2594. lengthSq() {
  2595. return this.x * this.x + this.y * this.y;
  2596. }
  2597. /**
  2598. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  2599. *
  2600. * @return {number} The length of this vector.
  2601. */
  2602. length() {
  2603. return Math.sqrt( this.x * this.x + this.y * this.y );
  2604. }
  2605. /**
  2606. * Computes the Manhattan length of this vector.
  2607. *
  2608. * @return {number} The length of this vector.
  2609. */
  2610. manhattanLength() {
  2611. return Math.abs( this.x ) + Math.abs( this.y );
  2612. }
  2613. /**
  2614. * Converts this vector to a unit vector - that is, sets it equal to a vector
  2615. * with the same direction as this one, but with a vector length of `1`.
  2616. *
  2617. * @return {Vector2} A reference to this vector.
  2618. */
  2619. normalize() {
  2620. return this.divideScalar( this.length() || 1 );
  2621. }
  2622. /**
  2623. * Computes the angle in radians of this vector with respect to the positive x-axis.
  2624. *
  2625. * @return {number} The angle in radians.
  2626. */
  2627. angle() {
  2628. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  2629. return angle;
  2630. }
  2631. /**
  2632. * Returns the angle between the given vector and this instance in radians.
  2633. *
  2634. * @param {Vector2} v - The vector to compute the angle with.
  2635. * @return {number} The angle in radians.
  2636. */
  2637. angleTo( v ) {
  2638. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2639. if ( denominator === 0 ) return Math.PI / 2;
  2640. const theta = this.dot( v ) / denominator;
  2641. // clamp, to handle numerical problems
  2642. return Math.acos( clamp( theta, -1, 1 ) );
  2643. }
  2644. /**
  2645. * Computes the distance from the given vector to this instance.
  2646. *
  2647. * @param {Vector2} v - The vector to compute the distance to.
  2648. * @return {number} The distance.
  2649. */
  2650. distanceTo( v ) {
  2651. return Math.sqrt( this.distanceToSquared( v ) );
  2652. }
  2653. /**
  2654. * Computes the squared distance from the given vector to this instance.
  2655. * If you are just comparing the distance with another distance, you should compare
  2656. * the distance squared instead as it is slightly more efficient to calculate.
  2657. *
  2658. * @param {Vector2} v - The vector to compute the squared distance to.
  2659. * @return {number} The squared distance.
  2660. */
  2661. distanceToSquared( v ) {
  2662. const dx = this.x - v.x, dy = this.y - v.y;
  2663. return dx * dx + dy * dy;
  2664. }
  2665. /**
  2666. * Computes the Manhattan distance from the given vector to this instance.
  2667. *
  2668. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  2669. * @return {number} The Manhattan distance.
  2670. */
  2671. manhattanDistanceTo( v ) {
  2672. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  2673. }
  2674. /**
  2675. * Sets this vector to a vector with the same direction as this one, but
  2676. * with the specified length.
  2677. *
  2678. * @param {number} length - The new length of this vector.
  2679. * @return {Vector2} A reference to this vector.
  2680. */
  2681. setLength( length ) {
  2682. return this.normalize().multiplyScalar( length );
  2683. }
  2684. /**
  2685. * Linearly interpolates between the given vector and this instance, where
  2686. * alpha is the percent distance along the line - alpha = 0 will be this
  2687. * vector, and alpha = 1 will be the given one.
  2688. *
  2689. * @param {Vector2} v - The vector to interpolate towards.
  2690. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2691. * @return {Vector2} A reference to this vector.
  2692. */
  2693. lerp( v, alpha ) {
  2694. this.x += ( v.x - this.x ) * alpha;
  2695. this.y += ( v.y - this.y ) * alpha;
  2696. return this;
  2697. }
  2698. /**
  2699. * Linearly interpolates between the given vectors, where alpha is the percent
  2700. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  2701. * be the second one. The result is stored in this instance.
  2702. *
  2703. * @param {Vector2} v1 - The first vector.
  2704. * @param {Vector2} v2 - The second vector.
  2705. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2706. * @return {Vector2} A reference to this vector.
  2707. */
  2708. lerpVectors( v1, v2, alpha ) {
  2709. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2710. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2711. return this;
  2712. }
  2713. /**
  2714. * Returns `true` if this vector is equal with the given one.
  2715. *
  2716. * @param {Vector2} v - The vector to test for equality.
  2717. * @return {boolean} Whether this vector is equal with the given one.
  2718. */
  2719. equals( v ) {
  2720. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  2721. }
  2722. /**
  2723. * Sets this vector's x value to be `array[ offset ]` and y
  2724. * value to be `array[ offset + 1 ]`.
  2725. *
  2726. * @param {Array<number>} array - An array holding the vector component values.
  2727. * @param {number} [offset=0] - The offset into the array.
  2728. * @return {Vector2} A reference to this vector.
  2729. */
  2730. fromArray( array, offset = 0 ) {
  2731. this.x = array[ offset ];
  2732. this.y = array[ offset + 1 ];
  2733. return this;
  2734. }
  2735. /**
  2736. * Writes the components of this vector to the given array. If no array is provided,
  2737. * the method returns a new instance.
  2738. *
  2739. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  2740. * @param {number} [offset=0] - Index of the first element in the array.
  2741. * @return {Array<number>} The vector components.
  2742. */
  2743. toArray( array = [], offset = 0 ) {
  2744. array[ offset ] = this.x;
  2745. array[ offset + 1 ] = this.y;
  2746. return array;
  2747. }
  2748. /**
  2749. * Sets the components of this vector from the given buffer attribute.
  2750. *
  2751. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  2752. * @param {number} index - The index into the attribute.
  2753. * @return {Vector2} A reference to this vector.
  2754. */
  2755. fromBufferAttribute( attribute, index ) {
  2756. this.x = attribute.getX( index );
  2757. this.y = attribute.getY( index );
  2758. return this;
  2759. }
  2760. /**
  2761. * Rotates this vector around the given center by the given angle.
  2762. *
  2763. * @param {Vector2} center - The point around which to rotate.
  2764. * @param {number} angle - The angle to rotate, in radians.
  2765. * @return {Vector2} A reference to this vector.
  2766. */
  2767. rotateAround( center, angle ) {
  2768. const c = Math.cos( angle ), s = Math.sin( angle );
  2769. const x = this.x - center.x;
  2770. const y = this.y - center.y;
  2771. this.x = x * c - y * s + center.x;
  2772. this.y = x * s + y * c + center.y;
  2773. return this;
  2774. }
  2775. /**
  2776. * Sets each component of this vector to a pseudo-random value between `0` and
  2777. * `1`, excluding `1`.
  2778. *
  2779. * @return {Vector2} A reference to this vector.
  2780. */
  2781. random() {
  2782. this.x = Math.random();
  2783. this.y = Math.random();
  2784. return this;
  2785. }
  2786. *[ Symbol.iterator ]() {
  2787. yield this.x;
  2788. yield this.y;
  2789. }
  2790. }
  2791. /**
  2792. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  2793. *
  2794. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  2795. * the corresponding order.
  2796. *
  2797. * Note that three.js expects Quaternions to be normalized.
  2798. * ```js
  2799. * const quaternion = new THREE.Quaternion();
  2800. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  2801. *
  2802. * const vector = new THREE.Vector3( 1, 0, 0 );
  2803. * vector.applyQuaternion( quaternion );
  2804. * ```
  2805. */
  2806. class Quaternion {
  2807. /**
  2808. * Constructs a new quaternion.
  2809. *
  2810. * @param {number} [x=0] - The x value of this quaternion.
  2811. * @param {number} [y=0] - The y value of this quaternion.
  2812. * @param {number} [z=0] - The z value of this quaternion.
  2813. * @param {number} [w=1] - The w value of this quaternion.
  2814. */
  2815. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2816. /**
  2817. * This flag can be used for type testing.
  2818. *
  2819. * @type {boolean}
  2820. * @readonly
  2821. * @default true
  2822. */
  2823. this.isQuaternion = true;
  2824. this._x = x;
  2825. this._y = y;
  2826. this._z = z;
  2827. this._w = w;
  2828. }
  2829. /**
  2830. * Interpolates between two quaternions via SLERP. This implementation assumes the
  2831. * quaternion data are managed in flat arrays.
  2832. *
  2833. * @param {Array<number>} dst - The destination array.
  2834. * @param {number} dstOffset - An offset into the destination array.
  2835. * @param {Array<number>} src0 - The source array of the first quaternion.
  2836. * @param {number} srcOffset0 - An offset into the first source array.
  2837. * @param {Array<number>} src1 - The source array of the second quaternion.
  2838. * @param {number} srcOffset1 - An offset into the second source array.
  2839. * @param {number} t - The interpolation factor in the range `[0,1]`.
  2840. * @see {@link Quaternion#slerp}
  2841. */
  2842. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2843. // fuzz-free, array-based Quaternion SLERP operation
  2844. let x0 = src0[ srcOffset0 + 0 ],
  2845. y0 = src0[ srcOffset0 + 1 ],
  2846. z0 = src0[ srcOffset0 + 2 ],
  2847. w0 = src0[ srcOffset0 + 3 ];
  2848. const x1 = src1[ srcOffset1 + 0 ],
  2849. y1 = src1[ srcOffset1 + 1 ],
  2850. z1 = src1[ srcOffset1 + 2 ],
  2851. w1 = src1[ srcOffset1 + 3 ];
  2852. if ( t === 0 ) {
  2853. dst[ dstOffset + 0 ] = x0;
  2854. dst[ dstOffset + 1 ] = y0;
  2855. dst[ dstOffset + 2 ] = z0;
  2856. dst[ dstOffset + 3 ] = w0;
  2857. return;
  2858. }
  2859. if ( t === 1 ) {
  2860. dst[ dstOffset + 0 ] = x1;
  2861. dst[ dstOffset + 1 ] = y1;
  2862. dst[ dstOffset + 2 ] = z1;
  2863. dst[ dstOffset + 3 ] = w1;
  2864. return;
  2865. }
  2866. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2867. let s = 1 - t;
  2868. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2869. dir = ( cos >= 0 ? 1 : -1 ),
  2870. sqrSin = 1 - cos * cos;
  2871. // Skip the Slerp for tiny steps to avoid numeric problems:
  2872. if ( sqrSin > Number.EPSILON ) {
  2873. const sin = Math.sqrt( sqrSin ),
  2874. len = Math.atan2( sin, cos * dir );
  2875. s = Math.sin( s * len ) / sin;
  2876. t = Math.sin( t * len ) / sin;
  2877. }
  2878. const tDir = t * dir;
  2879. x0 = x0 * s + x1 * tDir;
  2880. y0 = y0 * s + y1 * tDir;
  2881. z0 = z0 * s + z1 * tDir;
  2882. w0 = w0 * s + w1 * tDir;
  2883. // Normalize in case we just did a lerp:
  2884. if ( s === 1 - t ) {
  2885. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2886. x0 *= f;
  2887. y0 *= f;
  2888. z0 *= f;
  2889. w0 *= f;
  2890. }
  2891. }
  2892. dst[ dstOffset ] = x0;
  2893. dst[ dstOffset + 1 ] = y0;
  2894. dst[ dstOffset + 2 ] = z0;
  2895. dst[ dstOffset + 3 ] = w0;
  2896. }
  2897. /**
  2898. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  2899. * in flat arrays.
  2900. *
  2901. * @param {Array<number>} dst - The destination array.
  2902. * @param {number} dstOffset - An offset into the destination array.
  2903. * @param {Array<number>} src0 - The source array of the first quaternion.
  2904. * @param {number} srcOffset0 - An offset into the first source array.
  2905. * @param {Array<number>} src1 - The source array of the second quaternion.
  2906. * @param {number} srcOffset1 - An offset into the second source array.
  2907. * @return {Array<number>} The destination array.
  2908. * @see {@link Quaternion#multiplyQuaternions}.
  2909. */
  2910. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2911. const x0 = src0[ srcOffset0 ];
  2912. const y0 = src0[ srcOffset0 + 1 ];
  2913. const z0 = src0[ srcOffset0 + 2 ];
  2914. const w0 = src0[ srcOffset0 + 3 ];
  2915. const x1 = src1[ srcOffset1 ];
  2916. const y1 = src1[ srcOffset1 + 1 ];
  2917. const z1 = src1[ srcOffset1 + 2 ];
  2918. const w1 = src1[ srcOffset1 + 3 ];
  2919. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2920. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2921. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2922. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2923. return dst;
  2924. }
  2925. /**
  2926. * The x value of this quaternion.
  2927. *
  2928. * @type {number}
  2929. * @default 0
  2930. */
  2931. get x() {
  2932. return this._x;
  2933. }
  2934. set x( value ) {
  2935. this._x = value;
  2936. this._onChangeCallback();
  2937. }
  2938. /**
  2939. * The y value of this quaternion.
  2940. *
  2941. * @type {number}
  2942. * @default 0
  2943. */
  2944. get y() {
  2945. return this._y;
  2946. }
  2947. set y( value ) {
  2948. this._y = value;
  2949. this._onChangeCallback();
  2950. }
  2951. /**
  2952. * The z value of this quaternion.
  2953. *
  2954. * @type {number}
  2955. * @default 0
  2956. */
  2957. get z() {
  2958. return this._z;
  2959. }
  2960. set z( value ) {
  2961. this._z = value;
  2962. this._onChangeCallback();
  2963. }
  2964. /**
  2965. * The w value of this quaternion.
  2966. *
  2967. * @type {number}
  2968. * @default 1
  2969. */
  2970. get w() {
  2971. return this._w;
  2972. }
  2973. set w( value ) {
  2974. this._w = value;
  2975. this._onChangeCallback();
  2976. }
  2977. /**
  2978. * Sets the quaternion components.
  2979. *
  2980. * @param {number} x - The x value of this quaternion.
  2981. * @param {number} y - The y value of this quaternion.
  2982. * @param {number} z - The z value of this quaternion.
  2983. * @param {number} w - The w value of this quaternion.
  2984. * @return {Quaternion} A reference to this quaternion.
  2985. */
  2986. set( x, y, z, w ) {
  2987. this._x = x;
  2988. this._y = y;
  2989. this._z = z;
  2990. this._w = w;
  2991. this._onChangeCallback();
  2992. return this;
  2993. }
  2994. /**
  2995. * Returns a new quaternion with copied values from this instance.
  2996. *
  2997. * @return {Quaternion} A clone of this instance.
  2998. */
  2999. clone() {
  3000. return new this.constructor( this._x, this._y, this._z, this._w );
  3001. }
  3002. /**
  3003. * Copies the values of the given quaternion to this instance.
  3004. *
  3005. * @param {Quaternion} quaternion - The quaternion to copy.
  3006. * @return {Quaternion} A reference to this quaternion.
  3007. */
  3008. copy( quaternion ) {
  3009. this._x = quaternion.x;
  3010. this._y = quaternion.y;
  3011. this._z = quaternion.z;
  3012. this._w = quaternion.w;
  3013. this._onChangeCallback();
  3014. return this;
  3015. }
  3016. /**
  3017. * Sets this quaternion from the rotation specified by the given
  3018. * Euler angles.
  3019. *
  3020. * @param {Euler} euler - The Euler angles.
  3021. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3022. * @return {Quaternion} A reference to this quaternion.
  3023. */
  3024. setFromEuler( euler, update = true ) {
  3025. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3026. // http://www.mathworks.com/matlabcentral/fileexchange/
  3027. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3028. // content/SpinCalc.m
  3029. const cos = Math.cos;
  3030. const sin = Math.sin;
  3031. const c1 = cos( x / 2 );
  3032. const c2 = cos( y / 2 );
  3033. const c3 = cos( z / 2 );
  3034. const s1 = sin( x / 2 );
  3035. const s2 = sin( y / 2 );
  3036. const s3 = sin( z / 2 );
  3037. switch ( order ) {
  3038. case 'XYZ':
  3039. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3040. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3041. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3042. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3043. break;
  3044. case 'YXZ':
  3045. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3046. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3047. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3048. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3049. break;
  3050. case 'ZXY':
  3051. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3052. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3053. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3054. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3055. break;
  3056. case 'ZYX':
  3057. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3058. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3059. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3060. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3061. break;
  3062. case 'YZX':
  3063. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3064. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3065. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3066. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3067. break;
  3068. case 'XZY':
  3069. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3070. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3071. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3072. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3073. break;
  3074. default:
  3075. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3076. }
  3077. if ( update === true ) this._onChangeCallback();
  3078. return this;
  3079. }
  3080. /**
  3081. * Sets this quaternion from the given axis and angle.
  3082. *
  3083. * @param {Vector3} axis - The normalized axis.
  3084. * @param {number} angle - The angle in radians.
  3085. * @return {Quaternion} A reference to this quaternion.
  3086. */
  3087. setFromAxisAngle( axis, angle ) {
  3088. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3089. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3090. this._x = axis.x * s;
  3091. this._y = axis.y * s;
  3092. this._z = axis.z * s;
  3093. this._w = Math.cos( halfAngle );
  3094. this._onChangeCallback();
  3095. return this;
  3096. }
  3097. /**
  3098. * Sets this quaternion from the given rotation matrix.
  3099. *
  3100. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3101. * @return {Quaternion} A reference to this quaternion.
  3102. */
  3103. setFromRotationMatrix( m ) {
  3104. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3105. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3106. const te = m.elements,
  3107. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3108. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3109. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3110. trace = m11 + m22 + m33;
  3111. if ( trace > 0 ) {
  3112. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3113. this._w = 0.25 / s;
  3114. this._x = ( m32 - m23 ) * s;
  3115. this._y = ( m13 - m31 ) * s;
  3116. this._z = ( m21 - m12 ) * s;
  3117. } else if ( m11 > m22 && m11 > m33 ) {
  3118. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3119. this._w = ( m32 - m23 ) / s;
  3120. this._x = 0.25 * s;
  3121. this._y = ( m12 + m21 ) / s;
  3122. this._z = ( m13 + m31 ) / s;
  3123. } else if ( m22 > m33 ) {
  3124. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3125. this._w = ( m13 - m31 ) / s;
  3126. this._x = ( m12 + m21 ) / s;
  3127. this._y = 0.25 * s;
  3128. this._z = ( m23 + m32 ) / s;
  3129. } else {
  3130. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3131. this._w = ( m21 - m12 ) / s;
  3132. this._x = ( m13 + m31 ) / s;
  3133. this._y = ( m23 + m32 ) / s;
  3134. this._z = 0.25 * s;
  3135. }
  3136. this._onChangeCallback();
  3137. return this;
  3138. }
  3139. /**
  3140. * Sets this quaternion to the rotation required to rotate the direction vector
  3141. * `vFrom` to the direction vector `vTo`.
  3142. *
  3143. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3144. * @param {Vector3} vTo - The second (normalized) direction vector.
  3145. * @return {Quaternion} A reference to this quaternion.
  3146. */
  3147. setFromUnitVectors( vFrom, vTo ) {
  3148. // assumes direction vectors vFrom and vTo are normalized
  3149. let r = vFrom.dot( vTo ) + 1;
  3150. if ( r < 1e-8 ) { // the epsilon value has been discussed in #31286
  3151. // vFrom and vTo point in opposite directions
  3152. r = 0;
  3153. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3154. this._x = - vFrom.y;
  3155. this._y = vFrom.x;
  3156. this._z = 0;
  3157. this._w = r;
  3158. } else {
  3159. this._x = 0;
  3160. this._y = - vFrom.z;
  3161. this._z = vFrom.y;
  3162. this._w = r;
  3163. }
  3164. } else {
  3165. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3166. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3167. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3168. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3169. this._w = r;
  3170. }
  3171. return this.normalize();
  3172. }
  3173. /**
  3174. * Returns the angle between this quaternion and the given one in radians.
  3175. *
  3176. * @param {Quaternion} q - The quaternion to compute the angle with.
  3177. * @return {number} The angle in radians.
  3178. */
  3179. angleTo( q ) {
  3180. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3181. }
  3182. /**
  3183. * Rotates this quaternion by a given angular step to the given quaternion.
  3184. * The method ensures that the final quaternion will not overshoot `q`.
  3185. *
  3186. * @param {Quaternion} q - The target quaternion.
  3187. * @param {number} step - The angular step in radians.
  3188. * @return {Quaternion} A reference to this quaternion.
  3189. */
  3190. rotateTowards( q, step ) {
  3191. const angle = this.angleTo( q );
  3192. if ( angle === 0 ) return this;
  3193. const t = Math.min( 1, step / angle );
  3194. this.slerp( q, t );
  3195. return this;
  3196. }
  3197. /**
  3198. * Sets this quaternion to the identity quaternion; that is, to the
  3199. * quaternion that represents "no rotation".
  3200. *
  3201. * @return {Quaternion} A reference to this quaternion.
  3202. */
  3203. identity() {
  3204. return this.set( 0, 0, 0, 1 );
  3205. }
  3206. /**
  3207. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  3208. * quaternion is assumed to have unit length.
  3209. *
  3210. * @return {Quaternion} A reference to this quaternion.
  3211. */
  3212. invert() {
  3213. return this.conjugate();
  3214. }
  3215. /**
  3216. * Returns the rotational conjugate of this quaternion. The conjugate of a
  3217. * quaternion represents the same rotation in the opposite direction about
  3218. * the rotational axis.
  3219. *
  3220. * @return {Quaternion} A reference to this quaternion.
  3221. */
  3222. conjugate() {
  3223. this._x *= -1;
  3224. this._y *= -1;
  3225. this._z *= -1;
  3226. this._onChangeCallback();
  3227. return this;
  3228. }
  3229. /**
  3230. * Calculates the dot product of this quaternion and the given one.
  3231. *
  3232. * @param {Quaternion} v - The quaternion to compute the dot product with.
  3233. * @return {number} The result of the dot product.
  3234. */
  3235. dot( v ) {
  3236. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  3237. }
  3238. /**
  3239. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  3240. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  3241. * lengths of two quaternions, as this is a slightly more efficient calculation than
  3242. * {@link Quaternion#length}.
  3243. *
  3244. * @return {number} The squared Euclidean length.
  3245. */
  3246. lengthSq() {
  3247. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  3248. }
  3249. /**
  3250. * Computes the Euclidean length (straight-line length) of this quaternion,
  3251. * considered as a 4 dimensional vector.
  3252. *
  3253. * @return {number} The Euclidean length.
  3254. */
  3255. length() {
  3256. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  3257. }
  3258. /**
  3259. * Normalizes this quaternion - that is, calculated the quaternion that performs
  3260. * the same rotation as this one, but has a length equal to `1`.
  3261. *
  3262. * @return {Quaternion} A reference to this quaternion.
  3263. */
  3264. normalize() {
  3265. let l = this.length();
  3266. if ( l === 0 ) {
  3267. this._x = 0;
  3268. this._y = 0;
  3269. this._z = 0;
  3270. this._w = 1;
  3271. } else {
  3272. l = 1 / l;
  3273. this._x = this._x * l;
  3274. this._y = this._y * l;
  3275. this._z = this._z * l;
  3276. this._w = this._w * l;
  3277. }
  3278. this._onChangeCallback();
  3279. return this;
  3280. }
  3281. /**
  3282. * Multiplies this quaternion by the given one.
  3283. *
  3284. * @param {Quaternion} q - The quaternion.
  3285. * @return {Quaternion} A reference to this quaternion.
  3286. */
  3287. multiply( q ) {
  3288. return this.multiplyQuaternions( this, q );
  3289. }
  3290. /**
  3291. * Pre-multiplies this quaternion by the given one.
  3292. *
  3293. * @param {Quaternion} q - The quaternion.
  3294. * @return {Quaternion} A reference to this quaternion.
  3295. */
  3296. premultiply( q ) {
  3297. return this.multiplyQuaternions( q, this );
  3298. }
  3299. /**
  3300. * Multiplies the given quaternions and stores the result in this instance.
  3301. *
  3302. * @param {Quaternion} a - The first quaternion.
  3303. * @param {Quaternion} b - The second quaternion.
  3304. * @return {Quaternion} A reference to this quaternion.
  3305. */
  3306. multiplyQuaternions( a, b ) {
  3307. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3308. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  3309. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  3310. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3311. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3312. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3313. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3314. this._onChangeCallback();
  3315. return this;
  3316. }
  3317. /**
  3318. * Performs a spherical linear interpolation between quaternions.
  3319. *
  3320. * @param {Quaternion} qb - The target quaternion.
  3321. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3322. * @return {Quaternion} A reference to this quaternion.
  3323. */
  3324. slerp( qb, t ) {
  3325. if ( t === 0 ) return this;
  3326. if ( t === 1 ) return this.copy( qb );
  3327. const x = this._x, y = this._y, z = this._z, w = this._w;
  3328. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  3329. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  3330. if ( cosHalfTheta < 0 ) {
  3331. this._w = - qb._w;
  3332. this._x = - qb._x;
  3333. this._y = - qb._y;
  3334. this._z = - qb._z;
  3335. cosHalfTheta = - cosHalfTheta;
  3336. } else {
  3337. this.copy( qb );
  3338. }
  3339. if ( cosHalfTheta >= 1.0 ) {
  3340. this._w = w;
  3341. this._x = x;
  3342. this._y = y;
  3343. this._z = z;
  3344. return this;
  3345. }
  3346. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  3347. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  3348. const s = 1 - t;
  3349. this._w = s * w + t * this._w;
  3350. this._x = s * x + t * this._x;
  3351. this._y = s * y + t * this._y;
  3352. this._z = s * z + t * this._z;
  3353. this.normalize(); // normalize calls _onChangeCallback()
  3354. return this;
  3355. }
  3356. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  3357. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  3358. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  3359. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  3360. this._w = ( w * ratioA + this._w * ratioB );
  3361. this._x = ( x * ratioA + this._x * ratioB );
  3362. this._y = ( y * ratioA + this._y * ratioB );
  3363. this._z = ( z * ratioA + this._z * ratioB );
  3364. this._onChangeCallback();
  3365. return this;
  3366. }
  3367. /**
  3368. * Performs a spherical linear interpolation between the given quaternions
  3369. * and stores the result in this quaternion.
  3370. *
  3371. * @param {Quaternion} qa - The source quaternion.
  3372. * @param {Quaternion} qb - The target quaternion.
  3373. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3374. * @return {Quaternion} A reference to this quaternion.
  3375. */
  3376. slerpQuaternions( qa, qb, t ) {
  3377. return this.copy( qa ).slerp( qb, t );
  3378. }
  3379. /**
  3380. * Sets this quaternion to a uniformly random, normalized quaternion.
  3381. *
  3382. * @return {Quaternion} A reference to this quaternion.
  3383. */
  3384. random() {
  3385. // Ken Shoemake
  3386. // Uniform random rotations
  3387. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  3388. const theta1 = 2 * Math.PI * Math.random();
  3389. const theta2 = 2 * Math.PI * Math.random();
  3390. const x0 = Math.random();
  3391. const r1 = Math.sqrt( 1 - x0 );
  3392. const r2 = Math.sqrt( x0 );
  3393. return this.set(
  3394. r1 * Math.sin( theta1 ),
  3395. r1 * Math.cos( theta1 ),
  3396. r2 * Math.sin( theta2 ),
  3397. r2 * Math.cos( theta2 ),
  3398. );
  3399. }
  3400. /**
  3401. * Returns `true` if this quaternion is equal with the given one.
  3402. *
  3403. * @param {Quaternion} quaternion - The quaternion to test for equality.
  3404. * @return {boolean} Whether this quaternion is equal with the given one.
  3405. */
  3406. equals( quaternion ) {
  3407. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  3408. }
  3409. /**
  3410. * Sets this quaternion's components from the given array.
  3411. *
  3412. * @param {Array<number>} array - An array holding the quaternion component values.
  3413. * @param {number} [offset=0] - The offset into the array.
  3414. * @return {Quaternion} A reference to this quaternion.
  3415. */
  3416. fromArray( array, offset = 0 ) {
  3417. this._x = array[ offset ];
  3418. this._y = array[ offset + 1 ];
  3419. this._z = array[ offset + 2 ];
  3420. this._w = array[ offset + 3 ];
  3421. this._onChangeCallback();
  3422. return this;
  3423. }
  3424. /**
  3425. * Writes the components of this quaternion to the given array. If no array is provided,
  3426. * the method returns a new instance.
  3427. *
  3428. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  3429. * @param {number} [offset=0] - Index of the first element in the array.
  3430. * @return {Array<number>} The quaternion components.
  3431. */
  3432. toArray( array = [], offset = 0 ) {
  3433. array[ offset ] = this._x;
  3434. array[ offset + 1 ] = this._y;
  3435. array[ offset + 2 ] = this._z;
  3436. array[ offset + 3 ] = this._w;
  3437. return array;
  3438. }
  3439. /**
  3440. * Sets the components of this quaternion from the given buffer attribute.
  3441. *
  3442. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  3443. * @param {number} index - The index into the attribute.
  3444. * @return {Quaternion} A reference to this quaternion.
  3445. */
  3446. fromBufferAttribute( attribute, index ) {
  3447. this._x = attribute.getX( index );
  3448. this._y = attribute.getY( index );
  3449. this._z = attribute.getZ( index );
  3450. this._w = attribute.getW( index );
  3451. this._onChangeCallback();
  3452. return this;
  3453. }
  3454. /**
  3455. * This methods defines the serialization result of this class. Returns the
  3456. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  3457. *
  3458. * @return {Array<number>} The serialized quaternion.
  3459. */
  3460. toJSON() {
  3461. return this.toArray();
  3462. }
  3463. _onChange( callback ) {
  3464. this._onChangeCallback = callback;
  3465. return this;
  3466. }
  3467. _onChangeCallback() {}
  3468. *[ Symbol.iterator ]() {
  3469. yield this._x;
  3470. yield this._y;
  3471. yield this._z;
  3472. yield this._w;
  3473. }
  3474. }
  3475. /**
  3476. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  3477. * (labeled x, y and z), which can be used to represent a number of things, such as:
  3478. *
  3479. * - A point in 3D space.
  3480. * - A direction and length in 3D space. In three.js the length will
  3481. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  3482. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  3483. * - Any arbitrary ordered triplet of numbers.
  3484. *
  3485. * There are other things a 3D vector can be used to represent, such as
  3486. * momentum vectors and so on, however these are the most
  3487. * common uses in three.js.
  3488. *
  3489. * Iterating through a vector instance will yield its components `(x, y, z)` in
  3490. * the corresponding order.
  3491. * ```js
  3492. * const a = new THREE.Vector3( 0, 1, 0 );
  3493. *
  3494. * //no arguments; will be initialised to (0, 0, 0)
  3495. * const b = new THREE.Vector3( );
  3496. *
  3497. * const d = a.distanceTo( b );
  3498. * ```
  3499. */
  3500. class Vector3 {
  3501. /**
  3502. * Constructs a new 3D vector.
  3503. *
  3504. * @param {number} [x=0] - The x value of this vector.
  3505. * @param {number} [y=0] - The y value of this vector.
  3506. * @param {number} [z=0] - The z value of this vector.
  3507. */
  3508. constructor( x = 0, y = 0, z = 0 ) {
  3509. /**
  3510. * This flag can be used for type testing.
  3511. *
  3512. * @type {boolean}
  3513. * @readonly
  3514. * @default true
  3515. */
  3516. Vector3.prototype.isVector3 = true;
  3517. /**
  3518. * The x value of this vector.
  3519. *
  3520. * @type {number}
  3521. */
  3522. this.x = x;
  3523. /**
  3524. * The y value of this vector.
  3525. *
  3526. * @type {number}
  3527. */
  3528. this.y = y;
  3529. /**
  3530. * The z value of this vector.
  3531. *
  3532. * @type {number}
  3533. */
  3534. this.z = z;
  3535. }
  3536. /**
  3537. * Sets the vector components.
  3538. *
  3539. * @param {number} x - The value of the x component.
  3540. * @param {number} y - The value of the y component.
  3541. * @param {number} z - The value of the z component.
  3542. * @return {Vector3} A reference to this vector.
  3543. */
  3544. set( x, y, z ) {
  3545. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  3546. this.x = x;
  3547. this.y = y;
  3548. this.z = z;
  3549. return this;
  3550. }
  3551. /**
  3552. * Sets the vector components to the same value.
  3553. *
  3554. * @param {number} scalar - The value to set for all vector components.
  3555. * @return {Vector3} A reference to this vector.
  3556. */
  3557. setScalar( scalar ) {
  3558. this.x = scalar;
  3559. this.y = scalar;
  3560. this.z = scalar;
  3561. return this;
  3562. }
  3563. /**
  3564. * Sets the vector's x component to the given value
  3565. *
  3566. * @param {number} x - The value to set.
  3567. * @return {Vector3} A reference to this vector.
  3568. */
  3569. setX( x ) {
  3570. this.x = x;
  3571. return this;
  3572. }
  3573. /**
  3574. * Sets the vector's y component to the given value
  3575. *
  3576. * @param {number} y - The value to set.
  3577. * @return {Vector3} A reference to this vector.
  3578. */
  3579. setY( y ) {
  3580. this.y = y;
  3581. return this;
  3582. }
  3583. /**
  3584. * Sets the vector's z component to the given value
  3585. *
  3586. * @param {number} z - The value to set.
  3587. * @return {Vector3} A reference to this vector.
  3588. */
  3589. setZ( z ) {
  3590. this.z = z;
  3591. return this;
  3592. }
  3593. /**
  3594. * Allows to set a vector component with an index.
  3595. *
  3596. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3597. * @param {number} value - The value to set.
  3598. * @return {Vector3} A reference to this vector.
  3599. */
  3600. setComponent( index, value ) {
  3601. switch ( index ) {
  3602. case 0: this.x = value; break;
  3603. case 1: this.y = value; break;
  3604. case 2: this.z = value; break;
  3605. default: throw new Error( 'index is out of range: ' + index );
  3606. }
  3607. return this;
  3608. }
  3609. /**
  3610. * Returns the value of the vector component which matches the given index.
  3611. *
  3612. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3613. * @return {number} A vector component value.
  3614. */
  3615. getComponent( index ) {
  3616. switch ( index ) {
  3617. case 0: return this.x;
  3618. case 1: return this.y;
  3619. case 2: return this.z;
  3620. default: throw new Error( 'index is out of range: ' + index );
  3621. }
  3622. }
  3623. /**
  3624. * Returns a new vector with copied values from this instance.
  3625. *
  3626. * @return {Vector3} A clone of this instance.
  3627. */
  3628. clone() {
  3629. return new this.constructor( this.x, this.y, this.z );
  3630. }
  3631. /**
  3632. * Copies the values of the given vector to this instance.
  3633. *
  3634. * @param {Vector3} v - The vector to copy.
  3635. * @return {Vector3} A reference to this vector.
  3636. */
  3637. copy( v ) {
  3638. this.x = v.x;
  3639. this.y = v.y;
  3640. this.z = v.z;
  3641. return this;
  3642. }
  3643. /**
  3644. * Adds the given vector to this instance.
  3645. *
  3646. * @param {Vector3} v - The vector to add.
  3647. * @return {Vector3} A reference to this vector.
  3648. */
  3649. add( v ) {
  3650. this.x += v.x;
  3651. this.y += v.y;
  3652. this.z += v.z;
  3653. return this;
  3654. }
  3655. /**
  3656. * Adds the given scalar value to all components of this instance.
  3657. *
  3658. * @param {number} s - The scalar to add.
  3659. * @return {Vector3} A reference to this vector.
  3660. */
  3661. addScalar( s ) {
  3662. this.x += s;
  3663. this.y += s;
  3664. this.z += s;
  3665. return this;
  3666. }
  3667. /**
  3668. * Adds the given vectors and stores the result in this instance.
  3669. *
  3670. * @param {Vector3} a - The first vector.
  3671. * @param {Vector3} b - The second vector.
  3672. * @return {Vector3} A reference to this vector.
  3673. */
  3674. addVectors( a, b ) {
  3675. this.x = a.x + b.x;
  3676. this.y = a.y + b.y;
  3677. this.z = a.z + b.z;
  3678. return this;
  3679. }
  3680. /**
  3681. * Adds the given vector scaled by the given factor to this instance.
  3682. *
  3683. * @param {Vector3|Vector4} v - The vector.
  3684. * @param {number} s - The factor that scales `v`.
  3685. * @return {Vector3} A reference to this vector.
  3686. */
  3687. addScaledVector( v, s ) {
  3688. this.x += v.x * s;
  3689. this.y += v.y * s;
  3690. this.z += v.z * s;
  3691. return this;
  3692. }
  3693. /**
  3694. * Subtracts the given vector from this instance.
  3695. *
  3696. * @param {Vector3} v - The vector to subtract.
  3697. * @return {Vector3} A reference to this vector.
  3698. */
  3699. sub( v ) {
  3700. this.x -= v.x;
  3701. this.y -= v.y;
  3702. this.z -= v.z;
  3703. return this;
  3704. }
  3705. /**
  3706. * Subtracts the given scalar value from all components of this instance.
  3707. *
  3708. * @param {number} s - The scalar to subtract.
  3709. * @return {Vector3} A reference to this vector.
  3710. */
  3711. subScalar( s ) {
  3712. this.x -= s;
  3713. this.y -= s;
  3714. this.z -= s;
  3715. return this;
  3716. }
  3717. /**
  3718. * Subtracts the given vectors and stores the result in this instance.
  3719. *
  3720. * @param {Vector3} a - The first vector.
  3721. * @param {Vector3} b - The second vector.
  3722. * @return {Vector3} A reference to this vector.
  3723. */
  3724. subVectors( a, b ) {
  3725. this.x = a.x - b.x;
  3726. this.y = a.y - b.y;
  3727. this.z = a.z - b.z;
  3728. return this;
  3729. }
  3730. /**
  3731. * Multiplies the given vector with this instance.
  3732. *
  3733. * @param {Vector3} v - The vector to multiply.
  3734. * @return {Vector3} A reference to this vector.
  3735. */
  3736. multiply( v ) {
  3737. this.x *= v.x;
  3738. this.y *= v.y;
  3739. this.z *= v.z;
  3740. return this;
  3741. }
  3742. /**
  3743. * Multiplies the given scalar value with all components of this instance.
  3744. *
  3745. * @param {number} scalar - The scalar to multiply.
  3746. * @return {Vector3} A reference to this vector.
  3747. */
  3748. multiplyScalar( scalar ) {
  3749. this.x *= scalar;
  3750. this.y *= scalar;
  3751. this.z *= scalar;
  3752. return this;
  3753. }
  3754. /**
  3755. * Multiplies the given vectors and stores the result in this instance.
  3756. *
  3757. * @param {Vector3} a - The first vector.
  3758. * @param {Vector3} b - The second vector.
  3759. * @return {Vector3} A reference to this vector.
  3760. */
  3761. multiplyVectors( a, b ) {
  3762. this.x = a.x * b.x;
  3763. this.y = a.y * b.y;
  3764. this.z = a.z * b.z;
  3765. return this;
  3766. }
  3767. /**
  3768. * Applies the given Euler rotation to this vector.
  3769. *
  3770. * @param {Euler} euler - The Euler angles.
  3771. * @return {Vector3} A reference to this vector.
  3772. */
  3773. applyEuler( euler ) {
  3774. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  3775. }
  3776. /**
  3777. * Applies a rotation specified by an axis and an angle to this vector.
  3778. *
  3779. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  3780. * @param {number} angle - The angle in radians.
  3781. * @return {Vector3} A reference to this vector.
  3782. */
  3783. applyAxisAngle( axis, angle ) {
  3784. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  3785. }
  3786. /**
  3787. * Multiplies this vector with the given 3x3 matrix.
  3788. *
  3789. * @param {Matrix3} m - The 3x3 matrix.
  3790. * @return {Vector3} A reference to this vector.
  3791. */
  3792. applyMatrix3( m ) {
  3793. const x = this.x, y = this.y, z = this.z;
  3794. const e = m.elements;
  3795. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  3796. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  3797. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  3798. return this;
  3799. }
  3800. /**
  3801. * Multiplies this vector by the given normal matrix and normalizes
  3802. * the result.
  3803. *
  3804. * @param {Matrix3} m - The normal matrix.
  3805. * @return {Vector3} A reference to this vector.
  3806. */
  3807. applyNormalMatrix( m ) {
  3808. return this.applyMatrix3( m ).normalize();
  3809. }
  3810. /**
  3811. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  3812. * divides by perspective.
  3813. *
  3814. * @param {Matrix4} m - The matrix to apply.
  3815. * @return {Vector3} A reference to this vector.
  3816. */
  3817. applyMatrix4( m ) {
  3818. const x = this.x, y = this.y, z = this.z;
  3819. const e = m.elements;
  3820. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  3821. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  3822. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  3823. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  3824. return this;
  3825. }
  3826. /**
  3827. * Applies the given Quaternion to this vector.
  3828. *
  3829. * @param {Quaternion} q - The Quaternion.
  3830. * @return {Vector3} A reference to this vector.
  3831. */
  3832. applyQuaternion( q ) {
  3833. // quaternion q is assumed to have unit length
  3834. const vx = this.x, vy = this.y, vz = this.z;
  3835. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  3836. // t = 2 * cross( q.xyz, v );
  3837. const tx = 2 * ( qy * vz - qz * vy );
  3838. const ty = 2 * ( qz * vx - qx * vz );
  3839. const tz = 2 * ( qx * vy - qy * vx );
  3840. // v + q.w * t + cross( q.xyz, t );
  3841. this.x = vx + qw * tx + qy * tz - qz * ty;
  3842. this.y = vy + qw * ty + qz * tx - qx * tz;
  3843. this.z = vz + qw * tz + qx * ty - qy * tx;
  3844. return this;
  3845. }
  3846. /**
  3847. * Projects this vector from world space into the camera's normalized
  3848. * device coordinate (NDC) space.
  3849. *
  3850. * @param {Camera} camera - The camera.
  3851. * @return {Vector3} A reference to this vector.
  3852. */
  3853. project( camera ) {
  3854. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  3855. }
  3856. /**
  3857. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  3858. * space into world space.
  3859. *
  3860. * @param {Camera} camera - The camera.
  3861. * @return {Vector3} A reference to this vector.
  3862. */
  3863. unproject( camera ) {
  3864. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  3865. }
  3866. /**
  3867. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  3868. * subset of the given 4x4 matrix and then normalizes the result.
  3869. *
  3870. * @param {Matrix4} m - The matrix.
  3871. * @return {Vector3} A reference to this vector.
  3872. */
  3873. transformDirection( m ) {
  3874. // input: THREE.Matrix4 affine matrix
  3875. // vector interpreted as a direction
  3876. const x = this.x, y = this.y, z = this.z;
  3877. const e = m.elements;
  3878. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  3879. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  3880. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  3881. return this.normalize();
  3882. }
  3883. /**
  3884. * Divides this instance by the given vector.
  3885. *
  3886. * @param {Vector3} v - The vector to divide.
  3887. * @return {Vector3} A reference to this vector.
  3888. */
  3889. divide( v ) {
  3890. this.x /= v.x;
  3891. this.y /= v.y;
  3892. this.z /= v.z;
  3893. return this;
  3894. }
  3895. /**
  3896. * Divides this vector by the given scalar.
  3897. *
  3898. * @param {number} scalar - The scalar to divide.
  3899. * @return {Vector3} A reference to this vector.
  3900. */
  3901. divideScalar( scalar ) {
  3902. return this.multiplyScalar( 1 / scalar );
  3903. }
  3904. /**
  3905. * If this vector's x, y or z value is greater than the given vector's x, y or z
  3906. * value, replace that value with the corresponding min value.
  3907. *
  3908. * @param {Vector3} v - The vector.
  3909. * @return {Vector3} A reference to this vector.
  3910. */
  3911. min( v ) {
  3912. this.x = Math.min( this.x, v.x );
  3913. this.y = Math.min( this.y, v.y );
  3914. this.z = Math.min( this.z, v.z );
  3915. return this;
  3916. }
  3917. /**
  3918. * If this vector's x, y or z value is less than the given vector's x, y or z
  3919. * value, replace that value with the corresponding max value.
  3920. *
  3921. * @param {Vector3} v - The vector.
  3922. * @return {Vector3} A reference to this vector.
  3923. */
  3924. max( v ) {
  3925. this.x = Math.max( this.x, v.x );
  3926. this.y = Math.max( this.y, v.y );
  3927. this.z = Math.max( this.z, v.z );
  3928. return this;
  3929. }
  3930. /**
  3931. * If this vector's x, y or z value is greater than the max vector's x, y or z
  3932. * value, it is replaced by the corresponding value.
  3933. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  3934. * it is replaced by the corresponding value.
  3935. *
  3936. * @param {Vector3} min - The minimum x, y and z values.
  3937. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  3938. * @return {Vector3} A reference to this vector.
  3939. */
  3940. clamp( min, max ) {
  3941. // assumes min < max, componentwise
  3942. this.x = clamp( this.x, min.x, max.x );
  3943. this.y = clamp( this.y, min.y, max.y );
  3944. this.z = clamp( this.z, min.z, max.z );
  3945. return this;
  3946. }
  3947. /**
  3948. * If this vector's x, y or z values are greater than the max value, they are
  3949. * replaced by the max value.
  3950. * If this vector's x, y or z values are less than the min value, they are
  3951. * replaced by the min value.
  3952. *
  3953. * @param {number} minVal - The minimum value the components will be clamped to.
  3954. * @param {number} maxVal - The maximum value the components will be clamped to.
  3955. * @return {Vector3} A reference to this vector.
  3956. */
  3957. clampScalar( minVal, maxVal ) {
  3958. this.x = clamp( this.x, minVal, maxVal );
  3959. this.y = clamp( this.y, minVal, maxVal );
  3960. this.z = clamp( this.z, minVal, maxVal );
  3961. return this;
  3962. }
  3963. /**
  3964. * If this vector's length is greater than the max value, it is replaced by
  3965. * the max value.
  3966. * If this vector's length is less than the min value, it is replaced by the
  3967. * min value.
  3968. *
  3969. * @param {number} min - The minimum value the vector length will be clamped to.
  3970. * @param {number} max - The maximum value the vector length will be clamped to.
  3971. * @return {Vector3} A reference to this vector.
  3972. */
  3973. clampLength( min, max ) {
  3974. const length = this.length();
  3975. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  3976. }
  3977. /**
  3978. * The components of this vector are rounded down to the nearest integer value.
  3979. *
  3980. * @return {Vector3} A reference to this vector.
  3981. */
  3982. floor() {
  3983. this.x = Math.floor( this.x );
  3984. this.y = Math.floor( this.y );
  3985. this.z = Math.floor( this.z );
  3986. return this;
  3987. }
  3988. /**
  3989. * The components of this vector are rounded up to the nearest integer value.
  3990. *
  3991. * @return {Vector3} A reference to this vector.
  3992. */
  3993. ceil() {
  3994. this.x = Math.ceil( this.x );
  3995. this.y = Math.ceil( this.y );
  3996. this.z = Math.ceil( this.z );
  3997. return this;
  3998. }
  3999. /**
  4000. * The components of this vector are rounded to the nearest integer value
  4001. *
  4002. * @return {Vector3} A reference to this vector.
  4003. */
  4004. round() {
  4005. this.x = Math.round( this.x );
  4006. this.y = Math.round( this.y );
  4007. this.z = Math.round( this.z );
  4008. return this;
  4009. }
  4010. /**
  4011. * The components of this vector are rounded towards zero (up if negative,
  4012. * down if positive) to an integer value.
  4013. *
  4014. * @return {Vector3} A reference to this vector.
  4015. */
  4016. roundToZero() {
  4017. this.x = Math.trunc( this.x );
  4018. this.y = Math.trunc( this.y );
  4019. this.z = Math.trunc( this.z );
  4020. return this;
  4021. }
  4022. /**
  4023. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4024. *
  4025. * @return {Vector3} A reference to this vector.
  4026. */
  4027. negate() {
  4028. this.x = - this.x;
  4029. this.y = - this.y;
  4030. this.z = - this.z;
  4031. return this;
  4032. }
  4033. /**
  4034. * Calculates the dot product of the given vector with this instance.
  4035. *
  4036. * @param {Vector3} v - The vector to compute the dot product with.
  4037. * @return {number} The result of the dot product.
  4038. */
  4039. dot( v ) {
  4040. return this.x * v.x + this.y * v.y + this.z * v.z;
  4041. }
  4042. // TODO lengthSquared?
  4043. /**
  4044. * Computes the square of the Euclidean length (straight-line length) from
  4045. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4046. * compare the length squared instead as it is slightly more efficient to calculate.
  4047. *
  4048. * @return {number} The square length of this vector.
  4049. */
  4050. lengthSq() {
  4051. return this.x * this.x + this.y * this.y + this.z * this.z;
  4052. }
  4053. /**
  4054. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4055. *
  4056. * @return {number} The length of this vector.
  4057. */
  4058. length() {
  4059. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4060. }
  4061. /**
  4062. * Computes the Manhattan length of this vector.
  4063. *
  4064. * @return {number} The length of this vector.
  4065. */
  4066. manhattanLength() {
  4067. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4068. }
  4069. /**
  4070. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4071. * with the same direction as this one, but with a vector length of `1`.
  4072. *
  4073. * @return {Vector3} A reference to this vector.
  4074. */
  4075. normalize() {
  4076. return this.divideScalar( this.length() || 1 );
  4077. }
  4078. /**
  4079. * Sets this vector to a vector with the same direction as this one, but
  4080. * with the specified length.
  4081. *
  4082. * @param {number} length - The new length of this vector.
  4083. * @return {Vector3} A reference to this vector.
  4084. */
  4085. setLength( length ) {
  4086. return this.normalize().multiplyScalar( length );
  4087. }
  4088. /**
  4089. * Linearly interpolates between the given vector and this instance, where
  4090. * alpha is the percent distance along the line - alpha = 0 will be this
  4091. * vector, and alpha = 1 will be the given one.
  4092. *
  4093. * @param {Vector3} v - The vector to interpolate towards.
  4094. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4095. * @return {Vector3} A reference to this vector.
  4096. */
  4097. lerp( v, alpha ) {
  4098. this.x += ( v.x - this.x ) * alpha;
  4099. this.y += ( v.y - this.y ) * alpha;
  4100. this.z += ( v.z - this.z ) * alpha;
  4101. return this;
  4102. }
  4103. /**
  4104. * Linearly interpolates between the given vectors, where alpha is the percent
  4105. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4106. * be the second one. The result is stored in this instance.
  4107. *
  4108. * @param {Vector3} v1 - The first vector.
  4109. * @param {Vector3} v2 - The second vector.
  4110. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4111. * @return {Vector3} A reference to this vector.
  4112. */
  4113. lerpVectors( v1, v2, alpha ) {
  4114. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4115. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4116. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4117. return this;
  4118. }
  4119. /**
  4120. * Calculates the cross product of the given vector with this instance.
  4121. *
  4122. * @param {Vector3} v - The vector to compute the cross product with.
  4123. * @return {Vector3} The result of the cross product.
  4124. */
  4125. cross( v ) {
  4126. return this.crossVectors( this, v );
  4127. }
  4128. /**
  4129. * Calculates the cross product of the given vectors and stores the result
  4130. * in this instance.
  4131. *
  4132. * @param {Vector3} a - The first vector.
  4133. * @param {Vector3} b - The second vector.
  4134. * @return {Vector3} A reference to this vector.
  4135. */
  4136. crossVectors( a, b ) {
  4137. const ax = a.x, ay = a.y, az = a.z;
  4138. const bx = b.x, by = b.y, bz = b.z;
  4139. this.x = ay * bz - az * by;
  4140. this.y = az * bx - ax * bz;
  4141. this.z = ax * by - ay * bx;
  4142. return this;
  4143. }
  4144. /**
  4145. * Projects this vector onto the given one.
  4146. *
  4147. * @param {Vector3} v - The vector to project to.
  4148. * @return {Vector3} A reference to this vector.
  4149. */
  4150. projectOnVector( v ) {
  4151. const denominator = v.lengthSq();
  4152. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4153. const scalar = v.dot( this ) / denominator;
  4154. return this.copy( v ).multiplyScalar( scalar );
  4155. }
  4156. /**
  4157. * Projects this vector onto a plane by subtracting this
  4158. * vector projected onto the plane's normal from this vector.
  4159. *
  4160. * @param {Vector3} planeNormal - The plane normal.
  4161. * @return {Vector3} A reference to this vector.
  4162. */
  4163. projectOnPlane( planeNormal ) {
  4164. _vector$c.copy( this ).projectOnVector( planeNormal );
  4165. return this.sub( _vector$c );
  4166. }
  4167. /**
  4168. * Reflects this vector off a plane orthogonal to the given normal vector.
  4169. *
  4170. * @param {Vector3} normal - The (normalized) normal vector.
  4171. * @return {Vector3} A reference to this vector.
  4172. */
  4173. reflect( normal ) {
  4174. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4175. }
  4176. /**
  4177. * Returns the angle between the given vector and this instance in radians.
  4178. *
  4179. * @param {Vector3} v - The vector to compute the angle with.
  4180. * @return {number} The angle in radians.
  4181. */
  4182. angleTo( v ) {
  4183. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4184. if ( denominator === 0 ) return Math.PI / 2;
  4185. const theta = this.dot( v ) / denominator;
  4186. // clamp, to handle numerical problems
  4187. return Math.acos( clamp( theta, -1, 1 ) );
  4188. }
  4189. /**
  4190. * Computes the distance from the given vector to this instance.
  4191. *
  4192. * @param {Vector3} v - The vector to compute the distance to.
  4193. * @return {number} The distance.
  4194. */
  4195. distanceTo( v ) {
  4196. return Math.sqrt( this.distanceToSquared( v ) );
  4197. }
  4198. /**
  4199. * Computes the squared distance from the given vector to this instance.
  4200. * If you are just comparing the distance with another distance, you should compare
  4201. * the distance squared instead as it is slightly more efficient to calculate.
  4202. *
  4203. * @param {Vector3} v - The vector to compute the squared distance to.
  4204. * @return {number} The squared distance.
  4205. */
  4206. distanceToSquared( v ) {
  4207. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  4208. return dx * dx + dy * dy + dz * dz;
  4209. }
  4210. /**
  4211. * Computes the Manhattan distance from the given vector to this instance.
  4212. *
  4213. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  4214. * @return {number} The Manhattan distance.
  4215. */
  4216. manhattanDistanceTo( v ) {
  4217. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  4218. }
  4219. /**
  4220. * Sets the vector components from the given spherical coordinates.
  4221. *
  4222. * @param {Spherical} s - The spherical coordinates.
  4223. * @return {Vector3} A reference to this vector.
  4224. */
  4225. setFromSpherical( s ) {
  4226. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  4227. }
  4228. /**
  4229. * Sets the vector components from the given spherical coordinates.
  4230. *
  4231. * @param {number} radius - The radius.
  4232. * @param {number} phi - The phi angle in radians.
  4233. * @param {number} theta - The theta angle in radians.
  4234. * @return {Vector3} A reference to this vector.
  4235. */
  4236. setFromSphericalCoords( radius, phi, theta ) {
  4237. const sinPhiRadius = Math.sin( phi ) * radius;
  4238. this.x = sinPhiRadius * Math.sin( theta );
  4239. this.y = Math.cos( phi ) * radius;
  4240. this.z = sinPhiRadius * Math.cos( theta );
  4241. return this;
  4242. }
  4243. /**
  4244. * Sets the vector components from the given cylindrical coordinates.
  4245. *
  4246. * @param {Cylindrical} c - The cylindrical coordinates.
  4247. * @return {Vector3} A reference to this vector.
  4248. */
  4249. setFromCylindrical( c ) {
  4250. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  4251. }
  4252. /**
  4253. * Sets the vector components from the given cylindrical coordinates.
  4254. *
  4255. * @param {number} radius - The radius.
  4256. * @param {number} theta - The theta angle in radians.
  4257. * @param {number} y - The y value.
  4258. * @return {Vector3} A reference to this vector.
  4259. */
  4260. setFromCylindricalCoords( radius, theta, y ) {
  4261. this.x = radius * Math.sin( theta );
  4262. this.y = y;
  4263. this.z = radius * Math.cos( theta );
  4264. return this;
  4265. }
  4266. /**
  4267. * Sets the vector components to the position elements of the
  4268. * given transformation matrix.
  4269. *
  4270. * @param {Matrix4} m - The 4x4 matrix.
  4271. * @return {Vector3} A reference to this vector.
  4272. */
  4273. setFromMatrixPosition( m ) {
  4274. const e = m.elements;
  4275. this.x = e[ 12 ];
  4276. this.y = e[ 13 ];
  4277. this.z = e[ 14 ];
  4278. return this;
  4279. }
  4280. /**
  4281. * Sets the vector components to the scale elements of the
  4282. * given transformation matrix.
  4283. *
  4284. * @param {Matrix4} m - The 4x4 matrix.
  4285. * @return {Vector3} A reference to this vector.
  4286. */
  4287. setFromMatrixScale( m ) {
  4288. const sx = this.setFromMatrixColumn( m, 0 ).length();
  4289. const sy = this.setFromMatrixColumn( m, 1 ).length();
  4290. const sz = this.setFromMatrixColumn( m, 2 ).length();
  4291. this.x = sx;
  4292. this.y = sy;
  4293. this.z = sz;
  4294. return this;
  4295. }
  4296. /**
  4297. * Sets the vector components from the specified matrix column.
  4298. *
  4299. * @param {Matrix4} m - The 4x4 matrix.
  4300. * @param {number} index - The column index.
  4301. * @return {Vector3} A reference to this vector.
  4302. */
  4303. setFromMatrixColumn( m, index ) {
  4304. return this.fromArray( m.elements, index * 4 );
  4305. }
  4306. /**
  4307. * Sets the vector components from the specified matrix column.
  4308. *
  4309. * @param {Matrix3} m - The 3x3 matrix.
  4310. * @param {number} index - The column index.
  4311. * @return {Vector3} A reference to this vector.
  4312. */
  4313. setFromMatrix3Column( m, index ) {
  4314. return this.fromArray( m.elements, index * 3 );
  4315. }
  4316. /**
  4317. * Sets the vector components from the given Euler angles.
  4318. *
  4319. * @param {Euler} e - The Euler angles to set.
  4320. * @return {Vector3} A reference to this vector.
  4321. */
  4322. setFromEuler( e ) {
  4323. this.x = e._x;
  4324. this.y = e._y;
  4325. this.z = e._z;
  4326. return this;
  4327. }
  4328. /**
  4329. * Sets the vector components from the RGB components of the
  4330. * given color.
  4331. *
  4332. * @param {Color} c - The color to set.
  4333. * @return {Vector3} A reference to this vector.
  4334. */
  4335. setFromColor( c ) {
  4336. this.x = c.r;
  4337. this.y = c.g;
  4338. this.z = c.b;
  4339. return this;
  4340. }
  4341. /**
  4342. * Returns `true` if this vector is equal with the given one.
  4343. *
  4344. * @param {Vector3} v - The vector to test for equality.
  4345. * @return {boolean} Whether this vector is equal with the given one.
  4346. */
  4347. equals( v ) {
  4348. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  4349. }
  4350. /**
  4351. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  4352. * and z value to be `array[ offset + 2 ]`.
  4353. *
  4354. * @param {Array<number>} array - An array holding the vector component values.
  4355. * @param {number} [offset=0] - The offset into the array.
  4356. * @return {Vector3} A reference to this vector.
  4357. */
  4358. fromArray( array, offset = 0 ) {
  4359. this.x = array[ offset ];
  4360. this.y = array[ offset + 1 ];
  4361. this.z = array[ offset + 2 ];
  4362. return this;
  4363. }
  4364. /**
  4365. * Writes the components of this vector to the given array. If no array is provided,
  4366. * the method returns a new instance.
  4367. *
  4368. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  4369. * @param {number} [offset=0] - Index of the first element in the array.
  4370. * @return {Array<number>} The vector components.
  4371. */
  4372. toArray( array = [], offset = 0 ) {
  4373. array[ offset ] = this.x;
  4374. array[ offset + 1 ] = this.y;
  4375. array[ offset + 2 ] = this.z;
  4376. return array;
  4377. }
  4378. /**
  4379. * Sets the components of this vector from the given buffer attribute.
  4380. *
  4381. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  4382. * @param {number} index - The index into the attribute.
  4383. * @return {Vector3} A reference to this vector.
  4384. */
  4385. fromBufferAttribute( attribute, index ) {
  4386. this.x = attribute.getX( index );
  4387. this.y = attribute.getY( index );
  4388. this.z = attribute.getZ( index );
  4389. return this;
  4390. }
  4391. /**
  4392. * Sets each component of this vector to a pseudo-random value between `0` and
  4393. * `1`, excluding `1`.
  4394. *
  4395. * @return {Vector3} A reference to this vector.
  4396. */
  4397. random() {
  4398. this.x = Math.random();
  4399. this.y = Math.random();
  4400. this.z = Math.random();
  4401. return this;
  4402. }
  4403. /**
  4404. * Sets this vector to a uniformly random point on a unit sphere.
  4405. *
  4406. * @return {Vector3} A reference to this vector.
  4407. */
  4408. randomDirection() {
  4409. // https://mathworld.wolfram.com/SpherePointPicking.html
  4410. const theta = Math.random() * Math.PI * 2;
  4411. const u = Math.random() * 2 - 1;
  4412. const c = Math.sqrt( 1 - u * u );
  4413. this.x = c * Math.cos( theta );
  4414. this.y = u;
  4415. this.z = c * Math.sin( theta );
  4416. return this;
  4417. }
  4418. *[ Symbol.iterator ]() {
  4419. yield this.x;
  4420. yield this.y;
  4421. yield this.z;
  4422. }
  4423. }
  4424. const _vector$c = /*@__PURE__*/ new Vector3();
  4425. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  4426. /**
  4427. * Represents a 3x3 matrix.
  4428. *
  4429. * A Note on Row-Major and Column-Major Ordering:
  4430. *
  4431. * The constructor and {@link Matrix3#set} method take arguments in
  4432. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  4433. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  4434. * This means that calling:
  4435. * ```js
  4436. * const m = new THREE.Matrix();
  4437. * m.set( 11, 12, 13,
  4438. * 21, 22, 23,
  4439. * 31, 32, 33 );
  4440. * ```
  4441. * will result in the elements array containing:
  4442. * ```js
  4443. * m.elements = [ 11, 21, 31,
  4444. * 12, 22, 32,
  4445. * 13, 23, 33 ];
  4446. * ```
  4447. * and internally all calculations are performed using column-major ordering.
  4448. * However, as the actual ordering makes no difference mathematically and
  4449. * most people are used to thinking about matrices in row-major order, the
  4450. * three.js documentation shows matrices in row-major order. Just bear in
  4451. * mind that if you are reading the source code, you'll have to take the
  4452. * transpose of any matrices outlined here to make sense of the calculations.
  4453. */
  4454. class Matrix3 {
  4455. /**
  4456. * Constructs a new 3x3 matrix. The arguments are supposed to be
  4457. * in row-major order. If no arguments are provided, the constructor
  4458. * initializes the matrix as an identity matrix.
  4459. *
  4460. * @param {number} [n11] - 1-1 matrix element.
  4461. * @param {number} [n12] - 1-2 matrix element.
  4462. * @param {number} [n13] - 1-3 matrix element.
  4463. * @param {number} [n21] - 2-1 matrix element.
  4464. * @param {number} [n22] - 2-2 matrix element.
  4465. * @param {number} [n23] - 2-3 matrix element.
  4466. * @param {number} [n31] - 3-1 matrix element.
  4467. * @param {number} [n32] - 3-2 matrix element.
  4468. * @param {number} [n33] - 3-3 matrix element.
  4469. */
  4470. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4471. /**
  4472. * This flag can be used for type testing.
  4473. *
  4474. * @type {boolean}
  4475. * @readonly
  4476. * @default true
  4477. */
  4478. Matrix3.prototype.isMatrix3 = true;
  4479. /**
  4480. * A column-major list of matrix values.
  4481. *
  4482. * @type {Array<number>}
  4483. */
  4484. this.elements = [
  4485. 1, 0, 0,
  4486. 0, 1, 0,
  4487. 0, 0, 1
  4488. ];
  4489. if ( n11 !== undefined ) {
  4490. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  4491. }
  4492. }
  4493. /**
  4494. * Sets the elements of the matrix.The arguments are supposed to be
  4495. * in row-major order.
  4496. *
  4497. * @param {number} [n11] - 1-1 matrix element.
  4498. * @param {number} [n12] - 1-2 matrix element.
  4499. * @param {number} [n13] - 1-3 matrix element.
  4500. * @param {number} [n21] - 2-1 matrix element.
  4501. * @param {number} [n22] - 2-2 matrix element.
  4502. * @param {number} [n23] - 2-3 matrix element.
  4503. * @param {number} [n31] - 3-1 matrix element.
  4504. * @param {number} [n32] - 3-2 matrix element.
  4505. * @param {number} [n33] - 3-3 matrix element.
  4506. * @return {Matrix3} A reference to this matrix.
  4507. */
  4508. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4509. const te = this.elements;
  4510. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  4511. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  4512. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  4513. return this;
  4514. }
  4515. /**
  4516. * Sets this matrix to the 3x3 identity matrix.
  4517. *
  4518. * @return {Matrix3} A reference to this matrix.
  4519. */
  4520. identity() {
  4521. this.set(
  4522. 1, 0, 0,
  4523. 0, 1, 0,
  4524. 0, 0, 1
  4525. );
  4526. return this;
  4527. }
  4528. /**
  4529. * Copies the values of the given matrix to this instance.
  4530. *
  4531. * @param {Matrix3} m - The matrix to copy.
  4532. * @return {Matrix3} A reference to this matrix.
  4533. */
  4534. copy( m ) {
  4535. const te = this.elements;
  4536. const me = m.elements;
  4537. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  4538. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  4539. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  4540. return this;
  4541. }
  4542. /**
  4543. * Extracts the basis of this matrix into the three axis vectors provided.
  4544. *
  4545. * @param {Vector3} xAxis - The basis's x axis.
  4546. * @param {Vector3} yAxis - The basis's y axis.
  4547. * @param {Vector3} zAxis - The basis's z axis.
  4548. * @return {Matrix3} A reference to this matrix.
  4549. */
  4550. extractBasis( xAxis, yAxis, zAxis ) {
  4551. xAxis.setFromMatrix3Column( this, 0 );
  4552. yAxis.setFromMatrix3Column( this, 1 );
  4553. zAxis.setFromMatrix3Column( this, 2 );
  4554. return this;
  4555. }
  4556. /**
  4557. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  4558. *
  4559. * @param {Matrix4} m - The 4x4 matrix.
  4560. * @return {Matrix3} A reference to this matrix.
  4561. */
  4562. setFromMatrix4( m ) {
  4563. const me = m.elements;
  4564. this.set(
  4565. me[ 0 ], me[ 4 ], me[ 8 ],
  4566. me[ 1 ], me[ 5 ], me[ 9 ],
  4567. me[ 2 ], me[ 6 ], me[ 10 ]
  4568. );
  4569. return this;
  4570. }
  4571. /**
  4572. * Post-multiplies this matrix by the given 3x3 matrix.
  4573. *
  4574. * @param {Matrix3} m - The matrix to multiply with.
  4575. * @return {Matrix3} A reference to this matrix.
  4576. */
  4577. multiply( m ) {
  4578. return this.multiplyMatrices( this, m );
  4579. }
  4580. /**
  4581. * Pre-multiplies this matrix by the given 3x3 matrix.
  4582. *
  4583. * @param {Matrix3} m - The matrix to multiply with.
  4584. * @return {Matrix3} A reference to this matrix.
  4585. */
  4586. premultiply( m ) {
  4587. return this.multiplyMatrices( m, this );
  4588. }
  4589. /**
  4590. * Multiples the given 3x3 matrices and stores the result
  4591. * in this matrix.
  4592. *
  4593. * @param {Matrix3} a - The first matrix.
  4594. * @param {Matrix3} b - The second matrix.
  4595. * @return {Matrix3} A reference to this matrix.
  4596. */
  4597. multiplyMatrices( a, b ) {
  4598. const ae = a.elements;
  4599. const be = b.elements;
  4600. const te = this.elements;
  4601. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  4602. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  4603. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  4604. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  4605. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  4606. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  4607. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  4608. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  4609. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  4610. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  4611. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  4612. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  4613. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  4614. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  4615. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  4616. return this;
  4617. }
  4618. /**
  4619. * Multiplies every component of the matrix by the given scalar.
  4620. *
  4621. * @param {number} s - The scalar.
  4622. * @return {Matrix3} A reference to this matrix.
  4623. */
  4624. multiplyScalar( s ) {
  4625. const te = this.elements;
  4626. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  4627. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  4628. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  4629. return this;
  4630. }
  4631. /**
  4632. * Computes and returns the determinant of this matrix.
  4633. *
  4634. * @return {number} The determinant.
  4635. */
  4636. determinant() {
  4637. const te = this.elements;
  4638. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  4639. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  4640. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  4641. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  4642. }
  4643. /**
  4644. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  4645. * You can not invert with a determinant of zero. If you attempt this, the method produces
  4646. * a zero matrix instead.
  4647. *
  4648. * @return {Matrix3} A reference to this matrix.
  4649. */
  4650. invert() {
  4651. const te = this.elements,
  4652. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  4653. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  4654. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  4655. t11 = n33 * n22 - n32 * n23,
  4656. t12 = n32 * n13 - n33 * n12,
  4657. t13 = n23 * n12 - n22 * n13,
  4658. det = n11 * t11 + n21 * t12 + n31 * t13;
  4659. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4660. const detInv = 1 / det;
  4661. te[ 0 ] = t11 * detInv;
  4662. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  4663. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  4664. te[ 3 ] = t12 * detInv;
  4665. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  4666. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  4667. te[ 6 ] = t13 * detInv;
  4668. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  4669. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  4670. return this;
  4671. }
  4672. /**
  4673. * Transposes this matrix in place.
  4674. *
  4675. * @return {Matrix3} A reference to this matrix.
  4676. */
  4677. transpose() {
  4678. let tmp;
  4679. const m = this.elements;
  4680. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  4681. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  4682. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  4683. return this;
  4684. }
  4685. /**
  4686. * Computes the normal matrix which is the inverse transpose of the upper
  4687. * left 3x3 portion of the given 4x4 matrix.
  4688. *
  4689. * @param {Matrix4} matrix4 - The 4x4 matrix.
  4690. * @return {Matrix3} A reference to this matrix.
  4691. */
  4692. getNormalMatrix( matrix4 ) {
  4693. return this.setFromMatrix4( matrix4 ).invert().transpose();
  4694. }
  4695. /**
  4696. * Transposes this matrix into the supplied array, and returns itself unchanged.
  4697. *
  4698. * @param {Array<number>} r - An array to store the transposed matrix elements.
  4699. * @return {Matrix3} A reference to this matrix.
  4700. */
  4701. transposeIntoArray( r ) {
  4702. const m = this.elements;
  4703. r[ 0 ] = m[ 0 ];
  4704. r[ 1 ] = m[ 3 ];
  4705. r[ 2 ] = m[ 6 ];
  4706. r[ 3 ] = m[ 1 ];
  4707. r[ 4 ] = m[ 4 ];
  4708. r[ 5 ] = m[ 7 ];
  4709. r[ 6 ] = m[ 2 ];
  4710. r[ 7 ] = m[ 5 ];
  4711. r[ 8 ] = m[ 8 ];
  4712. return this;
  4713. }
  4714. /**
  4715. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  4716. *
  4717. * @param {number} tx - Offset x.
  4718. * @param {number} ty - Offset y.
  4719. * @param {number} sx - Repeat x.
  4720. * @param {number} sy - Repeat y.
  4721. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  4722. * @param {number} cx - Center x of rotation.
  4723. * @param {number} cy - Center y of rotation
  4724. * @return {Matrix3} A reference to this matrix.
  4725. */
  4726. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  4727. const c = Math.cos( rotation );
  4728. const s = Math.sin( rotation );
  4729. this.set(
  4730. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  4731. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  4732. 0, 0, 1
  4733. );
  4734. return this;
  4735. }
  4736. /**
  4737. * Scales this matrix with the given scalar values.
  4738. *
  4739. * @param {number} sx - The amount to scale in the X axis.
  4740. * @param {number} sy - The amount to scale in the Y axis.
  4741. * @return {Matrix3} A reference to this matrix.
  4742. */
  4743. scale( sx, sy ) {
  4744. this.premultiply( _m3.makeScale( sx, sy ) );
  4745. return this;
  4746. }
  4747. /**
  4748. * Rotates this matrix by the given angle.
  4749. *
  4750. * @param {number} theta - The rotation in radians.
  4751. * @return {Matrix3} A reference to this matrix.
  4752. */
  4753. rotate( theta ) {
  4754. this.premultiply( _m3.makeRotation( - theta ) );
  4755. return this;
  4756. }
  4757. /**
  4758. * Translates this matrix by the given scalar values.
  4759. *
  4760. * @param {number} tx - The amount to translate in the X axis.
  4761. * @param {number} ty - The amount to translate in the Y axis.
  4762. * @return {Matrix3} A reference to this matrix.
  4763. */
  4764. translate( tx, ty ) {
  4765. this.premultiply( _m3.makeTranslation( tx, ty ) );
  4766. return this;
  4767. }
  4768. // for 2D Transforms
  4769. /**
  4770. * Sets this matrix as a 2D translation transform.
  4771. *
  4772. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  4773. * @param {number} y - The amount to translate in the Y axis.
  4774. * @return {Matrix3} A reference to this matrix.
  4775. */
  4776. makeTranslation( x, y ) {
  4777. if ( x.isVector2 ) {
  4778. this.set(
  4779. 1, 0, x.x,
  4780. 0, 1, x.y,
  4781. 0, 0, 1
  4782. );
  4783. } else {
  4784. this.set(
  4785. 1, 0, x,
  4786. 0, 1, y,
  4787. 0, 0, 1
  4788. );
  4789. }
  4790. return this;
  4791. }
  4792. /**
  4793. * Sets this matrix as a 2D rotational transformation.
  4794. *
  4795. * @param {number} theta - The rotation in radians.
  4796. * @return {Matrix3} A reference to this matrix.
  4797. */
  4798. makeRotation( theta ) {
  4799. // counterclockwise
  4800. const c = Math.cos( theta );
  4801. const s = Math.sin( theta );
  4802. this.set(
  4803. c, - s, 0,
  4804. s, c, 0,
  4805. 0, 0, 1
  4806. );
  4807. return this;
  4808. }
  4809. /**
  4810. * Sets this matrix as a 2D scale transform.
  4811. *
  4812. * @param {number} x - The amount to scale in the X axis.
  4813. * @param {number} y - The amount to scale in the Y axis.
  4814. * @return {Matrix3} A reference to this matrix.
  4815. */
  4816. makeScale( x, y ) {
  4817. this.set(
  4818. x, 0, 0,
  4819. 0, y, 0,
  4820. 0, 0, 1
  4821. );
  4822. return this;
  4823. }
  4824. /**
  4825. * Returns `true` if this matrix is equal with the given one.
  4826. *
  4827. * @param {Matrix3} matrix - The matrix to test for equality.
  4828. * @return {boolean} Whether this matrix is equal with the given one.
  4829. */
  4830. equals( matrix ) {
  4831. const te = this.elements;
  4832. const me = matrix.elements;
  4833. for ( let i = 0; i < 9; i ++ ) {
  4834. if ( te[ i ] !== me[ i ] ) return false;
  4835. }
  4836. return true;
  4837. }
  4838. /**
  4839. * Sets the elements of the matrix from the given array.
  4840. *
  4841. * @param {Array<number>} array - The matrix elements in column-major order.
  4842. * @param {number} [offset=0] - Index of the first element in the array.
  4843. * @return {Matrix3} A reference to this matrix.
  4844. */
  4845. fromArray( array, offset = 0 ) {
  4846. for ( let i = 0; i < 9; i ++ ) {
  4847. this.elements[ i ] = array[ i + offset ];
  4848. }
  4849. return this;
  4850. }
  4851. /**
  4852. * Writes the elements of this matrix to the given array. If no array is provided,
  4853. * the method returns a new instance.
  4854. *
  4855. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  4856. * @param {number} [offset=0] - Index of the first element in the array.
  4857. * @return {Array<number>} The matrix elements in column-major order.
  4858. */
  4859. toArray( array = [], offset = 0 ) {
  4860. const te = this.elements;
  4861. array[ offset ] = te[ 0 ];
  4862. array[ offset + 1 ] = te[ 1 ];
  4863. array[ offset + 2 ] = te[ 2 ];
  4864. array[ offset + 3 ] = te[ 3 ];
  4865. array[ offset + 4 ] = te[ 4 ];
  4866. array[ offset + 5 ] = te[ 5 ];
  4867. array[ offset + 6 ] = te[ 6 ];
  4868. array[ offset + 7 ] = te[ 7 ];
  4869. array[ offset + 8 ] = te[ 8 ];
  4870. return array;
  4871. }
  4872. /**
  4873. * Returns a matrix with copied values from this instance.
  4874. *
  4875. * @return {Matrix3} A clone of this instance.
  4876. */
  4877. clone() {
  4878. return new this.constructor().fromArray( this.elements );
  4879. }
  4880. }
  4881. const _m3 = /*@__PURE__*/ new Matrix3();
  4882. function arrayNeedsUint32( array ) {
  4883. // assumes larger values usually on last
  4884. for ( let i = array.length - 1; i >= 0; -- i ) {
  4885. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  4886. }
  4887. return false;
  4888. }
  4889. const TYPED_ARRAYS = {
  4890. Int8Array: Int8Array,
  4891. Uint8Array: Uint8Array,
  4892. Uint8ClampedArray: Uint8ClampedArray,
  4893. Int16Array: Int16Array,
  4894. Uint16Array: Uint16Array,
  4895. Int32Array: Int32Array,
  4896. Uint32Array: Uint32Array,
  4897. Float32Array: Float32Array,
  4898. Float64Array: Float64Array
  4899. };
  4900. function getTypedArray( type, buffer ) {
  4901. return new TYPED_ARRAYS[ type ]( buffer );
  4902. }
  4903. function createElementNS( name ) {
  4904. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  4905. }
  4906. function createCanvasElement() {
  4907. const canvas = createElementNS( 'canvas' );
  4908. canvas.style.display = 'block';
  4909. return canvas;
  4910. }
  4911. const _cache = {};
  4912. function warnOnce( message ) {
  4913. if ( message in _cache ) return;
  4914. _cache[ message ] = true;
  4915. console.warn( message );
  4916. }
  4917. function probeAsync( gl, sync, interval ) {
  4918. return new Promise( function ( resolve, reject ) {
  4919. function probe() {
  4920. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  4921. case gl.WAIT_FAILED:
  4922. reject();
  4923. break;
  4924. case gl.TIMEOUT_EXPIRED:
  4925. setTimeout( probe, interval );
  4926. break;
  4927. default:
  4928. resolve();
  4929. }
  4930. }
  4931. setTimeout( probe, interval );
  4932. } );
  4933. }
  4934. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  4935. 0.4123908, 0.3575843, 0.1804808,
  4936. 0.2126390, 0.7151687, 0.0721923,
  4937. 0.0193308, 0.1191948, 0.9505322
  4938. );
  4939. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  4940. 3.2409699, -1.5373832, -0.4986108,
  4941. -0.9692436, 1.8759675, 0.0415551,
  4942. 0.0556301, -0.203977, 1.0569715
  4943. );
  4944. function createColorManagement() {
  4945. const ColorManagement = {
  4946. enabled: true,
  4947. workingColorSpace: LinearSRGBColorSpace,
  4948. /**
  4949. * Implementations of supported color spaces.
  4950. *
  4951. * Required:
  4952. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  4953. * - whitePoint: reference white [ x y ]
  4954. * - transfer: transfer function (pre-defined)
  4955. * - toXYZ: Matrix3 RGB to XYZ transform
  4956. * - fromXYZ: Matrix3 XYZ to RGB transform
  4957. * - luminanceCoefficients: RGB luminance coefficients
  4958. *
  4959. * Optional:
  4960. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' }
  4961. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  4962. *
  4963. * Reference:
  4964. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  4965. */
  4966. spaces: {},
  4967. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  4968. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  4969. return color;
  4970. }
  4971. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  4972. color.r = SRGBToLinear( color.r );
  4973. color.g = SRGBToLinear( color.g );
  4974. color.b = SRGBToLinear( color.b );
  4975. }
  4976. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  4977. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  4978. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  4979. }
  4980. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  4981. color.r = LinearToSRGB( color.r );
  4982. color.g = LinearToSRGB( color.g );
  4983. color.b = LinearToSRGB( color.b );
  4984. }
  4985. return color;
  4986. },
  4987. workingToColorSpace: function ( color, targetColorSpace ) {
  4988. return this.convert( color, this.workingColorSpace, targetColorSpace );
  4989. },
  4990. colorSpaceToWorking: function ( color, sourceColorSpace ) {
  4991. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  4992. },
  4993. getPrimaries: function ( colorSpace ) {
  4994. return this.spaces[ colorSpace ].primaries;
  4995. },
  4996. getTransfer: function ( colorSpace ) {
  4997. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  4998. return this.spaces[ colorSpace ].transfer;
  4999. },
  5000. getToneMappingMode: function ( colorSpace ) {
  5001. return this.spaces[ colorSpace ].outputColorSpaceConfig.toneMappingMode || 'standard';
  5002. },
  5003. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  5004. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  5005. },
  5006. define: function ( colorSpaces ) {
  5007. Object.assign( this.spaces, colorSpaces );
  5008. },
  5009. // Internal APIs
  5010. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  5011. return targetMatrix
  5012. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  5013. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  5014. },
  5015. _getDrawingBufferColorSpace: function ( colorSpace ) {
  5016. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  5017. },
  5018. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  5019. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  5020. },
  5021. // Deprecated
  5022. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  5023. warnOnce( 'THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().' ); // @deprecated, r177
  5024. return ColorManagement.workingToColorSpace( color, targetColorSpace );
  5025. },
  5026. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  5027. warnOnce( 'THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().' ); // @deprecated, r177
  5028. return ColorManagement.colorSpaceToWorking( color, sourceColorSpace );
  5029. },
  5030. };
  5031. /******************************************************************************
  5032. * sRGB definitions
  5033. */
  5034. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  5035. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  5036. const D65 = [ 0.3127, 0.3290 ];
  5037. ColorManagement.define( {
  5038. [ LinearSRGBColorSpace ]: {
  5039. primaries: REC709_PRIMARIES,
  5040. whitePoint: D65,
  5041. transfer: LinearTransfer,
  5042. toXYZ: LINEAR_REC709_TO_XYZ,
  5043. fromXYZ: XYZ_TO_LINEAR_REC709,
  5044. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5045. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  5046. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5047. },
  5048. [ SRGBColorSpace ]: {
  5049. primaries: REC709_PRIMARIES,
  5050. whitePoint: D65,
  5051. transfer: SRGBTransfer,
  5052. toXYZ: LINEAR_REC709_TO_XYZ,
  5053. fromXYZ: XYZ_TO_LINEAR_REC709,
  5054. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5055. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5056. },
  5057. } );
  5058. return ColorManagement;
  5059. }
  5060. const ColorManagement = /*@__PURE__*/ createColorManagement();
  5061. function SRGBToLinear( c ) {
  5062. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5063. }
  5064. function LinearToSRGB( c ) {
  5065. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5066. }
  5067. let _canvas;
  5068. /**
  5069. * A class containing utility functions for images.
  5070. *
  5071. * @hideconstructor
  5072. */
  5073. class ImageUtils {
  5074. /**
  5075. * Returns a data URI containing a representation of the given image.
  5076. *
  5077. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  5078. * @param {string} [type='image/png'] - Indicates the image format.
  5079. * @return {string} The data URI.
  5080. */
  5081. static getDataURL( image, type = 'image/png' ) {
  5082. if ( /^data:/i.test( image.src ) ) {
  5083. return image.src;
  5084. }
  5085. if ( typeof HTMLCanvasElement === 'undefined' ) {
  5086. return image.src;
  5087. }
  5088. let canvas;
  5089. if ( image instanceof HTMLCanvasElement ) {
  5090. canvas = image;
  5091. } else {
  5092. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  5093. _canvas.width = image.width;
  5094. _canvas.height = image.height;
  5095. const context = _canvas.getContext( '2d' );
  5096. if ( image instanceof ImageData ) {
  5097. context.putImageData( image, 0, 0 );
  5098. } else {
  5099. context.drawImage( image, 0, 0, image.width, image.height );
  5100. }
  5101. canvas = _canvas;
  5102. }
  5103. return canvas.toDataURL( type );
  5104. }
  5105. /**
  5106. * Converts the given sRGB image data to linear color space.
  5107. *
  5108. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  5109. * @return {HTMLCanvasElement|Object} The converted image.
  5110. */
  5111. static sRGBToLinear( image ) {
  5112. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5113. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5114. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5115. const canvas = createElementNS( 'canvas' );
  5116. canvas.width = image.width;
  5117. canvas.height = image.height;
  5118. const context = canvas.getContext( '2d' );
  5119. context.drawImage( image, 0, 0, image.width, image.height );
  5120. const imageData = context.getImageData( 0, 0, image.width, image.height );
  5121. const data = imageData.data;
  5122. for ( let i = 0; i < data.length; i ++ ) {
  5123. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  5124. }
  5125. context.putImageData( imageData, 0, 0 );
  5126. return canvas;
  5127. } else if ( image.data ) {
  5128. const data = image.data.slice( 0 );
  5129. for ( let i = 0; i < data.length; i ++ ) {
  5130. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  5131. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  5132. } else {
  5133. // assuming float
  5134. data[ i ] = SRGBToLinear( data[ i ] );
  5135. }
  5136. }
  5137. return {
  5138. data: data,
  5139. width: image.width,
  5140. height: image.height
  5141. };
  5142. } else {
  5143. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  5144. return image;
  5145. }
  5146. }
  5147. }
  5148. let _sourceId = 0;
  5149. /**
  5150. * Represents the data source of a texture.
  5151. *
  5152. * The main purpose of this class is to decouple the data definition from the texture
  5153. * definition so the same data can be used with multiple texture instances.
  5154. */
  5155. class Source {
  5156. /**
  5157. * Constructs a new video texture.
  5158. *
  5159. * @param {any} [data=null] - The data definition of a texture.
  5160. */
  5161. constructor( data = null ) {
  5162. /**
  5163. * This flag can be used for type testing.
  5164. *
  5165. * @type {boolean}
  5166. * @readonly
  5167. * @default true
  5168. */
  5169. this.isSource = true;
  5170. /**
  5171. * The ID of the source.
  5172. *
  5173. * @name Source#id
  5174. * @type {number}
  5175. * @readonly
  5176. */
  5177. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  5178. /**
  5179. * The UUID of the source.
  5180. *
  5181. * @type {string}
  5182. * @readonly
  5183. */
  5184. this.uuid = generateUUID();
  5185. /**
  5186. * The data definition of a texture.
  5187. *
  5188. * @type {any}
  5189. */
  5190. this.data = data;
  5191. /**
  5192. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  5193. * provides more control on how texture data should be processed. When `dataReady` is set
  5194. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  5195. * the data into the GPU memory.
  5196. *
  5197. * @type {boolean}
  5198. * @default true
  5199. */
  5200. this.dataReady = true;
  5201. /**
  5202. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  5203. *
  5204. * @type {number}
  5205. * @readonly
  5206. * @default 0
  5207. */
  5208. this.version = 0;
  5209. }
  5210. /**
  5211. * Returns the dimensions of the source into the given target vector.
  5212. *
  5213. * @param {(Vector2|Vector3)} target - The target object the result is written into.
  5214. * @return {(Vector2|Vector3)} The dimensions of the source.
  5215. */
  5216. getSize( target ) {
  5217. const data = this.data;
  5218. if ( data instanceof HTMLVideoElement ) {
  5219. target.set( data.videoWidth, data.videoHeight, 0 );
  5220. } else if ( data instanceof VideoFrame ) {
  5221. target.set( data.displayHeight, data.displayWidth, 0 );
  5222. } else if ( data !== null ) {
  5223. target.set( data.width, data.height, data.depth || 0 );
  5224. } else {
  5225. target.set( 0, 0, 0 );
  5226. }
  5227. return target;
  5228. }
  5229. /**
  5230. * When the property is set to `true`, the engine allocates the memory
  5231. * for the texture (if necessary) and triggers the actual texture upload
  5232. * to the GPU next time the source is used.
  5233. *
  5234. * @type {boolean}
  5235. * @default false
  5236. * @param {boolean} value
  5237. */
  5238. set needsUpdate( value ) {
  5239. if ( value === true ) this.version ++;
  5240. }
  5241. /**
  5242. * Serializes the source into JSON.
  5243. *
  5244. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5245. * @return {Object} A JSON object representing the serialized source.
  5246. * @see {@link ObjectLoader#parse}
  5247. */
  5248. toJSON( meta ) {
  5249. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5250. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  5251. return meta.images[ this.uuid ];
  5252. }
  5253. const output = {
  5254. uuid: this.uuid,
  5255. url: ''
  5256. };
  5257. const data = this.data;
  5258. if ( data !== null ) {
  5259. let url;
  5260. if ( Array.isArray( data ) ) {
  5261. // cube texture
  5262. url = [];
  5263. for ( let i = 0, l = data.length; i < l; i ++ ) {
  5264. if ( data[ i ].isDataTexture ) {
  5265. url.push( serializeImage( data[ i ].image ) );
  5266. } else {
  5267. url.push( serializeImage( data[ i ] ) );
  5268. }
  5269. }
  5270. } else {
  5271. // texture
  5272. url = serializeImage( data );
  5273. }
  5274. output.url = url;
  5275. }
  5276. if ( ! isRootObject ) {
  5277. meta.images[ this.uuid ] = output;
  5278. }
  5279. return output;
  5280. }
  5281. }
  5282. function serializeImage( image ) {
  5283. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5284. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5285. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5286. // default images
  5287. return ImageUtils.getDataURL( image );
  5288. } else {
  5289. if ( image.data ) {
  5290. // images of DataTexture
  5291. return {
  5292. data: Array.from( image.data ),
  5293. width: image.width,
  5294. height: image.height,
  5295. type: image.data.constructor.name
  5296. };
  5297. } else {
  5298. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  5299. return {};
  5300. }
  5301. }
  5302. }
  5303. let _textureId = 0;
  5304. const _tempVec3 = /*@__PURE__*/ new Vector3();
  5305. /**
  5306. * Base class for all textures.
  5307. *
  5308. * Note: After the initial use of a texture, its dimensions, format, and type
  5309. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  5310. *
  5311. * @augments EventDispatcher
  5312. */
  5313. class Texture extends EventDispatcher {
  5314. /**
  5315. * Constructs a new texture.
  5316. *
  5317. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  5318. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  5319. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  5320. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  5321. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  5322. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  5323. * @param {number} [format=RGBAFormat] - The texture format.
  5324. * @param {number} [type=UnsignedByteType] - The texture type.
  5325. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  5326. * @param {string} [colorSpace=NoColorSpace] - The color space.
  5327. */
  5328. 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 ) {
  5329. super();
  5330. /**
  5331. * This flag can be used for type testing.
  5332. *
  5333. * @type {boolean}
  5334. * @readonly
  5335. * @default true
  5336. */
  5337. this.isTexture = true;
  5338. /**
  5339. * The ID of the texture.
  5340. *
  5341. * @name Texture#id
  5342. * @type {number}
  5343. * @readonly
  5344. */
  5345. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  5346. /**
  5347. * The UUID of the material.
  5348. *
  5349. * @type {string}
  5350. * @readonly
  5351. */
  5352. this.uuid = generateUUID();
  5353. /**
  5354. * The name of the material.
  5355. *
  5356. * @type {string}
  5357. */
  5358. this.name = '';
  5359. /**
  5360. * The data definition of a texture. A reference to the data source can be
  5361. * shared across textures. This is often useful in context of spritesheets
  5362. * where multiple textures render the same data but with different texture
  5363. * transformations.
  5364. *
  5365. * @type {Source}
  5366. */
  5367. this.source = new Source( image );
  5368. /**
  5369. * An array holding user-defined mipmaps.
  5370. *
  5371. * @type {Array<Object>}
  5372. */
  5373. this.mipmaps = [];
  5374. /**
  5375. * How the texture is applied to the object. The value `UVMapping`
  5376. * is the default, where texture or uv coordinates are used to apply the map.
  5377. *
  5378. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  5379. * @default UVMapping
  5380. */
  5381. this.mapping = mapping;
  5382. /**
  5383. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  5384. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  5385. *
  5386. * @type {number}
  5387. * @default 0
  5388. */
  5389. this.channel = 0;
  5390. /**
  5391. * This defines how the texture is wrapped horizontally and corresponds to
  5392. * *U* in UV mapping.
  5393. *
  5394. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5395. * @default ClampToEdgeWrapping
  5396. */
  5397. this.wrapS = wrapS;
  5398. /**
  5399. * This defines how the texture is wrapped horizontally and corresponds to
  5400. * *V* in UV mapping.
  5401. *
  5402. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5403. * @default ClampToEdgeWrapping
  5404. */
  5405. this.wrapT = wrapT;
  5406. /**
  5407. * How the texture is sampled when a texel covers more than one pixel.
  5408. *
  5409. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5410. * @default LinearFilter
  5411. */
  5412. this.magFilter = magFilter;
  5413. /**
  5414. * How the texture is sampled when a texel covers less than one pixel.
  5415. *
  5416. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5417. * @default LinearMipmapLinearFilter
  5418. */
  5419. this.minFilter = minFilter;
  5420. /**
  5421. * The number of samples taken along the axis through the pixel that has the
  5422. * highest density of texels. By default, this value is `1`. A higher value
  5423. * gives a less blurry result than a basic mipmap, at the cost of more
  5424. * texture samples being used.
  5425. *
  5426. * @type {number}
  5427. * @default 0
  5428. */
  5429. this.anisotropy = anisotropy;
  5430. /**
  5431. * The format of the texture.
  5432. *
  5433. * @type {number}
  5434. * @default RGBAFormat
  5435. */
  5436. this.format = format;
  5437. /**
  5438. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  5439. * defines how the texture data is going to be stored on the GPU.
  5440. *
  5441. * This property allows to overwrite the default format.
  5442. *
  5443. * @type {?string}
  5444. * @default null
  5445. */
  5446. this.internalFormat = null;
  5447. /**
  5448. * The data type of the texture.
  5449. *
  5450. * @type {number}
  5451. * @default UnsignedByteType
  5452. */
  5453. this.type = type;
  5454. /**
  5455. * How much a single repetition of the texture is offset from the beginning,
  5456. * in each direction U and V. Typical range is `0.0` to `1.0`.
  5457. *
  5458. * @type {Vector2}
  5459. * @default (0,0)
  5460. */
  5461. this.offset = new Vector2( 0, 0 );
  5462. /**
  5463. * How many times the texture is repeated across the surface, in each
  5464. * direction U and V. If repeat is set greater than `1` in either direction,
  5465. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  5466. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  5467. *
  5468. * @type {Vector2}
  5469. * @default (1,1)
  5470. */
  5471. this.repeat = new Vector2( 1, 1 );
  5472. /**
  5473. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  5474. * to the center of the texture. Default is `(0, 0)`, the lower left.
  5475. *
  5476. * @type {Vector2}
  5477. * @default (0,0)
  5478. */
  5479. this.center = new Vector2( 0, 0 );
  5480. /**
  5481. * How much the texture is rotated around the center point, in radians.
  5482. * Positive values are counter-clockwise.
  5483. *
  5484. * @type {number}
  5485. * @default 0
  5486. */
  5487. this.rotation = 0;
  5488. /**
  5489. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  5490. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  5491. * {@link Texture#rotation}, and {@link Texture#center}.
  5492. *
  5493. * Set this to `false` if you are specifying the uv-transform matrix directly.
  5494. *
  5495. * @type {boolean}
  5496. * @default true
  5497. */
  5498. this.matrixAutoUpdate = true;
  5499. /**
  5500. * The uv-transformation matrix of the texture.
  5501. *
  5502. * @type {Matrix3}
  5503. */
  5504. this.matrix = new Matrix3();
  5505. /**
  5506. * Whether to generate mipmaps (if possible) for a texture.
  5507. *
  5508. * Set this to `false` if you are creating mipmaps manually.
  5509. *
  5510. * @type {boolean}
  5511. * @default true
  5512. */
  5513. this.generateMipmaps = true;
  5514. /**
  5515. * If set to `true`, the alpha channel, if present, is multiplied into the
  5516. * color channels when the texture is uploaded to the GPU.
  5517. *
  5518. * Note that this property has no effect when using `ImageBitmap`. You need to
  5519. * configure premultiply alpha on bitmap creation instead.
  5520. *
  5521. * @type {boolean}
  5522. * @default false
  5523. */
  5524. this.premultiplyAlpha = false;
  5525. /**
  5526. * If set to `true`, the texture is flipped along the vertical axis when
  5527. * uploaded to the GPU.
  5528. *
  5529. * Note that this property has no effect when using `ImageBitmap`. You need to
  5530. * configure the flip on bitmap creation instead.
  5531. *
  5532. * @type {boolean}
  5533. * @default true
  5534. */
  5535. this.flipY = true;
  5536. /**
  5537. * Specifies the alignment requirements for the start of each pixel row in memory.
  5538. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  5539. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  5540. *
  5541. * @type {number}
  5542. * @default 4
  5543. */
  5544. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  5545. /**
  5546. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  5547. *
  5548. * @type {string}
  5549. * @default NoColorSpace
  5550. */
  5551. this.colorSpace = colorSpace;
  5552. /**
  5553. * An object that can be used to store custom data about the texture. It
  5554. * should not hold references to functions as these will not be cloned.
  5555. *
  5556. * @type {Object}
  5557. */
  5558. this.userData = {};
  5559. /**
  5560. * This can be used to only update a subregion or specific rows of the texture (for example, just the
  5561. * first 3 rows). Use the `addUpdateRange()` function to add ranges to this array.
  5562. *
  5563. * @type {Array<Object>}
  5564. */
  5565. this.updateRanges = [];
  5566. /**
  5567. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  5568. *
  5569. * @type {number}
  5570. * @readonly
  5571. * @default 0
  5572. */
  5573. this.version = 0;
  5574. /**
  5575. * A callback function, called when the texture is updated (e.g., when
  5576. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  5577. *
  5578. * @type {?Function}
  5579. * @default null
  5580. */
  5581. this.onUpdate = null;
  5582. /**
  5583. * An optional back reference to the textures render target.
  5584. *
  5585. * @type {?(RenderTarget|WebGLRenderTarget)}
  5586. * @default null
  5587. */
  5588. this.renderTarget = null;
  5589. /**
  5590. * Indicates whether a texture belongs to a render target or not.
  5591. *
  5592. * @type {boolean}
  5593. * @readonly
  5594. * @default false
  5595. */
  5596. this.isRenderTargetTexture = false;
  5597. /**
  5598. * Indicates if a texture should be handled like a texture array.
  5599. *
  5600. * @type {boolean}
  5601. * @readonly
  5602. * @default false
  5603. */
  5604. this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false;
  5605. /**
  5606. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  5607. * (only relevant for render target textures).
  5608. *
  5609. * @type {number}
  5610. * @readonly
  5611. * @default 0
  5612. */
  5613. this.pmremVersion = 0;
  5614. }
  5615. /**
  5616. * The width of the texture in pixels.
  5617. */
  5618. get width() {
  5619. return this.source.getSize( _tempVec3 ).x;
  5620. }
  5621. /**
  5622. * The height of the texture in pixels.
  5623. */
  5624. get height() {
  5625. return this.source.getSize( _tempVec3 ).y;
  5626. }
  5627. /**
  5628. * The depth of the texture in pixels.
  5629. */
  5630. get depth() {
  5631. return this.source.getSize( _tempVec3 ).z;
  5632. }
  5633. /**
  5634. * The image object holding the texture data.
  5635. *
  5636. * @type {?Object}
  5637. */
  5638. get image() {
  5639. return this.source.data;
  5640. }
  5641. set image( value = null ) {
  5642. this.source.data = value;
  5643. }
  5644. /**
  5645. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  5646. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  5647. */
  5648. updateMatrix() {
  5649. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  5650. }
  5651. /**
  5652. * Adds a range of data in the data texture to be updated on the GPU.
  5653. *
  5654. * @param {number} start - Position at which to start update.
  5655. * @param {number} count - The number of components to update.
  5656. */
  5657. addUpdateRange( start, count ) {
  5658. this.updateRanges.push( { start, count } );
  5659. }
  5660. /**
  5661. * Clears the update ranges.
  5662. */
  5663. clearUpdateRanges() {
  5664. this.updateRanges.length = 0;
  5665. }
  5666. /**
  5667. * Returns a new texture with copied values from this instance.
  5668. *
  5669. * @return {Texture} A clone of this instance.
  5670. */
  5671. clone() {
  5672. return new this.constructor().copy( this );
  5673. }
  5674. /**
  5675. * Copies the values of the given texture to this instance.
  5676. *
  5677. * @param {Texture} source - The texture to copy.
  5678. * @return {Texture} A reference to this instance.
  5679. */
  5680. copy( source ) {
  5681. this.name = source.name;
  5682. this.source = source.source;
  5683. this.mipmaps = source.mipmaps.slice( 0 );
  5684. this.mapping = source.mapping;
  5685. this.channel = source.channel;
  5686. this.wrapS = source.wrapS;
  5687. this.wrapT = source.wrapT;
  5688. this.magFilter = source.magFilter;
  5689. this.minFilter = source.minFilter;
  5690. this.anisotropy = source.anisotropy;
  5691. this.format = source.format;
  5692. this.internalFormat = source.internalFormat;
  5693. this.type = source.type;
  5694. this.offset.copy( source.offset );
  5695. this.repeat.copy( source.repeat );
  5696. this.center.copy( source.center );
  5697. this.rotation = source.rotation;
  5698. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5699. this.matrix.copy( source.matrix );
  5700. this.generateMipmaps = source.generateMipmaps;
  5701. this.premultiplyAlpha = source.premultiplyAlpha;
  5702. this.flipY = source.flipY;
  5703. this.unpackAlignment = source.unpackAlignment;
  5704. this.colorSpace = source.colorSpace;
  5705. this.renderTarget = source.renderTarget;
  5706. this.isRenderTargetTexture = source.isRenderTargetTexture;
  5707. this.isArrayTexture = source.isArrayTexture;
  5708. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5709. this.needsUpdate = true;
  5710. return this;
  5711. }
  5712. /**
  5713. * Sets this texture's properties based on `values`.
  5714. * @param {Object} values - A container with texture parameters.
  5715. */
  5716. setValues( values ) {
  5717. for ( const key in values ) {
  5718. const newValue = values[ key ];
  5719. if ( newValue === undefined ) {
  5720. console.warn( `THREE.Texture.setValues(): parameter '${ key }' has value of undefined.` );
  5721. continue;
  5722. }
  5723. const currentValue = this[ key ];
  5724. if ( currentValue === undefined ) {
  5725. console.warn( `THREE.Texture.setValues(): property '${ key }' does not exist.` );
  5726. continue;
  5727. }
  5728. if ( ( currentValue && newValue ) && ( currentValue.isVector2 && newValue.isVector2 ) ) {
  5729. currentValue.copy( newValue );
  5730. } else if ( ( currentValue && newValue ) && ( currentValue.isVector3 && newValue.isVector3 ) ) {
  5731. currentValue.copy( newValue );
  5732. } else if ( ( currentValue && newValue ) && ( currentValue.isMatrix3 && newValue.isMatrix3 ) ) {
  5733. currentValue.copy( newValue );
  5734. } else {
  5735. this[ key ] = newValue;
  5736. }
  5737. }
  5738. }
  5739. /**
  5740. * Serializes the texture into JSON.
  5741. *
  5742. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5743. * @return {Object} A JSON object representing the serialized texture.
  5744. * @see {@link ObjectLoader#parse}
  5745. */
  5746. toJSON( meta ) {
  5747. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5748. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  5749. return meta.textures[ this.uuid ];
  5750. }
  5751. const output = {
  5752. metadata: {
  5753. version: 4.7,
  5754. type: 'Texture',
  5755. generator: 'Texture.toJSON'
  5756. },
  5757. uuid: this.uuid,
  5758. name: this.name,
  5759. image: this.source.toJSON( meta ).uuid,
  5760. mapping: this.mapping,
  5761. channel: this.channel,
  5762. repeat: [ this.repeat.x, this.repeat.y ],
  5763. offset: [ this.offset.x, this.offset.y ],
  5764. center: [ this.center.x, this.center.y ],
  5765. rotation: this.rotation,
  5766. wrap: [ this.wrapS, this.wrapT ],
  5767. format: this.format,
  5768. internalFormat: this.internalFormat,
  5769. type: this.type,
  5770. colorSpace: this.colorSpace,
  5771. minFilter: this.minFilter,
  5772. magFilter: this.magFilter,
  5773. anisotropy: this.anisotropy,
  5774. flipY: this.flipY,
  5775. generateMipmaps: this.generateMipmaps,
  5776. premultiplyAlpha: this.premultiplyAlpha,
  5777. unpackAlignment: this.unpackAlignment
  5778. };
  5779. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  5780. if ( ! isRootObject ) {
  5781. meta.textures[ this.uuid ] = output;
  5782. }
  5783. return output;
  5784. }
  5785. /**
  5786. * Frees the GPU-related resources allocated by this instance. Call this
  5787. * method whenever this instance is no longer used in your app.
  5788. *
  5789. * @fires Texture#dispose
  5790. */
  5791. dispose() {
  5792. /**
  5793. * Fires when the texture has been disposed of.
  5794. *
  5795. * @event Texture#dispose
  5796. * @type {Object}
  5797. */
  5798. this.dispatchEvent( { type: 'dispose' } );
  5799. }
  5800. /**
  5801. * Transforms the given uv vector with the textures uv transformation matrix.
  5802. *
  5803. * @param {Vector2} uv - The uv vector.
  5804. * @return {Vector2} The transformed uv vector.
  5805. */
  5806. transformUv( uv ) {
  5807. if ( this.mapping !== UVMapping ) return uv;
  5808. uv.applyMatrix3( this.matrix );
  5809. if ( uv.x < 0 || uv.x > 1 ) {
  5810. switch ( this.wrapS ) {
  5811. case RepeatWrapping:
  5812. uv.x = uv.x - Math.floor( uv.x );
  5813. break;
  5814. case ClampToEdgeWrapping:
  5815. uv.x = uv.x < 0 ? 0 : 1;
  5816. break;
  5817. case MirroredRepeatWrapping:
  5818. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  5819. uv.x = Math.ceil( uv.x ) - uv.x;
  5820. } else {
  5821. uv.x = uv.x - Math.floor( uv.x );
  5822. }
  5823. break;
  5824. }
  5825. }
  5826. if ( uv.y < 0 || uv.y > 1 ) {
  5827. switch ( this.wrapT ) {
  5828. case RepeatWrapping:
  5829. uv.y = uv.y - Math.floor( uv.y );
  5830. break;
  5831. case ClampToEdgeWrapping:
  5832. uv.y = uv.y < 0 ? 0 : 1;
  5833. break;
  5834. case MirroredRepeatWrapping:
  5835. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  5836. uv.y = Math.ceil( uv.y ) - uv.y;
  5837. } else {
  5838. uv.y = uv.y - Math.floor( uv.y );
  5839. }
  5840. break;
  5841. }
  5842. }
  5843. if ( this.flipY ) {
  5844. uv.y = 1 - uv.y;
  5845. }
  5846. return uv;
  5847. }
  5848. /**
  5849. * Setting this property to `true` indicates the engine the texture
  5850. * must be updated in the next render. This triggers a texture upload
  5851. * to the GPU and ensures correct texture parameter configuration.
  5852. *
  5853. * @type {boolean}
  5854. * @default false
  5855. * @param {boolean} value
  5856. */
  5857. set needsUpdate( value ) {
  5858. if ( value === true ) {
  5859. this.version ++;
  5860. this.source.needsUpdate = true;
  5861. }
  5862. }
  5863. /**
  5864. * Setting this property to `true` indicates the engine the PMREM
  5865. * must be regenerated.
  5866. *
  5867. * @type {boolean}
  5868. * @default false
  5869. * @param {boolean} value
  5870. */
  5871. set needsPMREMUpdate( value ) {
  5872. if ( value === true ) {
  5873. this.pmremVersion ++;
  5874. }
  5875. }
  5876. }
  5877. /**
  5878. * The default image for all textures.
  5879. *
  5880. * @static
  5881. * @type {?Image}
  5882. * @default null
  5883. */
  5884. Texture.DEFAULT_IMAGE = null;
  5885. /**
  5886. * The default mapping for all textures.
  5887. *
  5888. * @static
  5889. * @type {number}
  5890. * @default UVMapping
  5891. */
  5892. Texture.DEFAULT_MAPPING = UVMapping;
  5893. /**
  5894. * The default anisotropy value for all textures.
  5895. *
  5896. * @static
  5897. * @type {number}
  5898. * @default 1
  5899. */
  5900. Texture.DEFAULT_ANISOTROPY = 1;
  5901. /**
  5902. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  5903. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  5904. *
  5905. * - A point in 4D space.
  5906. * - A direction and length in 4D space. In three.js the length will
  5907. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  5908. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  5909. * - Any arbitrary ordered quadruplet of numbers.
  5910. *
  5911. * There are other things a 4D vector can be used to represent, however these
  5912. * are the most common uses in *three.js*.
  5913. *
  5914. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  5915. * the corresponding order.
  5916. * ```js
  5917. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  5918. *
  5919. * //no arguments; will be initialised to (0, 0, 0, 1)
  5920. * const b = new THREE.Vector4( );
  5921. *
  5922. * const d = a.dot( b );
  5923. * ```
  5924. */
  5925. class Vector4 {
  5926. /**
  5927. * Constructs a new 4D vector.
  5928. *
  5929. * @param {number} [x=0] - The x value of this vector.
  5930. * @param {number} [y=0] - The y value of this vector.
  5931. * @param {number} [z=0] - The z value of this vector.
  5932. * @param {number} [w=1] - The w value of this vector.
  5933. */
  5934. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  5935. /**
  5936. * This flag can be used for type testing.
  5937. *
  5938. * @type {boolean}
  5939. * @readonly
  5940. * @default true
  5941. */
  5942. Vector4.prototype.isVector4 = true;
  5943. /**
  5944. * The x value of this vector.
  5945. *
  5946. * @type {number}
  5947. */
  5948. this.x = x;
  5949. /**
  5950. * The y value of this vector.
  5951. *
  5952. * @type {number}
  5953. */
  5954. this.y = y;
  5955. /**
  5956. * The z value of this vector.
  5957. *
  5958. * @type {number}
  5959. */
  5960. this.z = z;
  5961. /**
  5962. * The w value of this vector.
  5963. *
  5964. * @type {number}
  5965. */
  5966. this.w = w;
  5967. }
  5968. /**
  5969. * Alias for {@link Vector4#z}.
  5970. *
  5971. * @type {number}
  5972. */
  5973. get width() {
  5974. return this.z;
  5975. }
  5976. set width( value ) {
  5977. this.z = value;
  5978. }
  5979. /**
  5980. * Alias for {@link Vector4#w}.
  5981. *
  5982. * @type {number}
  5983. */
  5984. get height() {
  5985. return this.w;
  5986. }
  5987. set height( value ) {
  5988. this.w = value;
  5989. }
  5990. /**
  5991. * Sets the vector components.
  5992. *
  5993. * @param {number} x - The value of the x component.
  5994. * @param {number} y - The value of the y component.
  5995. * @param {number} z - The value of the z component.
  5996. * @param {number} w - The value of the w component.
  5997. * @return {Vector4} A reference to this vector.
  5998. */
  5999. set( x, y, z, w ) {
  6000. this.x = x;
  6001. this.y = y;
  6002. this.z = z;
  6003. this.w = w;
  6004. return this;
  6005. }
  6006. /**
  6007. * Sets the vector components to the same value.
  6008. *
  6009. * @param {number} scalar - The value to set for all vector components.
  6010. * @return {Vector4} A reference to this vector.
  6011. */
  6012. setScalar( scalar ) {
  6013. this.x = scalar;
  6014. this.y = scalar;
  6015. this.z = scalar;
  6016. this.w = scalar;
  6017. return this;
  6018. }
  6019. /**
  6020. * Sets the vector's x component to the given value
  6021. *
  6022. * @param {number} x - The value to set.
  6023. * @return {Vector4} A reference to this vector.
  6024. */
  6025. setX( x ) {
  6026. this.x = x;
  6027. return this;
  6028. }
  6029. /**
  6030. * Sets the vector's y component to the given value
  6031. *
  6032. * @param {number} y - The value to set.
  6033. * @return {Vector4} A reference to this vector.
  6034. */
  6035. setY( y ) {
  6036. this.y = y;
  6037. return this;
  6038. }
  6039. /**
  6040. * Sets the vector's z component to the given value
  6041. *
  6042. * @param {number} z - The value to set.
  6043. * @return {Vector4} A reference to this vector.
  6044. */
  6045. setZ( z ) {
  6046. this.z = z;
  6047. return this;
  6048. }
  6049. /**
  6050. * Sets the vector's w component to the given value
  6051. *
  6052. * @param {number} w - The value to set.
  6053. * @return {Vector4} A reference to this vector.
  6054. */
  6055. setW( w ) {
  6056. this.w = w;
  6057. return this;
  6058. }
  6059. /**
  6060. * Allows to set a vector component with an index.
  6061. *
  6062. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6063. * `2` equals to z, `3` equals to w.
  6064. * @param {number} value - The value to set.
  6065. * @return {Vector4} A reference to this vector.
  6066. */
  6067. setComponent( index, value ) {
  6068. switch ( index ) {
  6069. case 0: this.x = value; break;
  6070. case 1: this.y = value; break;
  6071. case 2: this.z = value; break;
  6072. case 3: this.w = value; break;
  6073. default: throw new Error( 'index is out of range: ' + index );
  6074. }
  6075. return this;
  6076. }
  6077. /**
  6078. * Returns the value of the vector component which matches the given index.
  6079. *
  6080. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6081. * `2` equals to z, `3` equals to w.
  6082. * @return {number} A vector component value.
  6083. */
  6084. getComponent( index ) {
  6085. switch ( index ) {
  6086. case 0: return this.x;
  6087. case 1: return this.y;
  6088. case 2: return this.z;
  6089. case 3: return this.w;
  6090. default: throw new Error( 'index is out of range: ' + index );
  6091. }
  6092. }
  6093. /**
  6094. * Returns a new vector with copied values from this instance.
  6095. *
  6096. * @return {Vector4} A clone of this instance.
  6097. */
  6098. clone() {
  6099. return new this.constructor( this.x, this.y, this.z, this.w );
  6100. }
  6101. /**
  6102. * Copies the values of the given vector to this instance.
  6103. *
  6104. * @param {Vector3|Vector4} v - The vector to copy.
  6105. * @return {Vector4} A reference to this vector.
  6106. */
  6107. copy( v ) {
  6108. this.x = v.x;
  6109. this.y = v.y;
  6110. this.z = v.z;
  6111. this.w = ( v.w !== undefined ) ? v.w : 1;
  6112. return this;
  6113. }
  6114. /**
  6115. * Adds the given vector to this instance.
  6116. *
  6117. * @param {Vector4} v - The vector to add.
  6118. * @return {Vector4} A reference to this vector.
  6119. */
  6120. add( v ) {
  6121. this.x += v.x;
  6122. this.y += v.y;
  6123. this.z += v.z;
  6124. this.w += v.w;
  6125. return this;
  6126. }
  6127. /**
  6128. * Adds the given scalar value to all components of this instance.
  6129. *
  6130. * @param {number} s - The scalar to add.
  6131. * @return {Vector4} A reference to this vector.
  6132. */
  6133. addScalar( s ) {
  6134. this.x += s;
  6135. this.y += s;
  6136. this.z += s;
  6137. this.w += s;
  6138. return this;
  6139. }
  6140. /**
  6141. * Adds the given vectors and stores the result in this instance.
  6142. *
  6143. * @param {Vector4} a - The first vector.
  6144. * @param {Vector4} b - The second vector.
  6145. * @return {Vector4} A reference to this vector.
  6146. */
  6147. addVectors( a, b ) {
  6148. this.x = a.x + b.x;
  6149. this.y = a.y + b.y;
  6150. this.z = a.z + b.z;
  6151. this.w = a.w + b.w;
  6152. return this;
  6153. }
  6154. /**
  6155. * Adds the given vector scaled by the given factor to this instance.
  6156. *
  6157. * @param {Vector4} v - The vector.
  6158. * @param {number} s - The factor that scales `v`.
  6159. * @return {Vector4} A reference to this vector.
  6160. */
  6161. addScaledVector( v, s ) {
  6162. this.x += v.x * s;
  6163. this.y += v.y * s;
  6164. this.z += v.z * s;
  6165. this.w += v.w * s;
  6166. return this;
  6167. }
  6168. /**
  6169. * Subtracts the given vector from this instance.
  6170. *
  6171. * @param {Vector4} v - The vector to subtract.
  6172. * @return {Vector4} A reference to this vector.
  6173. */
  6174. sub( v ) {
  6175. this.x -= v.x;
  6176. this.y -= v.y;
  6177. this.z -= v.z;
  6178. this.w -= v.w;
  6179. return this;
  6180. }
  6181. /**
  6182. * Subtracts the given scalar value from all components of this instance.
  6183. *
  6184. * @param {number} s - The scalar to subtract.
  6185. * @return {Vector4} A reference to this vector.
  6186. */
  6187. subScalar( s ) {
  6188. this.x -= s;
  6189. this.y -= s;
  6190. this.z -= s;
  6191. this.w -= s;
  6192. return this;
  6193. }
  6194. /**
  6195. * Subtracts the given vectors and stores the result in this instance.
  6196. *
  6197. * @param {Vector4} a - The first vector.
  6198. * @param {Vector4} b - The second vector.
  6199. * @return {Vector4} A reference to this vector.
  6200. */
  6201. subVectors( a, b ) {
  6202. this.x = a.x - b.x;
  6203. this.y = a.y - b.y;
  6204. this.z = a.z - b.z;
  6205. this.w = a.w - b.w;
  6206. return this;
  6207. }
  6208. /**
  6209. * Multiplies the given vector with this instance.
  6210. *
  6211. * @param {Vector4} v - The vector to multiply.
  6212. * @return {Vector4} A reference to this vector.
  6213. */
  6214. multiply( v ) {
  6215. this.x *= v.x;
  6216. this.y *= v.y;
  6217. this.z *= v.z;
  6218. this.w *= v.w;
  6219. return this;
  6220. }
  6221. /**
  6222. * Multiplies the given scalar value with all components of this instance.
  6223. *
  6224. * @param {number} scalar - The scalar to multiply.
  6225. * @return {Vector4} A reference to this vector.
  6226. */
  6227. multiplyScalar( scalar ) {
  6228. this.x *= scalar;
  6229. this.y *= scalar;
  6230. this.z *= scalar;
  6231. this.w *= scalar;
  6232. return this;
  6233. }
  6234. /**
  6235. * Multiplies this vector with the given 4x4 matrix.
  6236. *
  6237. * @param {Matrix4} m - The 4x4 matrix.
  6238. * @return {Vector4} A reference to this vector.
  6239. */
  6240. applyMatrix4( m ) {
  6241. const x = this.x, y = this.y, z = this.z, w = this.w;
  6242. const e = m.elements;
  6243. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6244. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6245. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6246. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6247. return this;
  6248. }
  6249. /**
  6250. * Divides this instance by the given vector.
  6251. *
  6252. * @param {Vector4} v - The vector to divide.
  6253. * @return {Vector4} A reference to this vector.
  6254. */
  6255. divide( v ) {
  6256. this.x /= v.x;
  6257. this.y /= v.y;
  6258. this.z /= v.z;
  6259. this.w /= v.w;
  6260. return this;
  6261. }
  6262. /**
  6263. * Divides this vector by the given scalar.
  6264. *
  6265. * @param {number} scalar - The scalar to divide.
  6266. * @return {Vector4} A reference to this vector.
  6267. */
  6268. divideScalar( scalar ) {
  6269. return this.multiplyScalar( 1 / scalar );
  6270. }
  6271. /**
  6272. * Sets the x, y and z components of this
  6273. * vector to the quaternion's axis and w to the angle.
  6274. *
  6275. * @param {Quaternion} q - The Quaternion to set.
  6276. * @return {Vector4} A reference to this vector.
  6277. */
  6278. setAxisAngleFromQuaternion( q ) {
  6279. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6280. // q is assumed to be normalized
  6281. this.w = 2 * Math.acos( q.w );
  6282. const s = Math.sqrt( 1 - q.w * q.w );
  6283. if ( s < 0.0001 ) {
  6284. this.x = 1;
  6285. this.y = 0;
  6286. this.z = 0;
  6287. } else {
  6288. this.x = q.x / s;
  6289. this.y = q.y / s;
  6290. this.z = q.z / s;
  6291. }
  6292. return this;
  6293. }
  6294. /**
  6295. * Sets the x, y and z components of this
  6296. * vector to the axis of rotation and w to the angle.
  6297. *
  6298. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  6299. * @return {Vector4} A reference to this vector.
  6300. */
  6301. setAxisAngleFromRotationMatrix( m ) {
  6302. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6303. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6304. let angle, x, y, z; // variables for result
  6305. const epsilon = 0.01, // margin to allow for rounding errors
  6306. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6307. te = m.elements,
  6308. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6309. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6310. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6311. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6312. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6313. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6314. // singularity found
  6315. // first check for identity matrix which must have +1 for all terms
  6316. // in leading diagonal and zero in other terms
  6317. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6318. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6319. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6320. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6321. // this singularity is identity matrix so angle = 0
  6322. this.set( 1, 0, 0, 0 );
  6323. return this; // zero angle, arbitrary axis
  6324. }
  6325. // otherwise this singularity is angle = 180
  6326. angle = Math.PI;
  6327. const xx = ( m11 + 1 ) / 2;
  6328. const yy = ( m22 + 1 ) / 2;
  6329. const zz = ( m33 + 1 ) / 2;
  6330. const xy = ( m12 + m21 ) / 4;
  6331. const xz = ( m13 + m31 ) / 4;
  6332. const yz = ( m23 + m32 ) / 4;
  6333. if ( ( xx > yy ) && ( xx > zz ) ) {
  6334. // m11 is the largest diagonal term
  6335. if ( xx < epsilon ) {
  6336. x = 0;
  6337. y = 0.707106781;
  6338. z = 0.707106781;
  6339. } else {
  6340. x = Math.sqrt( xx );
  6341. y = xy / x;
  6342. z = xz / x;
  6343. }
  6344. } else if ( yy > zz ) {
  6345. // m22 is the largest diagonal term
  6346. if ( yy < epsilon ) {
  6347. x = 0.707106781;
  6348. y = 0;
  6349. z = 0.707106781;
  6350. } else {
  6351. y = Math.sqrt( yy );
  6352. x = xy / y;
  6353. z = yz / y;
  6354. }
  6355. } else {
  6356. // m33 is the largest diagonal term so base result on this
  6357. if ( zz < epsilon ) {
  6358. x = 0.707106781;
  6359. y = 0.707106781;
  6360. z = 0;
  6361. } else {
  6362. z = Math.sqrt( zz );
  6363. x = xz / z;
  6364. y = yz / z;
  6365. }
  6366. }
  6367. this.set( x, y, z, angle );
  6368. return this; // return 180 deg rotation
  6369. }
  6370. // as we have reached here there are no singularities so we can handle normally
  6371. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6372. ( m13 - m31 ) * ( m13 - m31 ) +
  6373. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6374. if ( Math.abs( s ) < 0.001 ) s = 1;
  6375. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6376. // caught by singularity test above, but I've left it in just in case
  6377. this.x = ( m32 - m23 ) / s;
  6378. this.y = ( m13 - m31 ) / s;
  6379. this.z = ( m21 - m12 ) / s;
  6380. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6381. return this;
  6382. }
  6383. /**
  6384. * Sets the vector components to the position elements of the
  6385. * given transformation matrix.
  6386. *
  6387. * @param {Matrix4} m - The 4x4 matrix.
  6388. * @return {Vector4} A reference to this vector.
  6389. */
  6390. setFromMatrixPosition( m ) {
  6391. const e = m.elements;
  6392. this.x = e[ 12 ];
  6393. this.y = e[ 13 ];
  6394. this.z = e[ 14 ];
  6395. this.w = e[ 15 ];
  6396. return this;
  6397. }
  6398. /**
  6399. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  6400. * value, replace that value with the corresponding min value.
  6401. *
  6402. * @param {Vector4} v - The vector.
  6403. * @return {Vector4} A reference to this vector.
  6404. */
  6405. min( v ) {
  6406. this.x = Math.min( this.x, v.x );
  6407. this.y = Math.min( this.y, v.y );
  6408. this.z = Math.min( this.z, v.z );
  6409. this.w = Math.min( this.w, v.w );
  6410. return this;
  6411. }
  6412. /**
  6413. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  6414. * value, replace that value with the corresponding max value.
  6415. *
  6416. * @param {Vector4} v - The vector.
  6417. * @return {Vector4} A reference to this vector.
  6418. */
  6419. max( v ) {
  6420. this.x = Math.max( this.x, v.x );
  6421. this.y = Math.max( this.y, v.y );
  6422. this.z = Math.max( this.z, v.z );
  6423. this.w = Math.max( this.w, v.w );
  6424. return this;
  6425. }
  6426. /**
  6427. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  6428. * value, it is replaced by the corresponding value.
  6429. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  6430. * it is replaced by the corresponding value.
  6431. *
  6432. * @param {Vector4} min - The minimum x, y and z values.
  6433. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  6434. * @return {Vector4} A reference to this vector.
  6435. */
  6436. clamp( min, max ) {
  6437. // assumes min < max, componentwise
  6438. this.x = clamp( this.x, min.x, max.x );
  6439. this.y = clamp( this.y, min.y, max.y );
  6440. this.z = clamp( this.z, min.z, max.z );
  6441. this.w = clamp( this.w, min.w, max.w );
  6442. return this;
  6443. }
  6444. /**
  6445. * If this vector's x, y, z or w values are greater than the max value, they are
  6446. * replaced by the max value.
  6447. * If this vector's x, y, z or w values are less than the min value, they are
  6448. * replaced by the min value.
  6449. *
  6450. * @param {number} minVal - The minimum value the components will be clamped to.
  6451. * @param {number} maxVal - The maximum value the components will be clamped to.
  6452. * @return {Vector4} A reference to this vector.
  6453. */
  6454. clampScalar( minVal, maxVal ) {
  6455. this.x = clamp( this.x, minVal, maxVal );
  6456. this.y = clamp( this.y, minVal, maxVal );
  6457. this.z = clamp( this.z, minVal, maxVal );
  6458. this.w = clamp( this.w, minVal, maxVal );
  6459. return this;
  6460. }
  6461. /**
  6462. * If this vector's length is greater than the max value, it is replaced by
  6463. * the max value.
  6464. * If this vector's length is less than the min value, it is replaced by the
  6465. * min value.
  6466. *
  6467. * @param {number} min - The minimum value the vector length will be clamped to.
  6468. * @param {number} max - The maximum value the vector length will be clamped to.
  6469. * @return {Vector4} A reference to this vector.
  6470. */
  6471. clampLength( min, max ) {
  6472. const length = this.length();
  6473. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6474. }
  6475. /**
  6476. * The components of this vector are rounded down to the nearest integer value.
  6477. *
  6478. * @return {Vector4} A reference to this vector.
  6479. */
  6480. floor() {
  6481. this.x = Math.floor( this.x );
  6482. this.y = Math.floor( this.y );
  6483. this.z = Math.floor( this.z );
  6484. this.w = Math.floor( this.w );
  6485. return this;
  6486. }
  6487. /**
  6488. * The components of this vector are rounded up to the nearest integer value.
  6489. *
  6490. * @return {Vector4} A reference to this vector.
  6491. */
  6492. ceil() {
  6493. this.x = Math.ceil( this.x );
  6494. this.y = Math.ceil( this.y );
  6495. this.z = Math.ceil( this.z );
  6496. this.w = Math.ceil( this.w );
  6497. return this;
  6498. }
  6499. /**
  6500. * The components of this vector are rounded to the nearest integer value
  6501. *
  6502. * @return {Vector4} A reference to this vector.
  6503. */
  6504. round() {
  6505. this.x = Math.round( this.x );
  6506. this.y = Math.round( this.y );
  6507. this.z = Math.round( this.z );
  6508. this.w = Math.round( this.w );
  6509. return this;
  6510. }
  6511. /**
  6512. * The components of this vector are rounded towards zero (up if negative,
  6513. * down if positive) to an integer value.
  6514. *
  6515. * @return {Vector4} A reference to this vector.
  6516. */
  6517. roundToZero() {
  6518. this.x = Math.trunc( this.x );
  6519. this.y = Math.trunc( this.y );
  6520. this.z = Math.trunc( this.z );
  6521. this.w = Math.trunc( this.w );
  6522. return this;
  6523. }
  6524. /**
  6525. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  6526. *
  6527. * @return {Vector4} A reference to this vector.
  6528. */
  6529. negate() {
  6530. this.x = - this.x;
  6531. this.y = - this.y;
  6532. this.z = - this.z;
  6533. this.w = - this.w;
  6534. return this;
  6535. }
  6536. /**
  6537. * Calculates the dot product of the given vector with this instance.
  6538. *
  6539. * @param {Vector4} v - The vector to compute the dot product with.
  6540. * @return {number} The result of the dot product.
  6541. */
  6542. dot( v ) {
  6543. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6544. }
  6545. /**
  6546. * Computes the square of the Euclidean length (straight-line length) from
  6547. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  6548. * compare the length squared instead as it is slightly more efficient to calculate.
  6549. *
  6550. * @return {number} The square length of this vector.
  6551. */
  6552. lengthSq() {
  6553. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6554. }
  6555. /**
  6556. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  6557. *
  6558. * @return {number} The length of this vector.
  6559. */
  6560. length() {
  6561. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6562. }
  6563. /**
  6564. * Computes the Manhattan length of this vector.
  6565. *
  6566. * @return {number} The length of this vector.
  6567. */
  6568. manhattanLength() {
  6569. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6570. }
  6571. /**
  6572. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6573. * with the same direction as this one, but with a vector length of `1`.
  6574. *
  6575. * @return {Vector4} A reference to this vector.
  6576. */
  6577. normalize() {
  6578. return this.divideScalar( this.length() || 1 );
  6579. }
  6580. /**
  6581. * Sets this vector to a vector with the same direction as this one, but
  6582. * with the specified length.
  6583. *
  6584. * @param {number} length - The new length of this vector.
  6585. * @return {Vector4} A reference to this vector.
  6586. */
  6587. setLength( length ) {
  6588. return this.normalize().multiplyScalar( length );
  6589. }
  6590. /**
  6591. * Linearly interpolates between the given vector and this instance, where
  6592. * alpha is the percent distance along the line - alpha = 0 will be this
  6593. * vector, and alpha = 1 will be the given one.
  6594. *
  6595. * @param {Vector4} v - The vector to interpolate towards.
  6596. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6597. * @return {Vector4} A reference to this vector.
  6598. */
  6599. lerp( v, alpha ) {
  6600. this.x += ( v.x - this.x ) * alpha;
  6601. this.y += ( v.y - this.y ) * alpha;
  6602. this.z += ( v.z - this.z ) * alpha;
  6603. this.w += ( v.w - this.w ) * alpha;
  6604. return this;
  6605. }
  6606. /**
  6607. * Linearly interpolates between the given vectors, where alpha is the percent
  6608. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6609. * be the second one. The result is stored in this instance.
  6610. *
  6611. * @param {Vector4} v1 - The first vector.
  6612. * @param {Vector4} v2 - The second vector.
  6613. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6614. * @return {Vector4} A reference to this vector.
  6615. */
  6616. lerpVectors( v1, v2, alpha ) {
  6617. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6618. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6619. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6620. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  6621. return this;
  6622. }
  6623. /**
  6624. * Returns `true` if this vector is equal with the given one.
  6625. *
  6626. * @param {Vector4} v - The vector to test for equality.
  6627. * @return {boolean} Whether this vector is equal with the given one.
  6628. */
  6629. equals( v ) {
  6630. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6631. }
  6632. /**
  6633. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  6634. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  6635. *
  6636. * @param {Array<number>} array - An array holding the vector component values.
  6637. * @param {number} [offset=0] - The offset into the array.
  6638. * @return {Vector4} A reference to this vector.
  6639. */
  6640. fromArray( array, offset = 0 ) {
  6641. this.x = array[ offset ];
  6642. this.y = array[ offset + 1 ];
  6643. this.z = array[ offset + 2 ];
  6644. this.w = array[ offset + 3 ];
  6645. return this;
  6646. }
  6647. /**
  6648. * Writes the components of this vector to the given array. If no array is provided,
  6649. * the method returns a new instance.
  6650. *
  6651. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  6652. * @param {number} [offset=0] - Index of the first element in the array.
  6653. * @return {Array<number>} The vector components.
  6654. */
  6655. toArray( array = [], offset = 0 ) {
  6656. array[ offset ] = this.x;
  6657. array[ offset + 1 ] = this.y;
  6658. array[ offset + 2 ] = this.z;
  6659. array[ offset + 3 ] = this.w;
  6660. return array;
  6661. }
  6662. /**
  6663. * Sets the components of this vector from the given buffer attribute.
  6664. *
  6665. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  6666. * @param {number} index - The index into the attribute.
  6667. * @return {Vector4} A reference to this vector.
  6668. */
  6669. fromBufferAttribute( attribute, index ) {
  6670. this.x = attribute.getX( index );
  6671. this.y = attribute.getY( index );
  6672. this.z = attribute.getZ( index );
  6673. this.w = attribute.getW( index );
  6674. return this;
  6675. }
  6676. /**
  6677. * Sets each component of this vector to a pseudo-random value between `0` and
  6678. * `1`, excluding `1`.
  6679. *
  6680. * @return {Vector4} A reference to this vector.
  6681. */
  6682. random() {
  6683. this.x = Math.random();
  6684. this.y = Math.random();
  6685. this.z = Math.random();
  6686. this.w = Math.random();
  6687. return this;
  6688. }
  6689. *[ Symbol.iterator ]() {
  6690. yield this.x;
  6691. yield this.y;
  6692. yield this.z;
  6693. yield this.w;
  6694. }
  6695. }
  6696. /**
  6697. * A render target is a buffer where the video card draws pixels for a scene
  6698. * that is being rendered in the background. It is used in different effects,
  6699. * such as applying postprocessing to a rendered image before displaying it
  6700. * on the screen.
  6701. *
  6702. * @augments EventDispatcher
  6703. */
  6704. class RenderTarget extends EventDispatcher {
  6705. /**
  6706. * Render target options.
  6707. *
  6708. * @typedef {Object} RenderTarget~Options
  6709. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  6710. * @property {number} [magFilter=LinearFilter] - The mag filter.
  6711. * @property {number} [minFilter=LinearFilter] - The min filter.
  6712. * @property {number} [format=RGBAFormat] - The texture format.
  6713. * @property {number} [type=UnsignedByteType] - The texture type.
  6714. * @property {?string} [internalFormat=null] - The texture's internal format.
  6715. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6716. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6717. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  6718. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  6719. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  6720. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  6721. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  6722. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  6723. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  6724. * @property {number} [samples=0] - The MSAA samples count.
  6725. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  6726. * @property {number} [depth=1] - The texture depth.
  6727. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering.
  6728. */
  6729. /**
  6730. * Constructs a new render target.
  6731. *
  6732. * @param {number} [width=1] - The width of the render target.
  6733. * @param {number} [height=1] - The height of the render target.
  6734. * @param {RenderTarget~Options} [options] - The configuration object.
  6735. */
  6736. constructor( width = 1, height = 1, options = {} ) {
  6737. super();
  6738. options = Object.assign( {
  6739. generateMipmaps: false,
  6740. internalFormat: null,
  6741. minFilter: LinearFilter,
  6742. depthBuffer: true,
  6743. stencilBuffer: false,
  6744. resolveDepthBuffer: true,
  6745. resolveStencilBuffer: true,
  6746. depthTexture: null,
  6747. samples: 0,
  6748. count: 1,
  6749. depth: 1,
  6750. multiview: false
  6751. }, options );
  6752. /**
  6753. * This flag can be used for type testing.
  6754. *
  6755. * @type {boolean}
  6756. * @readonly
  6757. * @default true
  6758. */
  6759. this.isRenderTarget = true;
  6760. /**
  6761. * The width of the render target.
  6762. *
  6763. * @type {number}
  6764. * @default 1
  6765. */
  6766. this.width = width;
  6767. /**
  6768. * The height of the render target.
  6769. *
  6770. * @type {number}
  6771. * @default 1
  6772. */
  6773. this.height = height;
  6774. /**
  6775. * The depth of the render target.
  6776. *
  6777. * @type {number}
  6778. * @default 1
  6779. */
  6780. this.depth = options.depth;
  6781. /**
  6782. * A rectangular area inside the render target's viewport. Fragments that are
  6783. * outside the area will be discarded.
  6784. *
  6785. * @type {Vector4}
  6786. * @default (0,0,width,height)
  6787. */
  6788. this.scissor = new Vector4( 0, 0, width, height );
  6789. /**
  6790. * Indicates whether the scissor test should be enabled when rendering into
  6791. * this render target or not.
  6792. *
  6793. * @type {boolean}
  6794. * @default false
  6795. */
  6796. this.scissorTest = false;
  6797. /**
  6798. * A rectangular area representing the render target's viewport.
  6799. *
  6800. * @type {Vector4}
  6801. * @default (0,0,width,height)
  6802. */
  6803. this.viewport = new Vector4( 0, 0, width, height );
  6804. const image = { width: width, height: height, depth: options.depth };
  6805. const texture = new Texture( image );
  6806. /**
  6807. * An array of textures. Each color attachment is represented as a separate texture.
  6808. * Has at least a single entry for the default color attachment.
  6809. *
  6810. * @type {Array<Texture>}
  6811. */
  6812. this.textures = [];
  6813. const count = options.count;
  6814. for ( let i = 0; i < count; i ++ ) {
  6815. this.textures[ i ] = texture.clone();
  6816. this.textures[ i ].isRenderTargetTexture = true;
  6817. this.textures[ i ].renderTarget = this;
  6818. }
  6819. this._setTextureOptions( options );
  6820. /**
  6821. * Whether to allocate a depth buffer or not.
  6822. *
  6823. * @type {boolean}
  6824. * @default true
  6825. */
  6826. this.depthBuffer = options.depthBuffer;
  6827. /**
  6828. * Whether to allocate a stencil buffer or not.
  6829. *
  6830. * @type {boolean}
  6831. * @default false
  6832. */
  6833. this.stencilBuffer = options.stencilBuffer;
  6834. /**
  6835. * Whether to resolve the depth buffer or not.
  6836. *
  6837. * @type {boolean}
  6838. * @default true
  6839. */
  6840. this.resolveDepthBuffer = options.resolveDepthBuffer;
  6841. /**
  6842. * Whether to resolve the stencil buffer or not.
  6843. *
  6844. * @type {boolean}
  6845. * @default true
  6846. */
  6847. this.resolveStencilBuffer = options.resolveStencilBuffer;
  6848. this._depthTexture = null;
  6849. this.depthTexture = options.depthTexture;
  6850. /**
  6851. * The number of MSAA samples.
  6852. *
  6853. * A value of `0` disables MSAA.
  6854. *
  6855. * @type {number}
  6856. * @default 0
  6857. */
  6858. this.samples = options.samples;
  6859. /**
  6860. * Whether to this target is used in multiview rendering.
  6861. *
  6862. * @type {boolean}
  6863. * @default false
  6864. */
  6865. this.multiview = options.multiview;
  6866. }
  6867. _setTextureOptions( options = {} ) {
  6868. const values = {
  6869. minFilter: LinearFilter,
  6870. generateMipmaps: false,
  6871. flipY: false,
  6872. internalFormat: null
  6873. };
  6874. if ( options.mapping !== undefined ) values.mapping = options.mapping;
  6875. if ( options.wrapS !== undefined ) values.wrapS = options.wrapS;
  6876. if ( options.wrapT !== undefined ) values.wrapT = options.wrapT;
  6877. if ( options.wrapR !== undefined ) values.wrapR = options.wrapR;
  6878. if ( options.magFilter !== undefined ) values.magFilter = options.magFilter;
  6879. if ( options.minFilter !== undefined ) values.minFilter = options.minFilter;
  6880. if ( options.format !== undefined ) values.format = options.format;
  6881. if ( options.type !== undefined ) values.type = options.type;
  6882. if ( options.anisotropy !== undefined ) values.anisotropy = options.anisotropy;
  6883. if ( options.colorSpace !== undefined ) values.colorSpace = options.colorSpace;
  6884. if ( options.flipY !== undefined ) values.flipY = options.flipY;
  6885. if ( options.generateMipmaps !== undefined ) values.generateMipmaps = options.generateMipmaps;
  6886. if ( options.internalFormat !== undefined ) values.internalFormat = options.internalFormat;
  6887. for ( let i = 0; i < this.textures.length; i ++ ) {
  6888. const texture = this.textures[ i ];
  6889. texture.setValues( values );
  6890. }
  6891. }
  6892. /**
  6893. * The texture representing the default color attachment.
  6894. *
  6895. * @type {Texture}
  6896. */
  6897. get texture() {
  6898. return this.textures[ 0 ];
  6899. }
  6900. set texture( value ) {
  6901. this.textures[ 0 ] = value;
  6902. }
  6903. set depthTexture( current ) {
  6904. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  6905. if ( current !== null ) current.renderTarget = this;
  6906. this._depthTexture = current;
  6907. }
  6908. /**
  6909. * Instead of saving the depth in a renderbuffer, a texture
  6910. * can be used instead which is useful for further processing
  6911. * e.g. in context of post-processing.
  6912. *
  6913. * @type {?DepthTexture}
  6914. * @default null
  6915. */
  6916. get depthTexture() {
  6917. return this._depthTexture;
  6918. }
  6919. /**
  6920. * Sets the size of this render target.
  6921. *
  6922. * @param {number} width - The width.
  6923. * @param {number} height - The height.
  6924. * @param {number} [depth=1] - The depth.
  6925. */
  6926. setSize( width, height, depth = 1 ) {
  6927. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  6928. this.width = width;
  6929. this.height = height;
  6930. this.depth = depth;
  6931. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  6932. this.textures[ i ].image.width = width;
  6933. this.textures[ i ].image.height = height;
  6934. this.textures[ i ].image.depth = depth;
  6935. this.textures[ i ].isArrayTexture = this.textures[ i ].image.depth > 1;
  6936. }
  6937. this.dispose();
  6938. }
  6939. this.viewport.set( 0, 0, width, height );
  6940. this.scissor.set( 0, 0, width, height );
  6941. }
  6942. /**
  6943. * Returns a new render target with copied values from this instance.
  6944. *
  6945. * @return {RenderTarget} A clone of this instance.
  6946. */
  6947. clone() {
  6948. return new this.constructor().copy( this );
  6949. }
  6950. /**
  6951. * Copies the settings of the given render target. This is a structural copy so
  6952. * no resources are shared between render targets after the copy. That includes
  6953. * all MRT textures and the depth texture.
  6954. *
  6955. * @param {RenderTarget} source - The render target to copy.
  6956. * @return {RenderTarget} A reference to this instance.
  6957. */
  6958. copy( source ) {
  6959. this.width = source.width;
  6960. this.height = source.height;
  6961. this.depth = source.depth;
  6962. this.scissor.copy( source.scissor );
  6963. this.scissorTest = source.scissorTest;
  6964. this.viewport.copy( source.viewport );
  6965. this.textures.length = 0;
  6966. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  6967. this.textures[ i ] = source.textures[ i ].clone();
  6968. this.textures[ i ].isRenderTargetTexture = true;
  6969. this.textures[ i ].renderTarget = this;
  6970. // ensure image object is not shared, see #20328
  6971. const image = Object.assign( {}, source.textures[ i ].image );
  6972. this.textures[ i ].source = new Source( image );
  6973. }
  6974. this.depthBuffer = source.depthBuffer;
  6975. this.stencilBuffer = source.stencilBuffer;
  6976. this.resolveDepthBuffer = source.resolveDepthBuffer;
  6977. this.resolveStencilBuffer = source.resolveStencilBuffer;
  6978. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  6979. this.samples = source.samples;
  6980. return this;
  6981. }
  6982. /**
  6983. * Frees the GPU-related resources allocated by this instance. Call this
  6984. * method whenever this instance is no longer used in your app.
  6985. *
  6986. * @fires RenderTarget#dispose
  6987. */
  6988. dispose() {
  6989. this.dispatchEvent( { type: 'dispose' } );
  6990. }
  6991. }
  6992. /**
  6993. * A render target used in context of {@link WebGLRenderer}.
  6994. *
  6995. * @augments RenderTarget
  6996. */
  6997. class WebGLRenderTarget extends RenderTarget {
  6998. /**
  6999. * Constructs a new 3D render target.
  7000. *
  7001. * @param {number} [width=1] - The width of the render target.
  7002. * @param {number} [height=1] - The height of the render target.
  7003. * @param {RenderTarget~Options} [options] - The configuration object.
  7004. */
  7005. constructor( width = 1, height = 1, options = {} ) {
  7006. super( width, height, options );
  7007. /**
  7008. * This flag can be used for type testing.
  7009. *
  7010. * @type {boolean}
  7011. * @readonly
  7012. * @default true
  7013. */
  7014. this.isWebGLRenderTarget = true;
  7015. }
  7016. }
  7017. /**
  7018. * Creates an array of textures directly from raw buffer data.
  7019. *
  7020. * @augments Texture
  7021. */
  7022. class DataArrayTexture extends Texture {
  7023. /**
  7024. * Constructs a new data array texture.
  7025. *
  7026. * @param {?TypedArray} [data=null] - The buffer data.
  7027. * @param {number} [width=1] - The width of the texture.
  7028. * @param {number} [height=1] - The height of the texture.
  7029. * @param {number} [depth=1] - The depth of the texture.
  7030. */
  7031. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7032. super( null );
  7033. /**
  7034. * This flag can be used for type testing.
  7035. *
  7036. * @type {boolean}
  7037. * @readonly
  7038. * @default true
  7039. */
  7040. this.isDataArrayTexture = true;
  7041. /**
  7042. * The image definition of a data texture.
  7043. *
  7044. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7045. */
  7046. this.image = { data, width, height, depth };
  7047. /**
  7048. * How the texture is sampled when a texel covers more than one pixel.
  7049. *
  7050. * Overwritten and set to `NearestFilter` by default.
  7051. *
  7052. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7053. * @default NearestFilter
  7054. */
  7055. this.magFilter = NearestFilter;
  7056. /**
  7057. * How the texture is sampled when a texel covers less than one pixel.
  7058. *
  7059. * Overwritten and set to `NearestFilter` by default.
  7060. *
  7061. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7062. * @default NearestFilter
  7063. */
  7064. this.minFilter = NearestFilter;
  7065. /**
  7066. * This defines how the texture is wrapped in the depth and corresponds to
  7067. * *W* in UVW mapping.
  7068. *
  7069. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7070. * @default ClampToEdgeWrapping
  7071. */
  7072. this.wrapR = ClampToEdgeWrapping;
  7073. /**
  7074. * Whether to generate mipmaps (if possible) for a texture.
  7075. *
  7076. * Overwritten and set to `false` by default.
  7077. *
  7078. * @type {boolean}
  7079. * @default false
  7080. */
  7081. this.generateMipmaps = false;
  7082. /**
  7083. * If set to `true`, the texture is flipped along the vertical axis when
  7084. * uploaded to the GPU.
  7085. *
  7086. * Overwritten and set to `false` by default.
  7087. *
  7088. * @type {boolean}
  7089. * @default false
  7090. */
  7091. this.flipY = false;
  7092. /**
  7093. * Specifies the alignment requirements for the start of each pixel row in memory.
  7094. *
  7095. * Overwritten and set to `1` by default.
  7096. *
  7097. * @type {boolean}
  7098. * @default 1
  7099. */
  7100. this.unpackAlignment = 1;
  7101. /**
  7102. * A set of all layers which need to be updated in the texture.
  7103. *
  7104. * @type {Set<number>}
  7105. */
  7106. this.layerUpdates = new Set();
  7107. }
  7108. /**
  7109. * Describes that a specific layer of the texture needs to be updated.
  7110. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  7111. * entire data texture array is sent to the GPU. Marking specific
  7112. * layers will only transmit subsets of all mipmaps associated with a
  7113. * specific depth in the array which is often much more performant.
  7114. *
  7115. * @param {number} layerIndex - The layer index that should be updated.
  7116. */
  7117. addLayerUpdate( layerIndex ) {
  7118. this.layerUpdates.add( layerIndex );
  7119. }
  7120. /**
  7121. * Resets the layer updates registry.
  7122. */
  7123. clearLayerUpdates() {
  7124. this.layerUpdates.clear();
  7125. }
  7126. }
  7127. /**
  7128. * An array render target used in context of {@link WebGLRenderer}.
  7129. *
  7130. * @augments WebGLRenderTarget
  7131. */
  7132. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  7133. /**
  7134. * Constructs a new array render target.
  7135. *
  7136. * @param {number} [width=1] - The width of the render target.
  7137. * @param {number} [height=1] - The height of the render target.
  7138. * @param {number} [depth=1] - The height of the render target.
  7139. * @param {RenderTarget~Options} [options] - The configuration object.
  7140. */
  7141. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7142. super( width, height, options );
  7143. /**
  7144. * This flag can be used for type testing.
  7145. *
  7146. * @type {boolean}
  7147. * @readonly
  7148. * @default true
  7149. */
  7150. this.isWebGLArrayRenderTarget = true;
  7151. this.depth = depth;
  7152. /**
  7153. * Overwritten with a different texture type.
  7154. *
  7155. * @type {DataArrayTexture}
  7156. */
  7157. this.texture = new DataArrayTexture( null, width, height, depth );
  7158. this._setTextureOptions( options );
  7159. this.texture.isRenderTargetTexture = true;
  7160. }
  7161. }
  7162. /**
  7163. * Creates a three-dimensional texture from raw data, with parameters to
  7164. * divide it into width, height, and depth.
  7165. *
  7166. * @augments Texture
  7167. */
  7168. class Data3DTexture extends Texture {
  7169. /**
  7170. * Constructs a new data array texture.
  7171. *
  7172. * @param {?TypedArray} [data=null] - The buffer data.
  7173. * @param {number} [width=1] - The width of the texture.
  7174. * @param {number} [height=1] - The height of the texture.
  7175. * @param {number} [depth=1] - The depth of the texture.
  7176. */
  7177. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7178. // We're going to add .setXXX() methods for setting properties later.
  7179. // Users can still set in Data3DTexture directly.
  7180. //
  7181. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  7182. // texture.anisotropy = 16;
  7183. //
  7184. // See #14839
  7185. super( null );
  7186. /**
  7187. * This flag can be used for type testing.
  7188. *
  7189. * @type {boolean}
  7190. * @readonly
  7191. * @default true
  7192. */
  7193. this.isData3DTexture = true;
  7194. /**
  7195. * The image definition of a data texture.
  7196. *
  7197. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7198. */
  7199. this.image = { data, width, height, depth };
  7200. /**
  7201. * How the texture is sampled when a texel covers more than one pixel.
  7202. *
  7203. * Overwritten and set to `NearestFilter` by default.
  7204. *
  7205. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7206. * @default NearestFilter
  7207. */
  7208. this.magFilter = NearestFilter;
  7209. /**
  7210. * How the texture is sampled when a texel covers less than one pixel.
  7211. *
  7212. * Overwritten and set to `NearestFilter` by default.
  7213. *
  7214. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7215. * @default NearestFilter
  7216. */
  7217. this.minFilter = NearestFilter;
  7218. /**
  7219. * This defines how the texture is wrapped in the depth and corresponds to
  7220. * *W* in UVW mapping.
  7221. *
  7222. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7223. * @default ClampToEdgeWrapping
  7224. */
  7225. this.wrapR = ClampToEdgeWrapping;
  7226. /**
  7227. * Whether to generate mipmaps (if possible) for a texture.
  7228. *
  7229. * Overwritten and set to `false` by default.
  7230. *
  7231. * @type {boolean}
  7232. * @default false
  7233. */
  7234. this.generateMipmaps = false;
  7235. /**
  7236. * If set to `true`, the texture is flipped along the vertical axis when
  7237. * uploaded to the GPU.
  7238. *
  7239. * Overwritten and set to `false` by default.
  7240. *
  7241. * @type {boolean}
  7242. * @default false
  7243. */
  7244. this.flipY = false;
  7245. /**
  7246. * Specifies the alignment requirements for the start of each pixel row in memory.
  7247. *
  7248. * Overwritten and set to `1` by default.
  7249. *
  7250. * @type {boolean}
  7251. * @default 1
  7252. */
  7253. this.unpackAlignment = 1;
  7254. }
  7255. }
  7256. /**
  7257. * A 3D render target used in context of {@link WebGLRenderer}.
  7258. *
  7259. * @augments WebGLRenderTarget
  7260. */
  7261. class WebGL3DRenderTarget extends WebGLRenderTarget {
  7262. /**
  7263. * Constructs a new 3D render target.
  7264. *
  7265. * @param {number} [width=1] - The width of the render target.
  7266. * @param {number} [height=1] - The height of the render target.
  7267. * @param {number} [depth=1] - The height of the render target.
  7268. * @param {RenderTarget~Options} [options] - The configuration object.
  7269. */
  7270. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7271. super( width, height, options );
  7272. /**
  7273. * This flag can be used for type testing.
  7274. *
  7275. * @type {boolean}
  7276. * @readonly
  7277. * @default true
  7278. */
  7279. this.isWebGL3DRenderTarget = true;
  7280. this.depth = depth;
  7281. /**
  7282. * Overwritten with a different texture type.
  7283. *
  7284. * @type {Data3DTexture}
  7285. */
  7286. this.texture = new Data3DTexture( null, width, height, depth );
  7287. this._setTextureOptions( options );
  7288. this.texture.isRenderTargetTexture = true;
  7289. }
  7290. }
  7291. /**
  7292. * Represents an axis-aligned bounding box (AABB) in 3D space.
  7293. */
  7294. class Box3 {
  7295. /**
  7296. * Constructs a new bounding box.
  7297. *
  7298. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  7299. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  7300. */
  7301. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  7302. /**
  7303. * This flag can be used for type testing.
  7304. *
  7305. * @type {boolean}
  7306. * @readonly
  7307. * @default true
  7308. */
  7309. this.isBox3 = true;
  7310. /**
  7311. * The lower boundary of the box.
  7312. *
  7313. * @type {Vector3}
  7314. */
  7315. this.min = min;
  7316. /**
  7317. * The upper boundary of the box.
  7318. *
  7319. * @type {Vector3}
  7320. */
  7321. this.max = max;
  7322. }
  7323. /**
  7324. * Sets the lower and upper boundaries of this box.
  7325. * Please note that this method only copies the values from the given objects.
  7326. *
  7327. * @param {Vector3} min - The lower boundary of the box.
  7328. * @param {Vector3} max - The upper boundary of the box.
  7329. * @return {Box3} A reference to this bounding box.
  7330. */
  7331. set( min, max ) {
  7332. this.min.copy( min );
  7333. this.max.copy( max );
  7334. return this;
  7335. }
  7336. /**
  7337. * Sets the upper and lower bounds of this box so it encloses the position data
  7338. * in the given array.
  7339. *
  7340. * @param {Array<number>} array - An array holding 3D position data.
  7341. * @return {Box3} A reference to this bounding box.
  7342. */
  7343. setFromArray( array ) {
  7344. this.makeEmpty();
  7345. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  7346. this.expandByPoint( _vector$b.fromArray( array, i ) );
  7347. }
  7348. return this;
  7349. }
  7350. /**
  7351. * Sets the upper and lower bounds of this box so it encloses the position data
  7352. * in the given buffer attribute.
  7353. *
  7354. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  7355. * @return {Box3} A reference to this bounding box.
  7356. */
  7357. setFromBufferAttribute( attribute ) {
  7358. this.makeEmpty();
  7359. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  7360. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  7361. }
  7362. return this;
  7363. }
  7364. /**
  7365. * Sets the upper and lower bounds of this box so it encloses the position data
  7366. * in the given array.
  7367. *
  7368. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  7369. * @return {Box3} A reference to this bounding box.
  7370. */
  7371. setFromPoints( points ) {
  7372. this.makeEmpty();
  7373. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7374. this.expandByPoint( points[ i ] );
  7375. }
  7376. return this;
  7377. }
  7378. /**
  7379. * Centers this box on the given center vector and sets this box's width, height and
  7380. * depth to the given size values.
  7381. *
  7382. * @param {Vector3} center - The center of the box.
  7383. * @param {Vector3} size - The x, y and z dimensions of the box.
  7384. * @return {Box3} A reference to this bounding box.
  7385. */
  7386. setFromCenterAndSize( center, size ) {
  7387. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  7388. this.min.copy( center ).sub( halfSize );
  7389. this.max.copy( center ).add( halfSize );
  7390. return this;
  7391. }
  7392. /**
  7393. * Computes the world-axis-aligned bounding box for the given 3D object
  7394. * (including its children), accounting for the object's, and children's,
  7395. * world transforms. The function may result in a larger box than strictly necessary.
  7396. *
  7397. * @param {Object3D} object - The 3D object to compute the bounding box for.
  7398. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  7399. * world-axis-aligned bounding box at the expense of more computation.
  7400. * @return {Box3} A reference to this bounding box.
  7401. */
  7402. setFromObject( object, precise = false ) {
  7403. this.makeEmpty();
  7404. return this.expandByObject( object, precise );
  7405. }
  7406. /**
  7407. * Returns a new box with copied values from this instance.
  7408. *
  7409. * @return {Box3} A clone of this instance.
  7410. */
  7411. clone() {
  7412. return new this.constructor().copy( this );
  7413. }
  7414. /**
  7415. * Copies the values of the given box to this instance.
  7416. *
  7417. * @param {Box3} box - The box to copy.
  7418. * @return {Box3} A reference to this bounding box.
  7419. */
  7420. copy( box ) {
  7421. this.min.copy( box.min );
  7422. this.max.copy( box.max );
  7423. return this;
  7424. }
  7425. /**
  7426. * Makes this box empty which means in encloses a zero space in 3D.
  7427. *
  7428. * @return {Box3} A reference to this bounding box.
  7429. */
  7430. makeEmpty() {
  7431. this.min.x = this.min.y = this.min.z = + Infinity;
  7432. this.max.x = this.max.y = this.max.z = - Infinity;
  7433. return this;
  7434. }
  7435. /**
  7436. * Returns true if this box includes zero points within its bounds.
  7437. * Note that a box with equal lower and upper bounds still includes one
  7438. * point, the one both bounds share.
  7439. *
  7440. * @return {boolean} Whether this box is empty or not.
  7441. */
  7442. isEmpty() {
  7443. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  7444. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  7445. }
  7446. /**
  7447. * Returns the center point of this box.
  7448. *
  7449. * @param {Vector3} target - The target vector that is used to store the method's result.
  7450. * @return {Vector3} The center point.
  7451. */
  7452. getCenter( target ) {
  7453. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  7454. }
  7455. /**
  7456. * Returns the dimensions of this box.
  7457. *
  7458. * @param {Vector3} target - The target vector that is used to store the method's result.
  7459. * @return {Vector3} The size.
  7460. */
  7461. getSize( target ) {
  7462. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  7463. }
  7464. /**
  7465. * Expands the boundaries of this box to include the given point.
  7466. *
  7467. * @param {Vector3} point - The point that should be included by the bounding box.
  7468. * @return {Box3} A reference to this bounding box.
  7469. */
  7470. expandByPoint( point ) {
  7471. this.min.min( point );
  7472. this.max.max( point );
  7473. return this;
  7474. }
  7475. /**
  7476. * Expands this box equilaterally by the given vector. The width of this
  7477. * box will be expanded by the x component of the vector in both
  7478. * directions. The height of this box will be expanded by the y component of
  7479. * the vector in both directions. The depth of this box will be
  7480. * expanded by the z component of the vector in both directions.
  7481. *
  7482. * @param {Vector3} vector - The vector that should expand the bounding box.
  7483. * @return {Box3} A reference to this bounding box.
  7484. */
  7485. expandByVector( vector ) {
  7486. this.min.sub( vector );
  7487. this.max.add( vector );
  7488. return this;
  7489. }
  7490. /**
  7491. * Expands each dimension of the box by the given scalar. If negative, the
  7492. * dimensions of the box will be contracted.
  7493. *
  7494. * @param {number} scalar - The scalar value that should expand the bounding box.
  7495. * @return {Box3} A reference to this bounding box.
  7496. */
  7497. expandByScalar( scalar ) {
  7498. this.min.addScalar( - scalar );
  7499. this.max.addScalar( scalar );
  7500. return this;
  7501. }
  7502. /**
  7503. * Expands the boundaries of this box to include the given 3D object and
  7504. * its children, accounting for the object's, and children's, world
  7505. * transforms. The function may result in a larger box than strictly
  7506. * necessary (unless the precise parameter is set to true).
  7507. *
  7508. * @param {Object3D} object - The 3D object that should expand the bounding box.
  7509. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  7510. * as little as necessary at the expense of more computation.
  7511. * @return {Box3} A reference to this bounding box.
  7512. */
  7513. expandByObject( object, precise = false ) {
  7514. // Computes the world-axis-aligned bounding box of an object (including its children),
  7515. // accounting for both the object's, and children's, world transforms
  7516. object.updateWorldMatrix( false, false );
  7517. const geometry = object.geometry;
  7518. if ( geometry !== undefined ) {
  7519. const positionAttribute = geometry.getAttribute( 'position' );
  7520. // precise AABB computation based on vertex data requires at least a position attribute.
  7521. // instancing isn't supported so far and uses the normal (conservative) code path.
  7522. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  7523. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  7524. if ( object.isMesh === true ) {
  7525. object.getVertexPosition( i, _vector$b );
  7526. } else {
  7527. _vector$b.fromBufferAttribute( positionAttribute, i );
  7528. }
  7529. _vector$b.applyMatrix4( object.matrixWorld );
  7530. this.expandByPoint( _vector$b );
  7531. }
  7532. } else {
  7533. if ( object.boundingBox !== undefined ) {
  7534. // object-level bounding box
  7535. if ( object.boundingBox === null ) {
  7536. object.computeBoundingBox();
  7537. }
  7538. _box$4.copy( object.boundingBox );
  7539. } else {
  7540. // geometry-level bounding box
  7541. if ( geometry.boundingBox === null ) {
  7542. geometry.computeBoundingBox();
  7543. }
  7544. _box$4.copy( geometry.boundingBox );
  7545. }
  7546. _box$4.applyMatrix4( object.matrixWorld );
  7547. this.union( _box$4 );
  7548. }
  7549. }
  7550. const children = object.children;
  7551. for ( let i = 0, l = children.length; i < l; i ++ ) {
  7552. this.expandByObject( children[ i ], precise );
  7553. }
  7554. return this;
  7555. }
  7556. /**
  7557. * Returns `true` if the given point lies within or on the boundaries of this box.
  7558. *
  7559. * @param {Vector3} point - The point to test.
  7560. * @return {boolean} Whether the bounding box contains the given point or not.
  7561. */
  7562. containsPoint( point ) {
  7563. return point.x >= this.min.x && point.x <= this.max.x &&
  7564. point.y >= this.min.y && point.y <= this.max.y &&
  7565. point.z >= this.min.z && point.z <= this.max.z;
  7566. }
  7567. /**
  7568. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  7569. * If this box and the given one are identical, this function also returns `true`.
  7570. *
  7571. * @param {Box3} box - The bounding box to test.
  7572. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  7573. */
  7574. containsBox( box ) {
  7575. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  7576. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  7577. this.min.z <= box.min.z && box.max.z <= this.max.z;
  7578. }
  7579. /**
  7580. * Returns a point as a proportion of this box's width, height and depth.
  7581. *
  7582. * @param {Vector3} point - A point in 3D space.
  7583. * @param {Vector3} target - The target vector that is used to store the method's result.
  7584. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  7585. */
  7586. getParameter( point, target ) {
  7587. // This can potentially have a divide by zero if the box
  7588. // has a size dimension of 0.
  7589. return target.set(
  7590. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7591. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  7592. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  7593. );
  7594. }
  7595. /**
  7596. * Returns `true` if the given bounding box intersects with this bounding box.
  7597. *
  7598. * @param {Box3} box - The bounding box to test.
  7599. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  7600. */
  7601. intersectsBox( box ) {
  7602. // using 6 splitting planes to rule out intersections.
  7603. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  7604. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  7605. box.max.z >= this.min.z && box.min.z <= this.max.z;
  7606. }
  7607. /**
  7608. * Returns `true` if the given bounding sphere intersects with this bounding box.
  7609. *
  7610. * @param {Sphere} sphere - The bounding sphere to test.
  7611. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  7612. */
  7613. intersectsSphere( sphere ) {
  7614. // Find the point on the AABB closest to the sphere center.
  7615. this.clampPoint( sphere.center, _vector$b );
  7616. // If that point is inside the sphere, the AABB and sphere intersect.
  7617. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  7618. }
  7619. /**
  7620. * Returns `true` if the given plane intersects with this bounding box.
  7621. *
  7622. * @param {Plane} plane - The plane to test.
  7623. * @return {boolean} Whether the given plane intersects with this bounding box.
  7624. */
  7625. intersectsPlane( plane ) {
  7626. // We compute the minimum and maximum dot product values. If those values
  7627. // are on the same side (back or front) of the plane, then there is no intersection.
  7628. let min, max;
  7629. if ( plane.normal.x > 0 ) {
  7630. min = plane.normal.x * this.min.x;
  7631. max = plane.normal.x * this.max.x;
  7632. } else {
  7633. min = plane.normal.x * this.max.x;
  7634. max = plane.normal.x * this.min.x;
  7635. }
  7636. if ( plane.normal.y > 0 ) {
  7637. min += plane.normal.y * this.min.y;
  7638. max += plane.normal.y * this.max.y;
  7639. } else {
  7640. min += plane.normal.y * this.max.y;
  7641. max += plane.normal.y * this.min.y;
  7642. }
  7643. if ( plane.normal.z > 0 ) {
  7644. min += plane.normal.z * this.min.z;
  7645. max += plane.normal.z * this.max.z;
  7646. } else {
  7647. min += plane.normal.z * this.max.z;
  7648. max += plane.normal.z * this.min.z;
  7649. }
  7650. return ( min <= - plane.constant && max >= - plane.constant );
  7651. }
  7652. /**
  7653. * Returns `true` if the given triangle intersects with this bounding box.
  7654. *
  7655. * @param {Triangle} triangle - The triangle to test.
  7656. * @return {boolean} Whether the given triangle intersects with this bounding box.
  7657. */
  7658. intersectsTriangle( triangle ) {
  7659. if ( this.isEmpty() ) {
  7660. return false;
  7661. }
  7662. // compute box center and extents
  7663. this.getCenter( _center );
  7664. _extents.subVectors( this.max, _center );
  7665. // translate triangle to aabb origin
  7666. _v0$3.subVectors( triangle.a, _center );
  7667. _v1$7.subVectors( triangle.b, _center );
  7668. _v2$4.subVectors( triangle.c, _center );
  7669. // compute edge vectors for triangle
  7670. _f0.subVectors( _v1$7, _v0$3 );
  7671. _f1.subVectors( _v2$4, _v1$7 );
  7672. _f2.subVectors( _v0$3, _v2$4 );
  7673. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7674. // 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
  7675. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7676. let axes = [
  7677. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  7678. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  7679. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  7680. ];
  7681. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  7682. return false;
  7683. }
  7684. // test 3 face normals from the aabb
  7685. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7686. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  7687. return false;
  7688. }
  7689. // finally testing the face normal of the triangle
  7690. // use already existing triangle edge vectors here
  7691. _triangleNormal.crossVectors( _f0, _f1 );
  7692. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  7693. return satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents );
  7694. }
  7695. /**
  7696. * Clamps the given point within the bounds of this box.
  7697. *
  7698. * @param {Vector3} point - The point to clamp.
  7699. * @param {Vector3} target - The target vector that is used to store the method's result.
  7700. * @return {Vector3} The clamped point.
  7701. */
  7702. clampPoint( point, target ) {
  7703. return target.copy( point ).clamp( this.min, this.max );
  7704. }
  7705. /**
  7706. * Returns the euclidean distance from any edge of this box to the specified point. If
  7707. * the given point lies inside of this box, the distance will be `0`.
  7708. *
  7709. * @param {Vector3} point - The point to compute the distance to.
  7710. * @return {number} The euclidean distance.
  7711. */
  7712. distanceToPoint( point ) {
  7713. return this.clampPoint( point, _vector$b ).distanceTo( point );
  7714. }
  7715. /**
  7716. * Returns a bounding sphere that encloses this bounding box.
  7717. *
  7718. * @param {Sphere} target - The target sphere that is used to store the method's result.
  7719. * @return {Sphere} The bounding sphere that encloses this bounding box.
  7720. */
  7721. getBoundingSphere( target ) {
  7722. if ( this.isEmpty() ) {
  7723. target.makeEmpty();
  7724. } else {
  7725. this.getCenter( target.center );
  7726. target.radius = this.getSize( _vector$b ).length() * 0.5;
  7727. }
  7728. return target;
  7729. }
  7730. /**
  7731. * Computes the intersection of this bounding box and the given one, setting the upper
  7732. * bound of this box to the lesser of the two boxes' upper bounds and the
  7733. * lower bound of this box to the greater of the two boxes' lower bounds. If
  7734. * there's no overlap, makes this box empty.
  7735. *
  7736. * @param {Box3} box - The bounding box to intersect with.
  7737. * @return {Box3} A reference to this bounding box.
  7738. */
  7739. intersect( box ) {
  7740. this.min.max( box.min );
  7741. this.max.min( box.max );
  7742. // 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.
  7743. if ( this.isEmpty() ) this.makeEmpty();
  7744. return this;
  7745. }
  7746. /**
  7747. * Computes the union of this box and another and the given one, setting the upper
  7748. * bound of this box to the greater of the two boxes' upper bounds and the
  7749. * lower bound of this box to the lesser of the two boxes' lower bounds.
  7750. *
  7751. * @param {Box3} box - The bounding box that will be unioned with this instance.
  7752. * @return {Box3} A reference to this bounding box.
  7753. */
  7754. union( box ) {
  7755. this.min.min( box.min );
  7756. this.max.max( box.max );
  7757. return this;
  7758. }
  7759. /**
  7760. * Transforms this bounding box by the given 4x4 transformation matrix.
  7761. *
  7762. * @param {Matrix4} matrix - The transformation matrix.
  7763. * @return {Box3} A reference to this bounding box.
  7764. */
  7765. applyMatrix4( matrix ) {
  7766. // transform of empty box is an empty box.
  7767. if ( this.isEmpty() ) return this;
  7768. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  7769. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  7770. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  7771. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  7772. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  7773. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  7774. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  7775. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  7776. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  7777. this.setFromPoints( _points );
  7778. return this;
  7779. }
  7780. /**
  7781. * Adds the given offset to both the upper and lower bounds of this bounding box,
  7782. * effectively moving it in 3D space.
  7783. *
  7784. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  7785. * @return {Box3} A reference to this bounding box.
  7786. */
  7787. translate( offset ) {
  7788. this.min.add( offset );
  7789. this.max.add( offset );
  7790. return this;
  7791. }
  7792. /**
  7793. * Returns `true` if this bounding box is equal with the given one.
  7794. *
  7795. * @param {Box3} box - The box to test for equality.
  7796. * @return {boolean} Whether this bounding box is equal with the given one.
  7797. */
  7798. equals( box ) {
  7799. return box.min.equals( this.min ) && box.max.equals( this.max );
  7800. }
  7801. /**
  7802. * Returns a serialized structure of the bounding box.
  7803. *
  7804. * @return {Object} Serialized structure with fields representing the object state.
  7805. */
  7806. toJSON() {
  7807. return {
  7808. min: this.min.toArray(),
  7809. max: this.max.toArray()
  7810. };
  7811. }
  7812. /**
  7813. * Returns a serialized structure of the bounding box.
  7814. *
  7815. * @param {Object} json - The serialized json to set the box from.
  7816. * @return {Box3} A reference to this bounding box.
  7817. */
  7818. fromJSON( json ) {
  7819. this.min.fromArray( json.min );
  7820. this.max.fromArray( json.max );
  7821. return this;
  7822. }
  7823. }
  7824. const _points = [
  7825. /*@__PURE__*/ new Vector3(),
  7826. /*@__PURE__*/ new Vector3(),
  7827. /*@__PURE__*/ new Vector3(),
  7828. /*@__PURE__*/ new Vector3(),
  7829. /*@__PURE__*/ new Vector3(),
  7830. /*@__PURE__*/ new Vector3(),
  7831. /*@__PURE__*/ new Vector3(),
  7832. /*@__PURE__*/ new Vector3()
  7833. ];
  7834. const _vector$b = /*@__PURE__*/ new Vector3();
  7835. const _box$4 = /*@__PURE__*/ new Box3();
  7836. // triangle centered vertices
  7837. const _v0$3 = /*@__PURE__*/ new Vector3();
  7838. const _v1$7 = /*@__PURE__*/ new Vector3();
  7839. const _v2$4 = /*@__PURE__*/ new Vector3();
  7840. // triangle edge vectors
  7841. const _f0 = /*@__PURE__*/ new Vector3();
  7842. const _f1 = /*@__PURE__*/ new Vector3();
  7843. const _f2 = /*@__PURE__*/ new Vector3();
  7844. const _center = /*@__PURE__*/ new Vector3();
  7845. const _extents = /*@__PURE__*/ new Vector3();
  7846. const _triangleNormal = /*@__PURE__*/ new Vector3();
  7847. const _testAxis = /*@__PURE__*/ new Vector3();
  7848. function satForAxes( axes, v0, v1, v2, extents ) {
  7849. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  7850. _testAxis.fromArray( axes, i );
  7851. // project the aabb onto the separating axis
  7852. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  7853. // project all 3 vertices of the triangle onto the separating axis
  7854. const p0 = v0.dot( _testAxis );
  7855. const p1 = v1.dot( _testAxis );
  7856. const p2 = v2.dot( _testAxis );
  7857. // actual test, basically see if either of the most extreme of the triangle points intersects r
  7858. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  7859. // points of the projected triangle are outside the projected half-length of the aabb
  7860. // the axis is separating and we can exit
  7861. return false;
  7862. }
  7863. }
  7864. return true;
  7865. }
  7866. const _box$3 = /*@__PURE__*/ new Box3();
  7867. const _v1$6 = /*@__PURE__*/ new Vector3();
  7868. const _v2$3 = /*@__PURE__*/ new Vector3();
  7869. /**
  7870. * An analytical 3D sphere defined by a center and radius. This class is mainly
  7871. * used as a Bounding Sphere for 3D objects.
  7872. */
  7873. class Sphere {
  7874. /**
  7875. * Constructs a new sphere.
  7876. *
  7877. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  7878. * @param {number} [radius=-1] - The radius of the sphere.
  7879. */
  7880. constructor( center = new Vector3(), radius = -1 ) {
  7881. /**
  7882. * This flag can be used for type testing.
  7883. *
  7884. * @type {boolean}
  7885. * @readonly
  7886. * @default true
  7887. */
  7888. this.isSphere = true;
  7889. /**
  7890. * The center of the sphere
  7891. *
  7892. * @type {Vector3}
  7893. */
  7894. this.center = center;
  7895. /**
  7896. * The radius of the sphere.
  7897. *
  7898. * @type {number}
  7899. */
  7900. this.radius = radius;
  7901. }
  7902. /**
  7903. * Sets the sphere's components by copying the given values.
  7904. *
  7905. * @param {Vector3} center - The center.
  7906. * @param {number} radius - The radius.
  7907. * @return {Sphere} A reference to this sphere.
  7908. */
  7909. set( center, radius ) {
  7910. this.center.copy( center );
  7911. this.radius = radius;
  7912. return this;
  7913. }
  7914. /**
  7915. * Computes the minimum bounding sphere for list of points.
  7916. * If the optional center point is given, it is used as the sphere's
  7917. * center. Otherwise, the center of the axis-aligned bounding box
  7918. * encompassing the points is calculated.
  7919. *
  7920. * @param {Array<Vector3>} points - A list of points in 3D space.
  7921. * @param {Vector3} [optionalCenter] - The center of the sphere.
  7922. * @return {Sphere} A reference to this sphere.
  7923. */
  7924. setFromPoints( points, optionalCenter ) {
  7925. const center = this.center;
  7926. if ( optionalCenter !== undefined ) {
  7927. center.copy( optionalCenter );
  7928. } else {
  7929. _box$3.setFromPoints( points ).getCenter( center );
  7930. }
  7931. let maxRadiusSq = 0;
  7932. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7933. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  7934. }
  7935. this.radius = Math.sqrt( maxRadiusSq );
  7936. return this;
  7937. }
  7938. /**
  7939. * Copies the values of the given sphere to this instance.
  7940. *
  7941. * @param {Sphere} sphere - The sphere to copy.
  7942. * @return {Sphere} A reference to this sphere.
  7943. */
  7944. copy( sphere ) {
  7945. this.center.copy( sphere.center );
  7946. this.radius = sphere.radius;
  7947. return this;
  7948. }
  7949. /**
  7950. * Returns `true` if the sphere is empty (the radius set to a negative number).
  7951. *
  7952. * Spheres with a radius of `0` contain only their center point and are not
  7953. * considered to be empty.
  7954. *
  7955. * @return {boolean} Whether this sphere is empty or not.
  7956. */
  7957. isEmpty() {
  7958. return ( this.radius < 0 );
  7959. }
  7960. /**
  7961. * Makes this sphere empty which means in encloses a zero space in 3D.
  7962. *
  7963. * @return {Sphere} A reference to this sphere.
  7964. */
  7965. makeEmpty() {
  7966. this.center.set( 0, 0, 0 );
  7967. this.radius = -1;
  7968. return this;
  7969. }
  7970. /**
  7971. * Returns `true` if this sphere contains the given point inclusive of
  7972. * the surface of the sphere.
  7973. *
  7974. * @param {Vector3} point - The point to check.
  7975. * @return {boolean} Whether this sphere contains the given point or not.
  7976. */
  7977. containsPoint( point ) {
  7978. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  7979. }
  7980. /**
  7981. * Returns the closest distance from the boundary of the sphere to the
  7982. * given point. If the sphere contains the point, the distance will
  7983. * be negative.
  7984. *
  7985. * @param {Vector3} point - The point to compute the distance to.
  7986. * @return {number} The distance to the point.
  7987. */
  7988. distanceToPoint( point ) {
  7989. return ( point.distanceTo( this.center ) - this.radius );
  7990. }
  7991. /**
  7992. * Returns `true` if this sphere intersects with the given one.
  7993. *
  7994. * @param {Sphere} sphere - The sphere to test.
  7995. * @return {boolean} Whether this sphere intersects with the given one or not.
  7996. */
  7997. intersectsSphere( sphere ) {
  7998. const radiusSum = this.radius + sphere.radius;
  7999. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  8000. }
  8001. /**
  8002. * Returns `true` if this sphere intersects with the given box.
  8003. *
  8004. * @param {Box3} box - The box to test.
  8005. * @return {boolean} Whether this sphere intersects with the given box or not.
  8006. */
  8007. intersectsBox( box ) {
  8008. return box.intersectsSphere( this );
  8009. }
  8010. /**
  8011. * Returns `true` if this sphere intersects with the given plane.
  8012. *
  8013. * @param {Plane} plane - The plane to test.
  8014. * @return {boolean} Whether this sphere intersects with the given plane or not.
  8015. */
  8016. intersectsPlane( plane ) {
  8017. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  8018. }
  8019. /**
  8020. * Clamps a point within the sphere. If the point is outside the sphere, it
  8021. * will clamp it to the closest point on the edge of the sphere. Points
  8022. * already inside the sphere will not be affected.
  8023. *
  8024. * @param {Vector3} point - The plane to clamp.
  8025. * @param {Vector3} target - The target vector that is used to store the method's result.
  8026. * @return {Vector3} The clamped point.
  8027. */
  8028. clampPoint( point, target ) {
  8029. const deltaLengthSq = this.center.distanceToSquared( point );
  8030. target.copy( point );
  8031. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  8032. target.sub( this.center ).normalize();
  8033. target.multiplyScalar( this.radius ).add( this.center );
  8034. }
  8035. return target;
  8036. }
  8037. /**
  8038. * Returns a bounding box that encloses this sphere.
  8039. *
  8040. * @param {Box3} target - The target box that is used to store the method's result.
  8041. * @return {Box3} The bounding box that encloses this sphere.
  8042. */
  8043. getBoundingBox( target ) {
  8044. if ( this.isEmpty() ) {
  8045. // Empty sphere produces empty bounding box
  8046. target.makeEmpty();
  8047. return target;
  8048. }
  8049. target.set( this.center, this.center );
  8050. target.expandByScalar( this.radius );
  8051. return target;
  8052. }
  8053. /**
  8054. * Transforms this sphere with the given 4x4 transformation matrix.
  8055. *
  8056. * @param {Matrix4} matrix - The transformation matrix.
  8057. * @return {Sphere} A reference to this sphere.
  8058. */
  8059. applyMatrix4( matrix ) {
  8060. this.center.applyMatrix4( matrix );
  8061. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  8062. return this;
  8063. }
  8064. /**
  8065. * Translates the sphere's center by the given offset.
  8066. *
  8067. * @param {Vector3} offset - The offset.
  8068. * @return {Sphere} A reference to this sphere.
  8069. */
  8070. translate( offset ) {
  8071. this.center.add( offset );
  8072. return this;
  8073. }
  8074. /**
  8075. * Expands the boundaries of this sphere to include the given point.
  8076. *
  8077. * @param {Vector3} point - The point to include.
  8078. * @return {Sphere} A reference to this sphere.
  8079. */
  8080. expandByPoint( point ) {
  8081. if ( this.isEmpty() ) {
  8082. this.center.copy( point );
  8083. this.radius = 0;
  8084. return this;
  8085. }
  8086. _v1$6.subVectors( point, this.center );
  8087. const lengthSq = _v1$6.lengthSq();
  8088. if ( lengthSq > ( this.radius * this.radius ) ) {
  8089. // calculate the minimal sphere
  8090. const length = Math.sqrt( lengthSq );
  8091. const delta = ( length - this.radius ) * 0.5;
  8092. this.center.addScaledVector( _v1$6, delta / length );
  8093. this.radius += delta;
  8094. }
  8095. return this;
  8096. }
  8097. /**
  8098. * Expands this sphere to enclose both the original sphere and the given sphere.
  8099. *
  8100. * @param {Sphere} sphere - The sphere to include.
  8101. * @return {Sphere} A reference to this sphere.
  8102. */
  8103. union( sphere ) {
  8104. if ( sphere.isEmpty() ) {
  8105. return this;
  8106. }
  8107. if ( this.isEmpty() ) {
  8108. this.copy( sphere );
  8109. return this;
  8110. }
  8111. if ( this.center.equals( sphere.center ) === true ) {
  8112. this.radius = Math.max( this.radius, sphere.radius );
  8113. } else {
  8114. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  8115. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  8116. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  8117. }
  8118. return this;
  8119. }
  8120. /**
  8121. * Returns `true` if this sphere is equal with the given one.
  8122. *
  8123. * @param {Sphere} sphere - The sphere to test for equality.
  8124. * @return {boolean} Whether this bounding sphere is equal with the given one.
  8125. */
  8126. equals( sphere ) {
  8127. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  8128. }
  8129. /**
  8130. * Returns a new sphere with copied values from this instance.
  8131. *
  8132. * @return {Sphere} A clone of this instance.
  8133. */
  8134. clone() {
  8135. return new this.constructor().copy( this );
  8136. }
  8137. /**
  8138. * Returns a serialized structure of the bounding sphere.
  8139. *
  8140. * @return {Object} Serialized structure with fields representing the object state.
  8141. */
  8142. toJSON() {
  8143. return {
  8144. radius: this.radius,
  8145. center: this.center.toArray()
  8146. };
  8147. }
  8148. /**
  8149. * Returns a serialized structure of the bounding sphere.
  8150. *
  8151. * @param {Object} json - The serialized json to set the sphere from.
  8152. * @return {Box3} A reference to this bounding sphere.
  8153. */
  8154. fromJSON( json ) {
  8155. this.radius = json.radius;
  8156. this.center.fromArray( json.center );
  8157. return this;
  8158. }
  8159. }
  8160. const _vector$a = /*@__PURE__*/ new Vector3();
  8161. const _segCenter = /*@__PURE__*/ new Vector3();
  8162. const _segDir = /*@__PURE__*/ new Vector3();
  8163. const _diff = /*@__PURE__*/ new Vector3();
  8164. const _edge1 = /*@__PURE__*/ new Vector3();
  8165. const _edge2 = /*@__PURE__*/ new Vector3();
  8166. const _normal$1 = /*@__PURE__*/ new Vector3();
  8167. /**
  8168. * A ray that emits from an origin in a certain direction. The class is used by
  8169. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  8170. * mouse picking (working out what objects in the 3D space the mouse is over)
  8171. * amongst other things.
  8172. */
  8173. class Ray {
  8174. /**
  8175. * Constructs a new ray.
  8176. *
  8177. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  8178. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  8179. */
  8180. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  8181. /**
  8182. * The origin of the ray.
  8183. *
  8184. * @type {Vector3}
  8185. */
  8186. this.origin = origin;
  8187. /**
  8188. * The (normalized) direction of the ray.
  8189. *
  8190. * @type {Vector3}
  8191. */
  8192. this.direction = direction;
  8193. }
  8194. /**
  8195. * Sets the ray's components by copying the given values.
  8196. *
  8197. * @param {Vector3} origin - The origin.
  8198. * @param {Vector3} direction - The direction.
  8199. * @return {Ray} A reference to this ray.
  8200. */
  8201. set( origin, direction ) {
  8202. this.origin.copy( origin );
  8203. this.direction.copy( direction );
  8204. return this;
  8205. }
  8206. /**
  8207. * Copies the values of the given ray to this instance.
  8208. *
  8209. * @param {Ray} ray - The ray to copy.
  8210. * @return {Ray} A reference to this ray.
  8211. */
  8212. copy( ray ) {
  8213. this.origin.copy( ray.origin );
  8214. this.direction.copy( ray.direction );
  8215. return this;
  8216. }
  8217. /**
  8218. * Returns a vector that is located at a given distance along this ray.
  8219. *
  8220. * @param {number} t - The distance along the ray to retrieve a position for.
  8221. * @param {Vector3} target - The target vector that is used to store the method's result.
  8222. * @return {Vector3} A position on the ray.
  8223. */
  8224. at( t, target ) {
  8225. return target.copy( this.origin ).addScaledVector( this.direction, t );
  8226. }
  8227. /**
  8228. * Adjusts the direction of the ray to point at the given vector in world space.
  8229. *
  8230. * @param {Vector3} v - The target position.
  8231. * @return {Ray} A reference to this ray.
  8232. */
  8233. lookAt( v ) {
  8234. this.direction.copy( v ).sub( this.origin ).normalize();
  8235. return this;
  8236. }
  8237. /**
  8238. * Shift the origin of this ray along its direction by the given distance.
  8239. *
  8240. * @param {number} t - The distance along the ray to interpolate.
  8241. * @return {Ray} A reference to this ray.
  8242. */
  8243. recast( t ) {
  8244. this.origin.copy( this.at( t, _vector$a ) );
  8245. return this;
  8246. }
  8247. /**
  8248. * Returns the point along this ray that is closest to the given point.
  8249. *
  8250. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  8251. * @param {Vector3} target - The target vector that is used to store the method's result.
  8252. * @return {Vector3} The closest point on this ray.
  8253. */
  8254. closestPointToPoint( point, target ) {
  8255. target.subVectors( point, this.origin );
  8256. const directionDistance = target.dot( this.direction );
  8257. if ( directionDistance < 0 ) {
  8258. return target.copy( this.origin );
  8259. }
  8260. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8261. }
  8262. /**
  8263. * Returns the distance of the closest approach between this ray and the given point.
  8264. *
  8265. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8266. * @return {number} The distance.
  8267. */
  8268. distanceToPoint( point ) {
  8269. return Math.sqrt( this.distanceSqToPoint( point ) );
  8270. }
  8271. /**
  8272. * Returns the squared distance of the closest approach between this ray and the given point.
  8273. *
  8274. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8275. * @return {number} The squared distance.
  8276. */
  8277. distanceSqToPoint( point ) {
  8278. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  8279. // point behind the ray
  8280. if ( directionDistance < 0 ) {
  8281. return this.origin.distanceToSquared( point );
  8282. }
  8283. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8284. return _vector$a.distanceToSquared( point );
  8285. }
  8286. /**
  8287. * Returns the squared distance between this ray and the given line segment.
  8288. *
  8289. * @param {Vector3} v0 - The start point of the line segment.
  8290. * @param {Vector3} v1 - The end point of the line segment.
  8291. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  8292. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  8293. * @return {number} The squared distance.
  8294. */
  8295. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  8296. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8297. // It returns the min distance between the ray and the segment
  8298. // defined by v0 and v1
  8299. // It can also set two optional targets :
  8300. // - The closest point on the ray
  8301. // - The closest point on the segment
  8302. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  8303. _segDir.copy( v1 ).sub( v0 ).normalize();
  8304. _diff.copy( this.origin ).sub( _segCenter );
  8305. const segExtent = v0.distanceTo( v1 ) * 0.5;
  8306. const a01 = - this.direction.dot( _segDir );
  8307. const b0 = _diff.dot( this.direction );
  8308. const b1 = - _diff.dot( _segDir );
  8309. const c = _diff.lengthSq();
  8310. const det = Math.abs( 1 - a01 * a01 );
  8311. let s0, s1, sqrDist, extDet;
  8312. if ( det > 0 ) {
  8313. // The ray and segment are not parallel.
  8314. s0 = a01 * b1 - b0;
  8315. s1 = a01 * b0 - b1;
  8316. extDet = segExtent * det;
  8317. if ( s0 >= 0 ) {
  8318. if ( s1 >= - extDet ) {
  8319. if ( s1 <= extDet ) {
  8320. // region 0
  8321. // Minimum at interior points of ray and segment.
  8322. const invDet = 1 / det;
  8323. s0 *= invDet;
  8324. s1 *= invDet;
  8325. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  8326. } else {
  8327. // region 1
  8328. s1 = segExtent;
  8329. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8330. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8331. }
  8332. } else {
  8333. // region 5
  8334. s1 = - segExtent;
  8335. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8336. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8337. }
  8338. } else {
  8339. if ( s1 <= - extDet ) {
  8340. // region 4
  8341. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  8342. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8343. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8344. } else if ( s1 <= extDet ) {
  8345. // region 3
  8346. s0 = 0;
  8347. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8348. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  8349. } else {
  8350. // region 2
  8351. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  8352. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8353. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8354. }
  8355. }
  8356. } else {
  8357. // Ray and segment are parallel.
  8358. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  8359. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8360. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8361. }
  8362. if ( optionalPointOnRay ) {
  8363. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  8364. }
  8365. if ( optionalPointOnSegment ) {
  8366. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  8367. }
  8368. return sqrDist;
  8369. }
  8370. /**
  8371. * Intersects this ray with the given sphere, returning the intersection
  8372. * point or `null` if there is no intersection.
  8373. *
  8374. * @param {Sphere} sphere - The sphere to intersect.
  8375. * @param {Vector3} target - The target vector that is used to store the method's result.
  8376. * @return {?Vector3} The intersection point.
  8377. */
  8378. intersectSphere( sphere, target ) {
  8379. _vector$a.subVectors( sphere.center, this.origin );
  8380. const tca = _vector$a.dot( this.direction );
  8381. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  8382. const radius2 = sphere.radius * sphere.radius;
  8383. if ( d2 > radius2 ) return null;
  8384. const thc = Math.sqrt( radius2 - d2 );
  8385. // t0 = first intersect point - entrance on front of sphere
  8386. const t0 = tca - thc;
  8387. // t1 = second intersect point - exit point on back of sphere
  8388. const t1 = tca + thc;
  8389. // test to see if t1 is behind the ray - if so, return null
  8390. if ( t1 < 0 ) return null;
  8391. // test to see if t0 is behind the ray:
  8392. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  8393. // in order to always return an intersect point that is in front of the ray.
  8394. if ( t0 < 0 ) return this.at( t1, target );
  8395. // else t0 is in front of the ray, so return the first collision point scaled by t0
  8396. return this.at( t0, target );
  8397. }
  8398. /**
  8399. * Returns `true` if this ray intersects with the given sphere.
  8400. *
  8401. * @param {Sphere} sphere - The sphere to intersect.
  8402. * @return {boolean} Whether this ray intersects with the given sphere or not.
  8403. */
  8404. intersectsSphere( sphere ) {
  8405. if ( sphere.radius < 0 ) return false; // handle empty spheres, see #31187
  8406. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  8407. }
  8408. /**
  8409. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  8410. * does not intersect with the plane.
  8411. *
  8412. * @param {Plane} plane - The plane to compute the distance to.
  8413. * @return {?number} Whether this ray intersects with the given sphere or not.
  8414. */
  8415. distanceToPlane( plane ) {
  8416. const denominator = plane.normal.dot( this.direction );
  8417. if ( denominator === 0 ) {
  8418. // line is coplanar, return origin
  8419. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  8420. return 0;
  8421. }
  8422. // Null is preferable to undefined since undefined means.... it is undefined
  8423. return null;
  8424. }
  8425. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  8426. // Return if the ray never intersects the plane
  8427. return t >= 0 ? t : null;
  8428. }
  8429. /**
  8430. * Intersects this ray with the given plane, returning the intersection
  8431. * point or `null` if there is no intersection.
  8432. *
  8433. * @param {Plane} plane - The plane to intersect.
  8434. * @param {Vector3} target - The target vector that is used to store the method's result.
  8435. * @return {?Vector3} The intersection point.
  8436. */
  8437. intersectPlane( plane, target ) {
  8438. const t = this.distanceToPlane( plane );
  8439. if ( t === null ) {
  8440. return null;
  8441. }
  8442. return this.at( t, target );
  8443. }
  8444. /**
  8445. * Returns `true` if this ray intersects with the given plane.
  8446. *
  8447. * @param {Plane} plane - The plane to intersect.
  8448. * @return {boolean} Whether this ray intersects with the given plane or not.
  8449. */
  8450. intersectsPlane( plane ) {
  8451. // check if the ray lies on the plane first
  8452. const distToPoint = plane.distanceToPoint( this.origin );
  8453. if ( distToPoint === 0 ) {
  8454. return true;
  8455. }
  8456. const denominator = plane.normal.dot( this.direction );
  8457. if ( denominator * distToPoint < 0 ) {
  8458. return true;
  8459. }
  8460. // ray origin is behind the plane (and is pointing behind it)
  8461. return false;
  8462. }
  8463. /**
  8464. * Intersects this ray with the given bounding box, returning the intersection
  8465. * point or `null` if there is no intersection.
  8466. *
  8467. * @param {Box3} box - The box to intersect.
  8468. * @param {Vector3} target - The target vector that is used to store the method's result.
  8469. * @return {?Vector3} The intersection point.
  8470. */
  8471. intersectBox( box, target ) {
  8472. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  8473. const invdirx = 1 / this.direction.x,
  8474. invdiry = 1 / this.direction.y,
  8475. invdirz = 1 / this.direction.z;
  8476. const origin = this.origin;
  8477. if ( invdirx >= 0 ) {
  8478. tmin = ( box.min.x - origin.x ) * invdirx;
  8479. tmax = ( box.max.x - origin.x ) * invdirx;
  8480. } else {
  8481. tmin = ( box.max.x - origin.x ) * invdirx;
  8482. tmax = ( box.min.x - origin.x ) * invdirx;
  8483. }
  8484. if ( invdiry >= 0 ) {
  8485. tymin = ( box.min.y - origin.y ) * invdiry;
  8486. tymax = ( box.max.y - origin.y ) * invdiry;
  8487. } else {
  8488. tymin = ( box.max.y - origin.y ) * invdiry;
  8489. tymax = ( box.min.y - origin.y ) * invdiry;
  8490. }
  8491. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  8492. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  8493. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  8494. if ( invdirz >= 0 ) {
  8495. tzmin = ( box.min.z - origin.z ) * invdirz;
  8496. tzmax = ( box.max.z - origin.z ) * invdirz;
  8497. } else {
  8498. tzmin = ( box.max.z - origin.z ) * invdirz;
  8499. tzmax = ( box.min.z - origin.z ) * invdirz;
  8500. }
  8501. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  8502. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  8503. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  8504. //return point closest to the ray (positive side)
  8505. if ( tmax < 0 ) return null;
  8506. return this.at( tmin >= 0 ? tmin : tmax, target );
  8507. }
  8508. /**
  8509. * Returns `true` if this ray intersects with the given box.
  8510. *
  8511. * @param {Box3} box - The box to intersect.
  8512. * @return {boolean} Whether this ray intersects with the given box or not.
  8513. */
  8514. intersectsBox( box ) {
  8515. return this.intersectBox( box, _vector$a ) !== null;
  8516. }
  8517. /**
  8518. * Intersects this ray with the given triangle, returning the intersection
  8519. * point or `null` if there is no intersection.
  8520. *
  8521. * @param {Vector3} a - The first vertex of the triangle.
  8522. * @param {Vector3} b - The second vertex of the triangle.
  8523. * @param {Vector3} c - The third vertex of the triangle.
  8524. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  8525. * @param {Vector3} target - The target vector that is used to store the method's result.
  8526. * @return {?Vector3} The intersection point.
  8527. */
  8528. intersectTriangle( a, b, c, backfaceCulling, target ) {
  8529. // Compute the offset origin, edges, and normal.
  8530. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  8531. _edge1.subVectors( b, a );
  8532. _edge2.subVectors( c, a );
  8533. _normal$1.crossVectors( _edge1, _edge2 );
  8534. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  8535. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  8536. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  8537. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  8538. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  8539. let DdN = this.direction.dot( _normal$1 );
  8540. let sign;
  8541. if ( DdN > 0 ) {
  8542. if ( backfaceCulling ) return null;
  8543. sign = 1;
  8544. } else if ( DdN < 0 ) {
  8545. sign = -1;
  8546. DdN = - DdN;
  8547. } else {
  8548. return null;
  8549. }
  8550. _diff.subVectors( this.origin, a );
  8551. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  8552. // b1 < 0, no intersection
  8553. if ( DdQxE2 < 0 ) {
  8554. return null;
  8555. }
  8556. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  8557. // b2 < 0, no intersection
  8558. if ( DdE1xQ < 0 ) {
  8559. return null;
  8560. }
  8561. // b1+b2 > 1, no intersection
  8562. if ( DdQxE2 + DdE1xQ > DdN ) {
  8563. return null;
  8564. }
  8565. // Line intersects triangle, check if ray does.
  8566. const QdN = - sign * _diff.dot( _normal$1 );
  8567. // t < 0, no intersection
  8568. if ( QdN < 0 ) {
  8569. return null;
  8570. }
  8571. // Ray intersects triangle.
  8572. return this.at( QdN / DdN, target );
  8573. }
  8574. /**
  8575. * Transforms this ray with the given 4x4 transformation matrix.
  8576. *
  8577. * @param {Matrix4} matrix4 - The transformation matrix.
  8578. * @return {Ray} A reference to this ray.
  8579. */
  8580. applyMatrix4( matrix4 ) {
  8581. this.origin.applyMatrix4( matrix4 );
  8582. this.direction.transformDirection( matrix4 );
  8583. return this;
  8584. }
  8585. /**
  8586. * Returns `true` if this ray is equal with the given one.
  8587. *
  8588. * @param {Ray} ray - The ray to test for equality.
  8589. * @return {boolean} Whether this ray is equal with the given one.
  8590. */
  8591. equals( ray ) {
  8592. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  8593. }
  8594. /**
  8595. * Returns a new ray with copied values from this instance.
  8596. *
  8597. * @return {Ray} A clone of this instance.
  8598. */
  8599. clone() {
  8600. return new this.constructor().copy( this );
  8601. }
  8602. }
  8603. /**
  8604. * Represents a 4x4 matrix.
  8605. *
  8606. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  8607. * 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}
  8608. *
  8609. * This allows a 3D vector representing a point in 3D space to undergo
  8610. * transformations such as translation, rotation, shear, scale, reflection,
  8611. * orthogonal or perspective projection and so on, by being multiplied by the
  8612. * matrix. This is known as `applying` the matrix to the vector.
  8613. *
  8614. * A Note on Row-Major and Column-Major Ordering:
  8615. *
  8616. * The constructor and {@link Matrix3#set} method take arguments in
  8617. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  8618. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  8619. * This means that calling:
  8620. * ```js
  8621. * const m = new THREE.Matrix4();
  8622. * m.set( 11, 12, 13, 14,
  8623. * 21, 22, 23, 24,
  8624. * 31, 32, 33, 34,
  8625. * 41, 42, 43, 44 );
  8626. * ```
  8627. * will result in the elements array containing:
  8628. * ```js
  8629. * m.elements = [ 11, 21, 31, 41,
  8630. * 12, 22, 32, 42,
  8631. * 13, 23, 33, 43,
  8632. * 14, 24, 34, 44 ];
  8633. * ```
  8634. * and internally all calculations are performed using column-major ordering.
  8635. * However, as the actual ordering makes no difference mathematically and
  8636. * most people are used to thinking about matrices in row-major order, the
  8637. * three.js documentation shows matrices in row-major order. Just bear in
  8638. * mind that if you are reading the source code, you'll have to take the
  8639. * transpose of any matrices outlined here to make sense of the calculations.
  8640. */
  8641. class Matrix4 {
  8642. /**
  8643. * Constructs a new 4x4 matrix. The arguments are supposed to be
  8644. * in row-major order. If no arguments are provided, the constructor
  8645. * initializes the matrix as an identity matrix.
  8646. *
  8647. * @param {number} [n11] - 1-1 matrix element.
  8648. * @param {number} [n12] - 1-2 matrix element.
  8649. * @param {number} [n13] - 1-3 matrix element.
  8650. * @param {number} [n14] - 1-4 matrix element.
  8651. * @param {number} [n21] - 2-1 matrix element.
  8652. * @param {number} [n22] - 2-2 matrix element.
  8653. * @param {number} [n23] - 2-3 matrix element.
  8654. * @param {number} [n24] - 2-4 matrix element.
  8655. * @param {number} [n31] - 3-1 matrix element.
  8656. * @param {number} [n32] - 3-2 matrix element.
  8657. * @param {number} [n33] - 3-3 matrix element.
  8658. * @param {number} [n34] - 3-4 matrix element.
  8659. * @param {number} [n41] - 4-1 matrix element.
  8660. * @param {number} [n42] - 4-2 matrix element.
  8661. * @param {number} [n43] - 4-3 matrix element.
  8662. * @param {number} [n44] - 4-4 matrix element.
  8663. */
  8664. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8665. /**
  8666. * This flag can be used for type testing.
  8667. *
  8668. * @type {boolean}
  8669. * @readonly
  8670. * @default true
  8671. */
  8672. Matrix4.prototype.isMatrix4 = true;
  8673. /**
  8674. * A column-major list of matrix values.
  8675. *
  8676. * @type {Array<number>}
  8677. */
  8678. this.elements = [
  8679. 1, 0, 0, 0,
  8680. 0, 1, 0, 0,
  8681. 0, 0, 1, 0,
  8682. 0, 0, 0, 1
  8683. ];
  8684. if ( n11 !== undefined ) {
  8685. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  8686. }
  8687. }
  8688. /**
  8689. * Sets the elements of the matrix.The arguments are supposed to be
  8690. * in row-major order.
  8691. *
  8692. * @param {number} [n11] - 1-1 matrix element.
  8693. * @param {number} [n12] - 1-2 matrix element.
  8694. * @param {number} [n13] - 1-3 matrix element.
  8695. * @param {number} [n14] - 1-4 matrix element.
  8696. * @param {number} [n21] - 2-1 matrix element.
  8697. * @param {number} [n22] - 2-2 matrix element.
  8698. * @param {number} [n23] - 2-3 matrix element.
  8699. * @param {number} [n24] - 2-4 matrix element.
  8700. * @param {number} [n31] - 3-1 matrix element.
  8701. * @param {number} [n32] - 3-2 matrix element.
  8702. * @param {number} [n33] - 3-3 matrix element.
  8703. * @param {number} [n34] - 3-4 matrix element.
  8704. * @param {number} [n41] - 4-1 matrix element.
  8705. * @param {number} [n42] - 4-2 matrix element.
  8706. * @param {number} [n43] - 4-3 matrix element.
  8707. * @param {number} [n44] - 4-4 matrix element.
  8708. * @return {Matrix4} A reference to this matrix.
  8709. */
  8710. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8711. const te = this.elements;
  8712. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  8713. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  8714. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  8715. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  8716. return this;
  8717. }
  8718. /**
  8719. * Sets this matrix to the 4x4 identity matrix.
  8720. *
  8721. * @return {Matrix4} A reference to this matrix.
  8722. */
  8723. identity() {
  8724. this.set(
  8725. 1, 0, 0, 0,
  8726. 0, 1, 0, 0,
  8727. 0, 0, 1, 0,
  8728. 0, 0, 0, 1
  8729. );
  8730. return this;
  8731. }
  8732. /**
  8733. * Returns a matrix with copied values from this instance.
  8734. *
  8735. * @return {Matrix4} A clone of this instance.
  8736. */
  8737. clone() {
  8738. return new Matrix4().fromArray( this.elements );
  8739. }
  8740. /**
  8741. * Copies the values of the given matrix to this instance.
  8742. *
  8743. * @param {Matrix4} m - The matrix to copy.
  8744. * @return {Matrix4} A reference to this matrix.
  8745. */
  8746. copy( m ) {
  8747. const te = this.elements;
  8748. const me = m.elements;
  8749. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  8750. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  8751. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  8752. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  8753. return this;
  8754. }
  8755. /**
  8756. * Copies the translation component of the given matrix
  8757. * into this matrix's translation component.
  8758. *
  8759. * @param {Matrix4} m - The matrix to copy the translation component.
  8760. * @return {Matrix4} A reference to this matrix.
  8761. */
  8762. copyPosition( m ) {
  8763. const te = this.elements, me = m.elements;
  8764. te[ 12 ] = me[ 12 ];
  8765. te[ 13 ] = me[ 13 ];
  8766. te[ 14 ] = me[ 14 ];
  8767. return this;
  8768. }
  8769. /**
  8770. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  8771. *
  8772. * @param {Matrix3} m - The 3x3 matrix.
  8773. * @return {Matrix4} A reference to this matrix.
  8774. */
  8775. setFromMatrix3( m ) {
  8776. const me = m.elements;
  8777. this.set(
  8778. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  8779. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  8780. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  8781. 0, 0, 0, 1
  8782. );
  8783. return this;
  8784. }
  8785. /**
  8786. * Extracts the basis of this matrix into the three axis vectors provided.
  8787. *
  8788. * @param {Vector3} xAxis - The basis's x axis.
  8789. * @param {Vector3} yAxis - The basis's y axis.
  8790. * @param {Vector3} zAxis - The basis's z axis.
  8791. * @return {Matrix4} A reference to this matrix.
  8792. */
  8793. extractBasis( xAxis, yAxis, zAxis ) {
  8794. xAxis.setFromMatrixColumn( this, 0 );
  8795. yAxis.setFromMatrixColumn( this, 1 );
  8796. zAxis.setFromMatrixColumn( this, 2 );
  8797. return this;
  8798. }
  8799. /**
  8800. * Sets the given basis vectors to this matrix.
  8801. *
  8802. * @param {Vector3} xAxis - The basis's x axis.
  8803. * @param {Vector3} yAxis - The basis's y axis.
  8804. * @param {Vector3} zAxis - The basis's z axis.
  8805. * @return {Matrix4} A reference to this matrix.
  8806. */
  8807. makeBasis( xAxis, yAxis, zAxis ) {
  8808. this.set(
  8809. xAxis.x, yAxis.x, zAxis.x, 0,
  8810. xAxis.y, yAxis.y, zAxis.y, 0,
  8811. xAxis.z, yAxis.z, zAxis.z, 0,
  8812. 0, 0, 0, 1
  8813. );
  8814. return this;
  8815. }
  8816. /**
  8817. * Extracts the rotation component of the given matrix
  8818. * into this matrix's rotation component.
  8819. *
  8820. * Note: This method does not support reflection matrices.
  8821. *
  8822. * @param {Matrix4} m - The matrix.
  8823. * @return {Matrix4} A reference to this matrix.
  8824. */
  8825. extractRotation( m ) {
  8826. const te = this.elements;
  8827. const me = m.elements;
  8828. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  8829. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  8830. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  8831. te[ 0 ] = me[ 0 ] * scaleX;
  8832. te[ 1 ] = me[ 1 ] * scaleX;
  8833. te[ 2 ] = me[ 2 ] * scaleX;
  8834. te[ 3 ] = 0;
  8835. te[ 4 ] = me[ 4 ] * scaleY;
  8836. te[ 5 ] = me[ 5 ] * scaleY;
  8837. te[ 6 ] = me[ 6 ] * scaleY;
  8838. te[ 7 ] = 0;
  8839. te[ 8 ] = me[ 8 ] * scaleZ;
  8840. te[ 9 ] = me[ 9 ] * scaleZ;
  8841. te[ 10 ] = me[ 10 ] * scaleZ;
  8842. te[ 11 ] = 0;
  8843. te[ 12 ] = 0;
  8844. te[ 13 ] = 0;
  8845. te[ 14 ] = 0;
  8846. te[ 15 ] = 1;
  8847. return this;
  8848. }
  8849. /**
  8850. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  8851. * the rotation specified by the given Euler angles. The rest of
  8852. * the matrix is set to the identity. Depending on the {@link Euler#order},
  8853. * there are six possible outcomes. See [this page]{@link https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix}
  8854. * for a complete list.
  8855. *
  8856. * @param {Euler} euler - The Euler angles.
  8857. * @return {Matrix4} A reference to this matrix.
  8858. */
  8859. makeRotationFromEuler( euler ) {
  8860. const te = this.elements;
  8861. const x = euler.x, y = euler.y, z = euler.z;
  8862. const a = Math.cos( x ), b = Math.sin( x );
  8863. const c = Math.cos( y ), d = Math.sin( y );
  8864. const e = Math.cos( z ), f = Math.sin( z );
  8865. if ( euler.order === 'XYZ' ) {
  8866. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8867. te[ 0 ] = c * e;
  8868. te[ 4 ] = - c * f;
  8869. te[ 8 ] = d;
  8870. te[ 1 ] = af + be * d;
  8871. te[ 5 ] = ae - bf * d;
  8872. te[ 9 ] = - b * c;
  8873. te[ 2 ] = bf - ae * d;
  8874. te[ 6 ] = be + af * d;
  8875. te[ 10 ] = a * c;
  8876. } else if ( euler.order === 'YXZ' ) {
  8877. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8878. te[ 0 ] = ce + df * b;
  8879. te[ 4 ] = de * b - cf;
  8880. te[ 8 ] = a * d;
  8881. te[ 1 ] = a * f;
  8882. te[ 5 ] = a * e;
  8883. te[ 9 ] = - b;
  8884. te[ 2 ] = cf * b - de;
  8885. te[ 6 ] = df + ce * b;
  8886. te[ 10 ] = a * c;
  8887. } else if ( euler.order === 'ZXY' ) {
  8888. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8889. te[ 0 ] = ce - df * b;
  8890. te[ 4 ] = - a * f;
  8891. te[ 8 ] = de + cf * b;
  8892. te[ 1 ] = cf + de * b;
  8893. te[ 5 ] = a * e;
  8894. te[ 9 ] = df - ce * b;
  8895. te[ 2 ] = - a * d;
  8896. te[ 6 ] = b;
  8897. te[ 10 ] = a * c;
  8898. } else if ( euler.order === 'ZYX' ) {
  8899. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8900. te[ 0 ] = c * e;
  8901. te[ 4 ] = be * d - af;
  8902. te[ 8 ] = ae * d + bf;
  8903. te[ 1 ] = c * f;
  8904. te[ 5 ] = bf * d + ae;
  8905. te[ 9 ] = af * d - be;
  8906. te[ 2 ] = - d;
  8907. te[ 6 ] = b * c;
  8908. te[ 10 ] = a * c;
  8909. } else if ( euler.order === 'YZX' ) {
  8910. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8911. te[ 0 ] = c * e;
  8912. te[ 4 ] = bd - ac * f;
  8913. te[ 8 ] = bc * f + ad;
  8914. te[ 1 ] = f;
  8915. te[ 5 ] = a * e;
  8916. te[ 9 ] = - b * e;
  8917. te[ 2 ] = - d * e;
  8918. te[ 6 ] = ad * f + bc;
  8919. te[ 10 ] = ac - bd * f;
  8920. } else if ( euler.order === 'XZY' ) {
  8921. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8922. te[ 0 ] = c * e;
  8923. te[ 4 ] = - f;
  8924. te[ 8 ] = d * e;
  8925. te[ 1 ] = ac * f + bd;
  8926. te[ 5 ] = a * e;
  8927. te[ 9 ] = ad * f - bc;
  8928. te[ 2 ] = bc * f - ad;
  8929. te[ 6 ] = b * e;
  8930. te[ 10 ] = bd * f + ac;
  8931. }
  8932. // bottom row
  8933. te[ 3 ] = 0;
  8934. te[ 7 ] = 0;
  8935. te[ 11 ] = 0;
  8936. // last column
  8937. te[ 12 ] = 0;
  8938. te[ 13 ] = 0;
  8939. te[ 14 ] = 0;
  8940. te[ 15 ] = 1;
  8941. return this;
  8942. }
  8943. /**
  8944. * Sets the rotation component of this matrix to the rotation specified by
  8945. * the given Quaternion as outlined [here]{@link https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion}
  8946. * The rest of the matrix is set to the identity.
  8947. *
  8948. * @param {Quaternion} q - The Quaternion.
  8949. * @return {Matrix4} A reference to this matrix.
  8950. */
  8951. makeRotationFromQuaternion( q ) {
  8952. return this.compose( _zero, q, _one );
  8953. }
  8954. /**
  8955. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  8956. * `target`, and oriented by the up-direction.
  8957. *
  8958. * @param {Vector3} eye - The eye vector.
  8959. * @param {Vector3} target - The target vector.
  8960. * @param {Vector3} up - The up vector.
  8961. * @return {Matrix4} A reference to this matrix.
  8962. */
  8963. lookAt( eye, target, up ) {
  8964. const te = this.elements;
  8965. _z.subVectors( eye, target );
  8966. if ( _z.lengthSq() === 0 ) {
  8967. // eye and target are in the same position
  8968. _z.z = 1;
  8969. }
  8970. _z.normalize();
  8971. _x.crossVectors( up, _z );
  8972. if ( _x.lengthSq() === 0 ) {
  8973. // up and z are parallel
  8974. if ( Math.abs( up.z ) === 1 ) {
  8975. _z.x += 0.0001;
  8976. } else {
  8977. _z.z += 0.0001;
  8978. }
  8979. _z.normalize();
  8980. _x.crossVectors( up, _z );
  8981. }
  8982. _x.normalize();
  8983. _y.crossVectors( _z, _x );
  8984. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  8985. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  8986. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  8987. return this;
  8988. }
  8989. /**
  8990. * Post-multiplies this matrix by the given 4x4 matrix.
  8991. *
  8992. * @param {Matrix4} m - The matrix to multiply with.
  8993. * @return {Matrix4} A reference to this matrix.
  8994. */
  8995. multiply( m ) {
  8996. return this.multiplyMatrices( this, m );
  8997. }
  8998. /**
  8999. * Pre-multiplies this matrix by the given 4x4 matrix.
  9000. *
  9001. * @param {Matrix4} m - The matrix to multiply with.
  9002. * @return {Matrix4} A reference to this matrix.
  9003. */
  9004. premultiply( m ) {
  9005. return this.multiplyMatrices( m, this );
  9006. }
  9007. /**
  9008. * Multiples the given 4x4 matrices and stores the result
  9009. * in this matrix.
  9010. *
  9011. * @param {Matrix4} a - The first matrix.
  9012. * @param {Matrix4} b - The second matrix.
  9013. * @return {Matrix4} A reference to this matrix.
  9014. */
  9015. multiplyMatrices( a, b ) {
  9016. const ae = a.elements;
  9017. const be = b.elements;
  9018. const te = this.elements;
  9019. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  9020. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  9021. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  9022. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  9023. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  9024. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  9025. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  9026. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  9027. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  9028. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  9029. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  9030. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  9031. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  9032. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  9033. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  9034. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  9035. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  9036. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  9037. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  9038. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  9039. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  9040. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  9041. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  9042. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  9043. return this;
  9044. }
  9045. /**
  9046. * Multiplies every component of the matrix by the given scalar.
  9047. *
  9048. * @param {number} s - The scalar.
  9049. * @return {Matrix4} A reference to this matrix.
  9050. */
  9051. multiplyScalar( s ) {
  9052. const te = this.elements;
  9053. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  9054. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  9055. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  9056. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  9057. return this;
  9058. }
  9059. /**
  9060. * Computes and returns the determinant of this matrix.
  9061. *
  9062. * Based on the method outlined [here]{@link http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html}.
  9063. *
  9064. * @return {number} The determinant.
  9065. */
  9066. determinant() {
  9067. const te = this.elements;
  9068. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  9069. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  9070. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  9071. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  9072. //TODO: make this more efficient
  9073. return (
  9074. n41 * (
  9075. + n14 * n23 * n32
  9076. - n13 * n24 * n32
  9077. - n14 * n22 * n33
  9078. + n12 * n24 * n33
  9079. + n13 * n22 * n34
  9080. - n12 * n23 * n34
  9081. ) +
  9082. n42 * (
  9083. + n11 * n23 * n34
  9084. - n11 * n24 * n33
  9085. + n14 * n21 * n33
  9086. - n13 * n21 * n34
  9087. + n13 * n24 * n31
  9088. - n14 * n23 * n31
  9089. ) +
  9090. n43 * (
  9091. + n11 * n24 * n32
  9092. - n11 * n22 * n34
  9093. - n14 * n21 * n32
  9094. + n12 * n21 * n34
  9095. + n14 * n22 * n31
  9096. - n12 * n24 * n31
  9097. ) +
  9098. n44 * (
  9099. - n13 * n22 * n31
  9100. - n11 * n23 * n32
  9101. + n11 * n22 * n33
  9102. + n13 * n21 * n32
  9103. - n12 * n21 * n33
  9104. + n12 * n23 * n31
  9105. )
  9106. );
  9107. }
  9108. /**
  9109. * Transposes this matrix in place.
  9110. *
  9111. * @return {Matrix4} A reference to this matrix.
  9112. */
  9113. transpose() {
  9114. const te = this.elements;
  9115. let tmp;
  9116. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  9117. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  9118. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  9119. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  9120. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  9121. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  9122. return this;
  9123. }
  9124. /**
  9125. * Sets the position component for this matrix from the given vector,
  9126. * without affecting the rest of the matrix.
  9127. *
  9128. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  9129. * @param {number} y - The y component of the vector.
  9130. * @param {number} z - The z component of the vector.
  9131. * @return {Matrix4} A reference to this matrix.
  9132. */
  9133. setPosition( x, y, z ) {
  9134. const te = this.elements;
  9135. if ( x.isVector3 ) {
  9136. te[ 12 ] = x.x;
  9137. te[ 13 ] = x.y;
  9138. te[ 14 ] = x.z;
  9139. } else {
  9140. te[ 12 ] = x;
  9141. te[ 13 ] = y;
  9142. te[ 14 ] = z;
  9143. }
  9144. return this;
  9145. }
  9146. /**
  9147. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  9148. * You can not invert with a determinant of zero. If you attempt this, the method produces
  9149. * a zero matrix instead.
  9150. *
  9151. * @return {Matrix4} A reference to this matrix.
  9152. */
  9153. invert() {
  9154. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  9155. const te = this.elements,
  9156. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  9157. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  9158. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  9159. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  9160. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  9161. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  9162. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  9163. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  9164. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  9165. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  9166. const detInv = 1 / det;
  9167. te[ 0 ] = t11 * detInv;
  9168. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  9169. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  9170. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  9171. te[ 4 ] = t12 * detInv;
  9172. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  9173. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  9174. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  9175. te[ 8 ] = t13 * detInv;
  9176. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  9177. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  9178. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  9179. te[ 12 ] = t14 * detInv;
  9180. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  9181. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  9182. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  9183. return this;
  9184. }
  9185. /**
  9186. * Multiplies the columns of this matrix by the given vector.
  9187. *
  9188. * @param {Vector3} v - The scale vector.
  9189. * @return {Matrix4} A reference to this matrix.
  9190. */
  9191. scale( v ) {
  9192. const te = this.elements;
  9193. const x = v.x, y = v.y, z = v.z;
  9194. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  9195. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  9196. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  9197. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  9198. return this;
  9199. }
  9200. /**
  9201. * Gets the maximum scale value of the three axes.
  9202. *
  9203. * @return {number} The maximum scale.
  9204. */
  9205. getMaxScaleOnAxis() {
  9206. const te = this.elements;
  9207. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  9208. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  9209. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  9210. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  9211. }
  9212. /**
  9213. * Sets this matrix as a translation transform from the given vector.
  9214. *
  9215. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  9216. * @param {number} y - The amount to translate in the Y axis.
  9217. * @param {number} z - The amount to translate in the z axis.
  9218. * @return {Matrix4} A reference to this matrix.
  9219. */
  9220. makeTranslation( x, y, z ) {
  9221. if ( x.isVector3 ) {
  9222. this.set(
  9223. 1, 0, 0, x.x,
  9224. 0, 1, 0, x.y,
  9225. 0, 0, 1, x.z,
  9226. 0, 0, 0, 1
  9227. );
  9228. } else {
  9229. this.set(
  9230. 1, 0, 0, x,
  9231. 0, 1, 0, y,
  9232. 0, 0, 1, z,
  9233. 0, 0, 0, 1
  9234. );
  9235. }
  9236. return this;
  9237. }
  9238. /**
  9239. * Sets this matrix as a rotational transformation around the X axis by
  9240. * the given angle.
  9241. *
  9242. * @param {number} theta - The rotation in radians.
  9243. * @return {Matrix4} A reference to this matrix.
  9244. */
  9245. makeRotationX( theta ) {
  9246. const c = Math.cos( theta ), s = Math.sin( theta );
  9247. this.set(
  9248. 1, 0, 0, 0,
  9249. 0, c, - s, 0,
  9250. 0, s, c, 0,
  9251. 0, 0, 0, 1
  9252. );
  9253. return this;
  9254. }
  9255. /**
  9256. * Sets this matrix as a rotational transformation around the Y axis by
  9257. * the given angle.
  9258. *
  9259. * @param {number} theta - The rotation in radians.
  9260. * @return {Matrix4} A reference to this matrix.
  9261. */
  9262. makeRotationY( theta ) {
  9263. const c = Math.cos( theta ), s = Math.sin( theta );
  9264. this.set(
  9265. c, 0, s, 0,
  9266. 0, 1, 0, 0,
  9267. - s, 0, c, 0,
  9268. 0, 0, 0, 1
  9269. );
  9270. return this;
  9271. }
  9272. /**
  9273. * Sets this matrix as a rotational transformation around the Z axis by
  9274. * the given angle.
  9275. *
  9276. * @param {number} theta - The rotation in radians.
  9277. * @return {Matrix4} A reference to this matrix.
  9278. */
  9279. makeRotationZ( theta ) {
  9280. const c = Math.cos( theta ), s = Math.sin( theta );
  9281. this.set(
  9282. c, - s, 0, 0,
  9283. s, c, 0, 0,
  9284. 0, 0, 1, 0,
  9285. 0, 0, 0, 1
  9286. );
  9287. return this;
  9288. }
  9289. /**
  9290. * Sets this matrix as a rotational transformation around the given axis by
  9291. * the given angle.
  9292. *
  9293. * This is a somewhat controversial but mathematically sound alternative to
  9294. * rotating via Quaternions. See the discussion [here]{@link https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199}.
  9295. *
  9296. * @param {Vector3} axis - The normalized rotation axis.
  9297. * @param {number} angle - The rotation in radians.
  9298. * @return {Matrix4} A reference to this matrix.
  9299. */
  9300. makeRotationAxis( axis, angle ) {
  9301. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  9302. const c = Math.cos( angle );
  9303. const s = Math.sin( angle );
  9304. const t = 1 - c;
  9305. const x = axis.x, y = axis.y, z = axis.z;
  9306. const tx = t * x, ty = t * y;
  9307. this.set(
  9308. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  9309. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  9310. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  9311. 0, 0, 0, 1
  9312. );
  9313. return this;
  9314. }
  9315. /**
  9316. * Sets this matrix as a scale transformation.
  9317. *
  9318. * @param {number} x - The amount to scale in the X axis.
  9319. * @param {number} y - The amount to scale in the Y axis.
  9320. * @param {number} z - The amount to scale in the Z axis.
  9321. * @return {Matrix4} A reference to this matrix.
  9322. */
  9323. makeScale( x, y, z ) {
  9324. this.set(
  9325. x, 0, 0, 0,
  9326. 0, y, 0, 0,
  9327. 0, 0, z, 0,
  9328. 0, 0, 0, 1
  9329. );
  9330. return this;
  9331. }
  9332. /**
  9333. * Sets this matrix as a shear transformation.
  9334. *
  9335. * @param {number} xy - The amount to shear X by Y.
  9336. * @param {number} xz - The amount to shear X by Z.
  9337. * @param {number} yx - The amount to shear Y by X.
  9338. * @param {number} yz - The amount to shear Y by Z.
  9339. * @param {number} zx - The amount to shear Z by X.
  9340. * @param {number} zy - The amount to shear Z by Y.
  9341. * @return {Matrix4} A reference to this matrix.
  9342. */
  9343. makeShear( xy, xz, yx, yz, zx, zy ) {
  9344. this.set(
  9345. 1, yx, zx, 0,
  9346. xy, 1, zy, 0,
  9347. xz, yz, 1, 0,
  9348. 0, 0, 0, 1
  9349. );
  9350. return this;
  9351. }
  9352. /**
  9353. * Sets this matrix to the transformation composed of the given position,
  9354. * rotation (Quaternion) and scale.
  9355. *
  9356. * @param {Vector3} position - The position vector.
  9357. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9358. * @param {Vector3} scale - The scale vector.
  9359. * @return {Matrix4} A reference to this matrix.
  9360. */
  9361. compose( position, quaternion, scale ) {
  9362. const te = this.elements;
  9363. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  9364. const x2 = x + x, y2 = y + y, z2 = z + z;
  9365. const xx = x * x2, xy = x * y2, xz = x * z2;
  9366. const yy = y * y2, yz = y * z2, zz = z * z2;
  9367. const wx = w * x2, wy = w * y2, wz = w * z2;
  9368. const sx = scale.x, sy = scale.y, sz = scale.z;
  9369. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  9370. te[ 1 ] = ( xy + wz ) * sx;
  9371. te[ 2 ] = ( xz - wy ) * sx;
  9372. te[ 3 ] = 0;
  9373. te[ 4 ] = ( xy - wz ) * sy;
  9374. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  9375. te[ 6 ] = ( yz + wx ) * sy;
  9376. te[ 7 ] = 0;
  9377. te[ 8 ] = ( xz + wy ) * sz;
  9378. te[ 9 ] = ( yz - wx ) * sz;
  9379. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  9380. te[ 11 ] = 0;
  9381. te[ 12 ] = position.x;
  9382. te[ 13 ] = position.y;
  9383. te[ 14 ] = position.z;
  9384. te[ 15 ] = 1;
  9385. return this;
  9386. }
  9387. /**
  9388. * Decomposes this matrix into its position, rotation and scale components
  9389. * and provides the result in the given objects.
  9390. *
  9391. * Note: Not all matrices are decomposable in this way. For example, if an
  9392. * object has a non-uniformly scaled parent, then the object's world matrix
  9393. * may not be decomposable, and this method may not be appropriate.
  9394. *
  9395. * @param {Vector3} position - The position vector.
  9396. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9397. * @param {Vector3} scale - The scale vector.
  9398. * @return {Matrix4} A reference to this matrix.
  9399. */
  9400. decompose( position, quaternion, scale ) {
  9401. const te = this.elements;
  9402. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  9403. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  9404. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  9405. // if determine is negative, we need to invert one scale
  9406. const det = this.determinant();
  9407. if ( det < 0 ) sx = - sx;
  9408. position.x = te[ 12 ];
  9409. position.y = te[ 13 ];
  9410. position.z = te[ 14 ];
  9411. // scale the rotation part
  9412. _m1$4.copy( this );
  9413. const invSX = 1 / sx;
  9414. const invSY = 1 / sy;
  9415. const invSZ = 1 / sz;
  9416. _m1$4.elements[ 0 ] *= invSX;
  9417. _m1$4.elements[ 1 ] *= invSX;
  9418. _m1$4.elements[ 2 ] *= invSX;
  9419. _m1$4.elements[ 4 ] *= invSY;
  9420. _m1$4.elements[ 5 ] *= invSY;
  9421. _m1$4.elements[ 6 ] *= invSY;
  9422. _m1$4.elements[ 8 ] *= invSZ;
  9423. _m1$4.elements[ 9 ] *= invSZ;
  9424. _m1$4.elements[ 10 ] *= invSZ;
  9425. quaternion.setFromRotationMatrix( _m1$4 );
  9426. scale.x = sx;
  9427. scale.y = sy;
  9428. scale.z = sz;
  9429. return this;
  9430. }
  9431. /**
  9432. * Creates a perspective projection matrix. This is used internally by
  9433. * {@link PerspectiveCamera#updateProjectionMatrix}.
  9434. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9435. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9436. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9437. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9438. * @param {number} near - The distance from the camera to the near plane.
  9439. * @param {number} far - The distance from the camera to the far plane.
  9440. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9441. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9442. * @return {Matrix4} A reference to this matrix.
  9443. */
  9444. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9445. const te = this.elements;
  9446. const x = 2 * near / ( right - left );
  9447. const y = 2 * near / ( top - bottom );
  9448. const a = ( right + left ) / ( right - left );
  9449. const b = ( top + bottom ) / ( top - bottom );
  9450. let c, d;
  9451. if ( reversedDepth ) {
  9452. c = near / ( far - near );
  9453. d = ( far * near ) / ( far - near );
  9454. } else {
  9455. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9456. c = - ( far + near ) / ( far - near );
  9457. d = ( -2 * far * near ) / ( far - near );
  9458. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9459. c = - far / ( far - near );
  9460. d = ( - far * near ) / ( far - near );
  9461. } else {
  9462. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  9463. }
  9464. }
  9465. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  9466. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  9467. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9468. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  9469. return this;
  9470. }
  9471. /**
  9472. * Creates a orthographic projection matrix. This is used internally by
  9473. * {@link OrthographicCamera#updateProjectionMatrix}.
  9474. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9475. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9476. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9477. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9478. * @param {number} near - The distance from the camera to the near plane.
  9479. * @param {number} far - The distance from the camera to the far plane.
  9480. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9481. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9482. * @return {Matrix4} A reference to this matrix.
  9483. */
  9484. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9485. const te = this.elements;
  9486. const x = 2 / ( right - left );
  9487. const y = 2 / ( top - bottom );
  9488. const a = - ( right + left ) / ( right - left );
  9489. const b = - ( top + bottom ) / ( top - bottom );
  9490. let c, d;
  9491. if ( reversedDepth ) {
  9492. c = 1 / ( far - near );
  9493. d = far / ( far - near );
  9494. } else {
  9495. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9496. c = -2 / ( far - near );
  9497. d = - ( far + near ) / ( far - near );
  9498. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9499. c = -1 / ( far - near );
  9500. d = - near / ( far - near );
  9501. } else {
  9502. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  9503. }
  9504. }
  9505. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = a;
  9506. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = 0; te[ 13 ] = b;
  9507. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9508. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  9509. return this;
  9510. }
  9511. /**
  9512. * Returns `true` if this matrix is equal with the given one.
  9513. *
  9514. * @param {Matrix4} matrix - The matrix to test for equality.
  9515. * @return {boolean} Whether this matrix is equal with the given one.
  9516. */
  9517. equals( matrix ) {
  9518. const te = this.elements;
  9519. const me = matrix.elements;
  9520. for ( let i = 0; i < 16; i ++ ) {
  9521. if ( te[ i ] !== me[ i ] ) return false;
  9522. }
  9523. return true;
  9524. }
  9525. /**
  9526. * Sets the elements of the matrix from the given array.
  9527. *
  9528. * @param {Array<number>} array - The matrix elements in column-major order.
  9529. * @param {number} [offset=0] - Index of the first element in the array.
  9530. * @return {Matrix4} A reference to this matrix.
  9531. */
  9532. fromArray( array, offset = 0 ) {
  9533. for ( let i = 0; i < 16; i ++ ) {
  9534. this.elements[ i ] = array[ i + offset ];
  9535. }
  9536. return this;
  9537. }
  9538. /**
  9539. * Writes the elements of this matrix to the given array. If no array is provided,
  9540. * the method returns a new instance.
  9541. *
  9542. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  9543. * @param {number} [offset=0] - Index of the first element in the array.
  9544. * @return {Array<number>} The matrix elements in column-major order.
  9545. */
  9546. toArray( array = [], offset = 0 ) {
  9547. const te = this.elements;
  9548. array[ offset ] = te[ 0 ];
  9549. array[ offset + 1 ] = te[ 1 ];
  9550. array[ offset + 2 ] = te[ 2 ];
  9551. array[ offset + 3 ] = te[ 3 ];
  9552. array[ offset + 4 ] = te[ 4 ];
  9553. array[ offset + 5 ] = te[ 5 ];
  9554. array[ offset + 6 ] = te[ 6 ];
  9555. array[ offset + 7 ] = te[ 7 ];
  9556. array[ offset + 8 ] = te[ 8 ];
  9557. array[ offset + 9 ] = te[ 9 ];
  9558. array[ offset + 10 ] = te[ 10 ];
  9559. array[ offset + 11 ] = te[ 11 ];
  9560. array[ offset + 12 ] = te[ 12 ];
  9561. array[ offset + 13 ] = te[ 13 ];
  9562. array[ offset + 14 ] = te[ 14 ];
  9563. array[ offset + 15 ] = te[ 15 ];
  9564. return array;
  9565. }
  9566. }
  9567. const _v1$5 = /*@__PURE__*/ new Vector3();
  9568. const _m1$4 = /*@__PURE__*/ new Matrix4();
  9569. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  9570. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  9571. const _x = /*@__PURE__*/ new Vector3();
  9572. const _y = /*@__PURE__*/ new Vector3();
  9573. const _z = /*@__PURE__*/ new Vector3();
  9574. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  9575. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  9576. /**
  9577. * A class representing Euler angles.
  9578. *
  9579. * Euler angles describe a rotational transformation by rotating an object on
  9580. * its various axes in specified amounts per axis, and a specified axis
  9581. * order.
  9582. *
  9583. * Iterating through an instance will yield its components (x, y, z,
  9584. * order) in the corresponding order.
  9585. *
  9586. * ```js
  9587. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  9588. * const b = new THREE.Vector3( 1, 0, 1 );
  9589. * b.applyEuler(a);
  9590. * ```
  9591. */
  9592. class Euler {
  9593. /**
  9594. * Constructs a new euler instance.
  9595. *
  9596. * @param {number} [x=0] - The angle of the x axis in radians.
  9597. * @param {number} [y=0] - The angle of the y axis in radians.
  9598. * @param {number} [z=0] - The angle of the z axis in radians.
  9599. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  9600. */
  9601. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  9602. /**
  9603. * This flag can be used for type testing.
  9604. *
  9605. * @type {boolean}
  9606. * @readonly
  9607. * @default true
  9608. */
  9609. this.isEuler = true;
  9610. this._x = x;
  9611. this._y = y;
  9612. this._z = z;
  9613. this._order = order;
  9614. }
  9615. /**
  9616. * The angle of the x axis in radians.
  9617. *
  9618. * @type {number}
  9619. * @default 0
  9620. */
  9621. get x() {
  9622. return this._x;
  9623. }
  9624. set x( value ) {
  9625. this._x = value;
  9626. this._onChangeCallback();
  9627. }
  9628. /**
  9629. * The angle of the y axis in radians.
  9630. *
  9631. * @type {number}
  9632. * @default 0
  9633. */
  9634. get y() {
  9635. return this._y;
  9636. }
  9637. set y( value ) {
  9638. this._y = value;
  9639. this._onChangeCallback();
  9640. }
  9641. /**
  9642. * The angle of the z axis in radians.
  9643. *
  9644. * @type {number}
  9645. * @default 0
  9646. */
  9647. get z() {
  9648. return this._z;
  9649. }
  9650. set z( value ) {
  9651. this._z = value;
  9652. this._onChangeCallback();
  9653. }
  9654. /**
  9655. * A string representing the order that the rotations are applied.
  9656. *
  9657. * @type {string}
  9658. * @default 'XYZ'
  9659. */
  9660. get order() {
  9661. return this._order;
  9662. }
  9663. set order( value ) {
  9664. this._order = value;
  9665. this._onChangeCallback();
  9666. }
  9667. /**
  9668. * Sets the Euler components.
  9669. *
  9670. * @param {number} x - The angle of the x axis in radians.
  9671. * @param {number} y - The angle of the y axis in radians.
  9672. * @param {number} z - The angle of the z axis in radians.
  9673. * @param {string} [order] - A string representing the order that the rotations are applied.
  9674. * @return {Euler} A reference to this Euler instance.
  9675. */
  9676. set( x, y, z, order = this._order ) {
  9677. this._x = x;
  9678. this._y = y;
  9679. this._z = z;
  9680. this._order = order;
  9681. this._onChangeCallback();
  9682. return this;
  9683. }
  9684. /**
  9685. * Returns a new Euler instance with copied values from this instance.
  9686. *
  9687. * @return {Euler} A clone of this instance.
  9688. */
  9689. clone() {
  9690. return new this.constructor( this._x, this._y, this._z, this._order );
  9691. }
  9692. /**
  9693. * Copies the values of the given Euler instance to this instance.
  9694. *
  9695. * @param {Euler} euler - The Euler instance to copy.
  9696. * @return {Euler} A reference to this Euler instance.
  9697. */
  9698. copy( euler ) {
  9699. this._x = euler._x;
  9700. this._y = euler._y;
  9701. this._z = euler._z;
  9702. this._order = euler._order;
  9703. this._onChangeCallback();
  9704. return this;
  9705. }
  9706. /**
  9707. * Sets the angles of this Euler instance from a pure rotation matrix.
  9708. *
  9709. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  9710. * @param {string} [order] - A string representing the order that the rotations are applied.
  9711. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9712. * @return {Euler} A reference to this Euler instance.
  9713. */
  9714. setFromRotationMatrix( m, order = this._order, update = true ) {
  9715. const te = m.elements;
  9716. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  9717. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  9718. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  9719. switch ( order ) {
  9720. case 'XYZ':
  9721. this._y = Math.asin( clamp( m13, -1, 1 ) );
  9722. if ( Math.abs( m13 ) < 0.9999999 ) {
  9723. this._x = Math.atan2( - m23, m33 );
  9724. this._z = Math.atan2( - m12, m11 );
  9725. } else {
  9726. this._x = Math.atan2( m32, m22 );
  9727. this._z = 0;
  9728. }
  9729. break;
  9730. case 'YXZ':
  9731. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  9732. if ( Math.abs( m23 ) < 0.9999999 ) {
  9733. this._y = Math.atan2( m13, m33 );
  9734. this._z = Math.atan2( m21, m22 );
  9735. } else {
  9736. this._y = Math.atan2( - m31, m11 );
  9737. this._z = 0;
  9738. }
  9739. break;
  9740. case 'ZXY':
  9741. this._x = Math.asin( clamp( m32, -1, 1 ) );
  9742. if ( Math.abs( m32 ) < 0.9999999 ) {
  9743. this._y = Math.atan2( - m31, m33 );
  9744. this._z = Math.atan2( - m12, m22 );
  9745. } else {
  9746. this._y = 0;
  9747. this._z = Math.atan2( m21, m11 );
  9748. }
  9749. break;
  9750. case 'ZYX':
  9751. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  9752. if ( Math.abs( m31 ) < 0.9999999 ) {
  9753. this._x = Math.atan2( m32, m33 );
  9754. this._z = Math.atan2( m21, m11 );
  9755. } else {
  9756. this._x = 0;
  9757. this._z = Math.atan2( - m12, m22 );
  9758. }
  9759. break;
  9760. case 'YZX':
  9761. this._z = Math.asin( clamp( m21, -1, 1 ) );
  9762. if ( Math.abs( m21 ) < 0.9999999 ) {
  9763. this._x = Math.atan2( - m23, m22 );
  9764. this._y = Math.atan2( - m31, m11 );
  9765. } else {
  9766. this._x = 0;
  9767. this._y = Math.atan2( m13, m33 );
  9768. }
  9769. break;
  9770. case 'XZY':
  9771. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  9772. if ( Math.abs( m12 ) < 0.9999999 ) {
  9773. this._x = Math.atan2( m32, m22 );
  9774. this._y = Math.atan2( m13, m11 );
  9775. } else {
  9776. this._x = Math.atan2( - m23, m33 );
  9777. this._y = 0;
  9778. }
  9779. break;
  9780. default:
  9781. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  9782. }
  9783. this._order = order;
  9784. if ( update === true ) this._onChangeCallback();
  9785. return this;
  9786. }
  9787. /**
  9788. * Sets the angles of this Euler instance from a normalized quaternion.
  9789. *
  9790. * @param {Quaternion} q - A normalized Quaternion.
  9791. * @param {string} [order] - A string representing the order that the rotations are applied.
  9792. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9793. * @return {Euler} A reference to this Euler instance.
  9794. */
  9795. setFromQuaternion( q, order, update ) {
  9796. _matrix$2.makeRotationFromQuaternion( q );
  9797. return this.setFromRotationMatrix( _matrix$2, order, update );
  9798. }
  9799. /**
  9800. * Sets the angles of this Euler instance from the given vector.
  9801. *
  9802. * @param {Vector3} v - The vector.
  9803. * @param {string} [order] - A string representing the order that the rotations are applied.
  9804. * @return {Euler} A reference to this Euler instance.
  9805. */
  9806. setFromVector3( v, order = this._order ) {
  9807. return this.set( v.x, v.y, v.z, order );
  9808. }
  9809. /**
  9810. * Resets the euler angle with a new order by creating a quaternion from this
  9811. * euler angle and then setting this euler angle with the quaternion and the
  9812. * new order.
  9813. *
  9814. * Warning: This discards revolution information.
  9815. *
  9816. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  9817. * @return {Euler} A reference to this Euler instance.
  9818. */
  9819. reorder( newOrder ) {
  9820. _quaternion$3.setFromEuler( this );
  9821. return this.setFromQuaternion( _quaternion$3, newOrder );
  9822. }
  9823. /**
  9824. * Returns `true` if this Euler instance is equal with the given one.
  9825. *
  9826. * @param {Euler} euler - The Euler instance to test for equality.
  9827. * @return {boolean} Whether this Euler instance is equal with the given one.
  9828. */
  9829. equals( euler ) {
  9830. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  9831. }
  9832. /**
  9833. * Sets this Euler instance's components to values from the given array. The first three
  9834. * entries of the array are assign to the x,y and z components. An optional fourth entry
  9835. * defines the Euler order.
  9836. *
  9837. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  9838. * @return {Euler} A reference to this Euler instance.
  9839. */
  9840. fromArray( array ) {
  9841. this._x = array[ 0 ];
  9842. this._y = array[ 1 ];
  9843. this._z = array[ 2 ];
  9844. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  9845. this._onChangeCallback();
  9846. return this;
  9847. }
  9848. /**
  9849. * Writes the components of this Euler instance to the given array. If no array is provided,
  9850. * the method returns a new instance.
  9851. *
  9852. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  9853. * @param {number} [offset=0] - Index of the first element in the array.
  9854. * @return {Array<number,number,number,string>} The Euler components.
  9855. */
  9856. toArray( array = [], offset = 0 ) {
  9857. array[ offset ] = this._x;
  9858. array[ offset + 1 ] = this._y;
  9859. array[ offset + 2 ] = this._z;
  9860. array[ offset + 3 ] = this._order;
  9861. return array;
  9862. }
  9863. _onChange( callback ) {
  9864. this._onChangeCallback = callback;
  9865. return this;
  9866. }
  9867. _onChangeCallback() {}
  9868. *[ Symbol.iterator ]() {
  9869. yield this._x;
  9870. yield this._y;
  9871. yield this._z;
  9872. yield this._order;
  9873. }
  9874. }
  9875. /**
  9876. * The default Euler angle order.
  9877. *
  9878. * @static
  9879. * @type {string}
  9880. * @default 'XYZ'
  9881. */
  9882. Euler.DEFAULT_ORDER = 'XYZ';
  9883. /**
  9884. * A layers object assigns an 3D object to 1 or more of 32
  9885. * layers numbered `0` to `31` - internally the layers are stored as a
  9886. * bit mask], and by default all 3D objects are a member of layer `0`.
  9887. *
  9888. * This can be used to control visibility - an object must share a layer with
  9889. * a camera to be visible when that camera's view is
  9890. * rendered.
  9891. *
  9892. * All classes that inherit from {@link Object3D} have an `layers` property which
  9893. * is an instance of this class.
  9894. */
  9895. class Layers {
  9896. /**
  9897. * Constructs a new layers instance, with membership
  9898. * initially set to layer `0`.
  9899. */
  9900. constructor() {
  9901. /**
  9902. * A bit mask storing which of the 32 layers this layers object is currently
  9903. * a member of.
  9904. *
  9905. * @type {number}
  9906. */
  9907. this.mask = 1 | 0;
  9908. }
  9909. /**
  9910. * Sets membership to the given layer, and remove membership all other layers.
  9911. *
  9912. * @param {number} layer - The layer to set.
  9913. */
  9914. set( layer ) {
  9915. this.mask = ( 1 << layer | 0 ) >>> 0;
  9916. }
  9917. /**
  9918. * Adds membership of the given layer.
  9919. *
  9920. * @param {number} layer - The layer to enable.
  9921. */
  9922. enable( layer ) {
  9923. this.mask |= 1 << layer | 0;
  9924. }
  9925. /**
  9926. * Adds membership to all layers.
  9927. */
  9928. enableAll() {
  9929. this.mask = 0xffffffff | 0;
  9930. }
  9931. /**
  9932. * Toggles the membership of the given layer.
  9933. *
  9934. * @param {number} layer - The layer to toggle.
  9935. */
  9936. toggle( layer ) {
  9937. this.mask ^= 1 << layer | 0;
  9938. }
  9939. /**
  9940. * Removes membership of the given layer.
  9941. *
  9942. * @param {number} layer - The layer to enable.
  9943. */
  9944. disable( layer ) {
  9945. this.mask &= ~ ( 1 << layer | 0 );
  9946. }
  9947. /**
  9948. * Removes the membership from all layers.
  9949. */
  9950. disableAll() {
  9951. this.mask = 0;
  9952. }
  9953. /**
  9954. * Returns `true` if this and the given layers object have at least one
  9955. * layer in common.
  9956. *
  9957. * @param {Layers} layers - The layers to test.
  9958. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  9959. */
  9960. test( layers ) {
  9961. return ( this.mask & layers.mask ) !== 0;
  9962. }
  9963. /**
  9964. * Returns `true` if the given layer is enabled.
  9965. *
  9966. * @param {number} layer - The layer to test.
  9967. * @return {boolean } Whether the given layer is enabled or not.
  9968. */
  9969. isEnabled( layer ) {
  9970. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  9971. }
  9972. }
  9973. let _object3DId = 0;
  9974. const _v1$4 = /*@__PURE__*/ new Vector3();
  9975. const _q1 = /*@__PURE__*/ new Quaternion();
  9976. const _m1$3 = /*@__PURE__*/ new Matrix4();
  9977. const _target = /*@__PURE__*/ new Vector3();
  9978. const _position$3 = /*@__PURE__*/ new Vector3();
  9979. const _scale$2 = /*@__PURE__*/ new Vector3();
  9980. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  9981. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  9982. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  9983. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  9984. /**
  9985. * Fires when the object has been added to its parent object.
  9986. *
  9987. * @event Object3D#added
  9988. * @type {Object}
  9989. */
  9990. const _addedEvent = { type: 'added' };
  9991. /**
  9992. * Fires when the object has been removed from its parent object.
  9993. *
  9994. * @event Object3D#removed
  9995. * @type {Object}
  9996. */
  9997. const _removedEvent = { type: 'removed' };
  9998. /**
  9999. * Fires when a new child object has been added.
  10000. *
  10001. * @event Object3D#childadded
  10002. * @type {Object}
  10003. */
  10004. const _childaddedEvent = { type: 'childadded', child: null };
  10005. /**
  10006. * Fires when a child object has been removed.
  10007. *
  10008. * @event Object3D#childremoved
  10009. * @type {Object}
  10010. */
  10011. const _childremovedEvent = { type: 'childremoved', child: null };
  10012. /**
  10013. * This is the base class for most objects in three.js and provides a set of
  10014. * properties and methods for manipulating objects in 3D space.
  10015. *
  10016. * @augments EventDispatcher
  10017. */
  10018. class Object3D extends EventDispatcher {
  10019. /**
  10020. * Constructs a new 3D object.
  10021. */
  10022. constructor() {
  10023. super();
  10024. /**
  10025. * This flag can be used for type testing.
  10026. *
  10027. * @type {boolean}
  10028. * @readonly
  10029. * @default true
  10030. */
  10031. this.isObject3D = true;
  10032. /**
  10033. * The ID of the 3D object.
  10034. *
  10035. * @name Object3D#id
  10036. * @type {number}
  10037. * @readonly
  10038. */
  10039. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  10040. /**
  10041. * The UUID of the 3D object.
  10042. *
  10043. * @type {string}
  10044. * @readonly
  10045. */
  10046. this.uuid = generateUUID();
  10047. /**
  10048. * The name of the 3D object.
  10049. *
  10050. * @type {string}
  10051. */
  10052. this.name = '';
  10053. /**
  10054. * The type property is used for detecting the object type
  10055. * in context of serialization/deserialization.
  10056. *
  10057. * @type {string}
  10058. * @readonly
  10059. */
  10060. this.type = 'Object3D';
  10061. /**
  10062. * A reference to the parent object.
  10063. *
  10064. * @type {?Object3D}
  10065. * @default null
  10066. */
  10067. this.parent = null;
  10068. /**
  10069. * An array holding the child 3D objects of this instance.
  10070. *
  10071. * @type {Array<Object3D>}
  10072. */
  10073. this.children = [];
  10074. /**
  10075. * Defines the `up` direction of the 3D object which influences
  10076. * the orientation via methods like {@link Object3D#lookAt}.
  10077. *
  10078. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  10079. *
  10080. * @type {Vector3}
  10081. */
  10082. this.up = Object3D.DEFAULT_UP.clone();
  10083. const position = new Vector3();
  10084. const rotation = new Euler();
  10085. const quaternion = new Quaternion();
  10086. const scale = new Vector3( 1, 1, 1 );
  10087. function onRotationChange() {
  10088. quaternion.setFromEuler( rotation, false );
  10089. }
  10090. function onQuaternionChange() {
  10091. rotation.setFromQuaternion( quaternion, undefined, false );
  10092. }
  10093. rotation._onChange( onRotationChange );
  10094. quaternion._onChange( onQuaternionChange );
  10095. Object.defineProperties( this, {
  10096. /**
  10097. * Represents the object's local position.
  10098. *
  10099. * @name Object3D#position
  10100. * @type {Vector3}
  10101. * @default (0,0,0)
  10102. */
  10103. position: {
  10104. configurable: true,
  10105. enumerable: true,
  10106. value: position
  10107. },
  10108. /**
  10109. * Represents the object's local rotation as Euler angles, in radians.
  10110. *
  10111. * @name Object3D#rotation
  10112. * @type {Euler}
  10113. * @default (0,0,0)
  10114. */
  10115. rotation: {
  10116. configurable: true,
  10117. enumerable: true,
  10118. value: rotation
  10119. },
  10120. /**
  10121. * Represents the object's local rotation as Quaternions.
  10122. *
  10123. * @name Object3D#quaternion
  10124. * @type {Quaternion}
  10125. */
  10126. quaternion: {
  10127. configurable: true,
  10128. enumerable: true,
  10129. value: quaternion
  10130. },
  10131. /**
  10132. * Represents the object's local scale.
  10133. *
  10134. * @name Object3D#scale
  10135. * @type {Vector3}
  10136. * @default (1,1,1)
  10137. */
  10138. scale: {
  10139. configurable: true,
  10140. enumerable: true,
  10141. value: scale
  10142. },
  10143. /**
  10144. * Represents the object's model-view matrix.
  10145. *
  10146. * @name Object3D#modelViewMatrix
  10147. * @type {Matrix4}
  10148. */
  10149. modelViewMatrix: {
  10150. value: new Matrix4()
  10151. },
  10152. /**
  10153. * Represents the object's normal matrix.
  10154. *
  10155. * @name Object3D#normalMatrix
  10156. * @type {Matrix3}
  10157. */
  10158. normalMatrix: {
  10159. value: new Matrix3()
  10160. }
  10161. } );
  10162. /**
  10163. * Represents the object's transformation matrix in local space.
  10164. *
  10165. * @type {Matrix4}
  10166. */
  10167. this.matrix = new Matrix4();
  10168. /**
  10169. * Represents the object's transformation matrix in world space.
  10170. * If the 3D object has no parent, then it's identical to the local transformation matrix
  10171. *
  10172. * @type {Matrix4}
  10173. */
  10174. this.matrixWorld = new Matrix4();
  10175. /**
  10176. * When set to `true`, the engine automatically computes the local matrix from position,
  10177. * rotation and scale every frame.
  10178. *
  10179. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  10180. *
  10181. * @type {boolean}
  10182. * @default true
  10183. */
  10184. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  10185. /**
  10186. * When set to `true`, the engine automatically computes the world matrix from the current local
  10187. * matrix and the object's transformation hierarchy.
  10188. *
  10189. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  10190. *
  10191. * @type {boolean}
  10192. * @default true
  10193. */
  10194. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  10195. /**
  10196. * When set to `true`, it calculates the world matrix in that frame and resets this property
  10197. * to `false`.
  10198. *
  10199. * @type {boolean}
  10200. * @default false
  10201. */
  10202. this.matrixWorldNeedsUpdate = false;
  10203. /**
  10204. * The layer membership of the 3D object. The 3D object is only visible if it has
  10205. * at least one layer in common with the camera in use. This property can also be
  10206. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  10207. *
  10208. * @type {Layers}
  10209. */
  10210. this.layers = new Layers();
  10211. /**
  10212. * When set to `true`, the 3D object gets rendered.
  10213. *
  10214. * @type {boolean}
  10215. * @default true
  10216. */
  10217. this.visible = true;
  10218. /**
  10219. * When set to `true`, the 3D object gets rendered into shadow maps.
  10220. *
  10221. * @type {boolean}
  10222. * @default false
  10223. */
  10224. this.castShadow = false;
  10225. /**
  10226. * When set to `true`, the 3D object is affected by shadows in the scene.
  10227. *
  10228. * @type {boolean}
  10229. * @default false
  10230. */
  10231. this.receiveShadow = false;
  10232. /**
  10233. * When set to `true`, the 3D object is honored by view frustum culling.
  10234. *
  10235. * @type {boolean}
  10236. * @default true
  10237. */
  10238. this.frustumCulled = true;
  10239. /**
  10240. * This value allows the default rendering order of scene graph objects to be
  10241. * overridden although opaque and transparent objects remain sorted independently.
  10242. * When this property is set for an instance of {@link Group},all descendants
  10243. * objects will be sorted and rendered together. Sorting is from lowest to highest
  10244. * render order.
  10245. *
  10246. * @type {number}
  10247. * @default 0
  10248. */
  10249. this.renderOrder = 0;
  10250. /**
  10251. * An array holding the animation clips of the 3D object.
  10252. *
  10253. * @type {Array<AnimationClip>}
  10254. */
  10255. this.animations = [];
  10256. /**
  10257. * Custom depth material to be used when rendering to the depth map. Can only be used
  10258. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  10259. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  10260. * material for proper shadows.
  10261. *
  10262. * Only relevant in context of {@link WebGLRenderer}.
  10263. *
  10264. * @type {(Material|undefined)}
  10265. * @default undefined
  10266. */
  10267. this.customDepthMaterial = undefined;
  10268. /**
  10269. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  10270. *
  10271. * Only relevant in context of {@link WebGLRenderer}.
  10272. *
  10273. * @type {(Material|undefined)}
  10274. * @default undefined
  10275. */
  10276. this.customDistanceMaterial = undefined;
  10277. /**
  10278. * An object that can be used to store custom data about the 3D object. It
  10279. * should not hold references to functions as these will not be cloned.
  10280. *
  10281. * @type {Object}
  10282. */
  10283. this.userData = {};
  10284. }
  10285. /**
  10286. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  10287. *
  10288. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10289. * @param {Object3D} object - The 3D object.
  10290. * @param {Camera} camera - The camera that is used to render the scene.
  10291. * @param {Camera} shadowCamera - The shadow camera.
  10292. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10293. * @param {Material} depthMaterial - The depth material.
  10294. * @param {Object} group - The geometry group data.
  10295. */
  10296. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10297. /**
  10298. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  10299. *
  10300. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10301. * @param {Object3D} object - The 3D object.
  10302. * @param {Camera} camera - The camera that is used to render the scene.
  10303. * @param {Camera} shadowCamera - The shadow camera.
  10304. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10305. * @param {Material} depthMaterial - The depth material.
  10306. * @param {Object} group - The geometry group data.
  10307. */
  10308. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10309. /**
  10310. * A callback that is executed immediately before a 3D object is rendered.
  10311. *
  10312. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10313. * @param {Object3D} object - The 3D object.
  10314. * @param {Camera} camera - The camera that is used to render the scene.
  10315. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10316. * @param {Material} material - The 3D object's material.
  10317. * @param {Object} group - The geometry group data.
  10318. */
  10319. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10320. /**
  10321. * A callback that is executed immediately after a 3D object is rendered.
  10322. *
  10323. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10324. * @param {Object3D} object - The 3D object.
  10325. * @param {Camera} camera - The camera that is used to render the scene.
  10326. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10327. * @param {Material} material - The 3D object's material.
  10328. * @param {Object} group - The geometry group data.
  10329. */
  10330. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10331. /**
  10332. * Applies the given transformation matrix to the object and updates the object's position,
  10333. * rotation and scale.
  10334. *
  10335. * @param {Matrix4} matrix - The transformation matrix.
  10336. */
  10337. applyMatrix4( matrix ) {
  10338. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10339. this.matrix.premultiply( matrix );
  10340. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10341. }
  10342. /**
  10343. * Applies a rotation represented by given the quaternion to the 3D object.
  10344. *
  10345. * @param {Quaternion} q - The quaternion.
  10346. * @return {Object3D} A reference to this instance.
  10347. */
  10348. applyQuaternion( q ) {
  10349. this.quaternion.premultiply( q );
  10350. return this;
  10351. }
  10352. /**
  10353. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  10354. *
  10355. * @param {Vector3} axis - The (normalized) axis vector.
  10356. * @param {number} angle - The angle in radians.
  10357. */
  10358. setRotationFromAxisAngle( axis, angle ) {
  10359. // assumes axis is normalized
  10360. this.quaternion.setFromAxisAngle( axis, angle );
  10361. }
  10362. /**
  10363. * Sets the given rotation represented as Euler angles to the 3D object.
  10364. *
  10365. * @param {Euler} euler - The Euler angles.
  10366. */
  10367. setRotationFromEuler( euler ) {
  10368. this.quaternion.setFromEuler( euler, true );
  10369. }
  10370. /**
  10371. * Sets the given rotation represented as rotation matrix to the 3D object.
  10372. *
  10373. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  10374. * a pure rotation matrix (i.e, unscaled).
  10375. */
  10376. setRotationFromMatrix( m ) {
  10377. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10378. this.quaternion.setFromRotationMatrix( m );
  10379. }
  10380. /**
  10381. * Sets the given rotation represented as a Quaternion to the 3D object.
  10382. *
  10383. * @param {Quaternion} q - The Quaternion
  10384. */
  10385. setRotationFromQuaternion( q ) {
  10386. // assumes q is normalized
  10387. this.quaternion.copy( q );
  10388. }
  10389. /**
  10390. * Rotates the 3D object along an axis in local space.
  10391. *
  10392. * @param {Vector3} axis - The (normalized) axis vector.
  10393. * @param {number} angle - The angle in radians.
  10394. * @return {Object3D} A reference to this instance.
  10395. */
  10396. rotateOnAxis( axis, angle ) {
  10397. // rotate object on axis in object space
  10398. // axis is assumed to be normalized
  10399. _q1.setFromAxisAngle( axis, angle );
  10400. this.quaternion.multiply( _q1 );
  10401. return this;
  10402. }
  10403. /**
  10404. * Rotates the 3D object along an axis in world space.
  10405. *
  10406. * @param {Vector3} axis - The (normalized) axis vector.
  10407. * @param {number} angle - The angle in radians.
  10408. * @return {Object3D} A reference to this instance.
  10409. */
  10410. rotateOnWorldAxis( axis, angle ) {
  10411. // rotate object on axis in world space
  10412. // axis is assumed to be normalized
  10413. // method assumes no rotated parent
  10414. _q1.setFromAxisAngle( axis, angle );
  10415. this.quaternion.premultiply( _q1 );
  10416. return this;
  10417. }
  10418. /**
  10419. * Rotates the 3D object around its X axis in local space.
  10420. *
  10421. * @param {number} angle - The angle in radians.
  10422. * @return {Object3D} A reference to this instance.
  10423. */
  10424. rotateX( angle ) {
  10425. return this.rotateOnAxis( _xAxis, angle );
  10426. }
  10427. /**
  10428. * Rotates the 3D object around its Y axis in local space.
  10429. *
  10430. * @param {number} angle - The angle in radians.
  10431. * @return {Object3D} A reference to this instance.
  10432. */
  10433. rotateY( angle ) {
  10434. return this.rotateOnAxis( _yAxis, angle );
  10435. }
  10436. /**
  10437. * Rotates the 3D object around its Z axis in local space.
  10438. *
  10439. * @param {number} angle - The angle in radians.
  10440. * @return {Object3D} A reference to this instance.
  10441. */
  10442. rotateZ( angle ) {
  10443. return this.rotateOnAxis( _zAxis, angle );
  10444. }
  10445. /**
  10446. * Translate the 3D object by a distance along the given axis in local space.
  10447. *
  10448. * @param {Vector3} axis - The (normalized) axis vector.
  10449. * @param {number} distance - The distance in world units.
  10450. * @return {Object3D} A reference to this instance.
  10451. */
  10452. translateOnAxis( axis, distance ) {
  10453. // translate object by distance along axis in object space
  10454. // axis is assumed to be normalized
  10455. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  10456. this.position.add( _v1$4.multiplyScalar( distance ) );
  10457. return this;
  10458. }
  10459. /**
  10460. * Translate the 3D object by a distance along its X-axis in local space.
  10461. *
  10462. * @param {number} distance - The distance in world units.
  10463. * @return {Object3D} A reference to this instance.
  10464. */
  10465. translateX( distance ) {
  10466. return this.translateOnAxis( _xAxis, distance );
  10467. }
  10468. /**
  10469. * Translate the 3D object by a distance along its Y-axis in local space.
  10470. *
  10471. * @param {number} distance - The distance in world units.
  10472. * @return {Object3D} A reference to this instance.
  10473. */
  10474. translateY( distance ) {
  10475. return this.translateOnAxis( _yAxis, distance );
  10476. }
  10477. /**
  10478. * Translate the 3D object by a distance along its Z-axis in local space.
  10479. *
  10480. * @param {number} distance - The distance in world units.
  10481. * @return {Object3D} A reference to this instance.
  10482. */
  10483. translateZ( distance ) {
  10484. return this.translateOnAxis( _zAxis, distance );
  10485. }
  10486. /**
  10487. * Converts the given vector from this 3D object's local space to world space.
  10488. *
  10489. * @param {Vector3} vector - The vector to convert.
  10490. * @return {Vector3} The converted vector.
  10491. */
  10492. localToWorld( vector ) {
  10493. this.updateWorldMatrix( true, false );
  10494. return vector.applyMatrix4( this.matrixWorld );
  10495. }
  10496. /**
  10497. * Converts the given vector from this 3D object's word space to local space.
  10498. *
  10499. * @param {Vector3} vector - The vector to convert.
  10500. * @return {Vector3} The converted vector.
  10501. */
  10502. worldToLocal( vector ) {
  10503. this.updateWorldMatrix( true, false );
  10504. return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() );
  10505. }
  10506. /**
  10507. * Rotates the object to face a point in world space.
  10508. *
  10509. * This method does not support objects having non-uniformly-scaled parent(s).
  10510. *
  10511. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  10512. * @param {number} [y] - The y coordinate in world space.
  10513. * @param {number} [z] - The z coordinate in world space.
  10514. */
  10515. lookAt( x, y, z ) {
  10516. // This method does not support objects having non-uniformly-scaled parent(s)
  10517. if ( x.isVector3 ) {
  10518. _target.copy( x );
  10519. } else {
  10520. _target.set( x, y, z );
  10521. }
  10522. const parent = this.parent;
  10523. this.updateWorldMatrix( true, false );
  10524. _position$3.setFromMatrixPosition( this.matrixWorld );
  10525. if ( this.isCamera || this.isLight ) {
  10526. _m1$3.lookAt( _position$3, _target, this.up );
  10527. } else {
  10528. _m1$3.lookAt( _target, _position$3, this.up );
  10529. }
  10530. this.quaternion.setFromRotationMatrix( _m1$3 );
  10531. if ( parent ) {
  10532. _m1$3.extractRotation( parent.matrixWorld );
  10533. _q1.setFromRotationMatrix( _m1$3 );
  10534. this.quaternion.premultiply( _q1.invert() );
  10535. }
  10536. }
  10537. /**
  10538. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  10539. * objects may be added. Any current parent on an object passed in here will be
  10540. * removed, since an object can have at most one parent.
  10541. *
  10542. * @fires Object3D#added
  10543. * @fires Object3D#childadded
  10544. * @param {Object3D} object - The 3D object to add.
  10545. * @return {Object3D} A reference to this instance.
  10546. */
  10547. add( object ) {
  10548. if ( arguments.length > 1 ) {
  10549. for ( let i = 0; i < arguments.length; i ++ ) {
  10550. this.add( arguments[ i ] );
  10551. }
  10552. return this;
  10553. }
  10554. if ( object === this ) {
  10555. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  10556. return this;
  10557. }
  10558. if ( object && object.isObject3D ) {
  10559. object.removeFromParent();
  10560. object.parent = this;
  10561. this.children.push( object );
  10562. object.dispatchEvent( _addedEvent );
  10563. _childaddedEvent.child = object;
  10564. this.dispatchEvent( _childaddedEvent );
  10565. _childaddedEvent.child = null;
  10566. } else {
  10567. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  10568. }
  10569. return this;
  10570. }
  10571. /**
  10572. * Removes the given 3D object as child from this 3D object.
  10573. * An arbitrary number of objects may be removed.
  10574. *
  10575. * @fires Object3D#removed
  10576. * @fires Object3D#childremoved
  10577. * @param {Object3D} object - The 3D object to remove.
  10578. * @return {Object3D} A reference to this instance.
  10579. */
  10580. remove( object ) {
  10581. if ( arguments.length > 1 ) {
  10582. for ( let i = 0; i < arguments.length; i ++ ) {
  10583. this.remove( arguments[ i ] );
  10584. }
  10585. return this;
  10586. }
  10587. const index = this.children.indexOf( object );
  10588. if ( index !== -1 ) {
  10589. object.parent = null;
  10590. this.children.splice( index, 1 );
  10591. object.dispatchEvent( _removedEvent );
  10592. _childremovedEvent.child = object;
  10593. this.dispatchEvent( _childremovedEvent );
  10594. _childremovedEvent.child = null;
  10595. }
  10596. return this;
  10597. }
  10598. /**
  10599. * Removes this 3D object from its current parent.
  10600. *
  10601. * @fires Object3D#removed
  10602. * @fires Object3D#childremoved
  10603. * @return {Object3D} A reference to this instance.
  10604. */
  10605. removeFromParent() {
  10606. const parent = this.parent;
  10607. if ( parent !== null ) {
  10608. parent.remove( this );
  10609. }
  10610. return this;
  10611. }
  10612. /**
  10613. * Removes all child objects.
  10614. *
  10615. * @fires Object3D#removed
  10616. * @fires Object3D#childremoved
  10617. * @return {Object3D} A reference to this instance.
  10618. */
  10619. clear() {
  10620. return this.remove( ... this.children );
  10621. }
  10622. /**
  10623. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  10624. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  10625. *
  10626. * @fires Object3D#added
  10627. * @fires Object3D#childadded
  10628. * @param {Object3D} object - The 3D object to attach.
  10629. * @return {Object3D} A reference to this instance.
  10630. */
  10631. attach( object ) {
  10632. // adds object as a child of this, while maintaining the object's world transform
  10633. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  10634. this.updateWorldMatrix( true, false );
  10635. _m1$3.copy( this.matrixWorld ).invert();
  10636. if ( object.parent !== null ) {
  10637. object.parent.updateWorldMatrix( true, false );
  10638. _m1$3.multiply( object.parent.matrixWorld );
  10639. }
  10640. object.applyMatrix4( _m1$3 );
  10641. object.removeFromParent();
  10642. object.parent = this;
  10643. this.children.push( object );
  10644. object.updateWorldMatrix( false, true );
  10645. object.dispatchEvent( _addedEvent );
  10646. _childaddedEvent.child = object;
  10647. this.dispatchEvent( _childaddedEvent );
  10648. _childaddedEvent.child = null;
  10649. return this;
  10650. }
  10651. /**
  10652. * Searches through the 3D object and its children, starting with the 3D object
  10653. * itself, and returns the first with a matching ID.
  10654. *
  10655. * @param {number} id - The id.
  10656. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10657. */
  10658. getObjectById( id ) {
  10659. return this.getObjectByProperty( 'id', id );
  10660. }
  10661. /**
  10662. * Searches through the 3D object and its children, starting with the 3D object
  10663. * itself, and returns the first with a matching name.
  10664. *
  10665. * @param {string} name - The name.
  10666. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10667. */
  10668. getObjectByName( name ) {
  10669. return this.getObjectByProperty( 'name', name );
  10670. }
  10671. /**
  10672. * Searches through the 3D object and its children, starting with the 3D object
  10673. * itself, and returns the first with a matching property value.
  10674. *
  10675. * @param {string} name - The name of the property.
  10676. * @param {any} value - The value.
  10677. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10678. */
  10679. getObjectByProperty( name, value ) {
  10680. if ( this[ name ] === value ) return this;
  10681. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  10682. const child = this.children[ i ];
  10683. const object = child.getObjectByProperty( name, value );
  10684. if ( object !== undefined ) {
  10685. return object;
  10686. }
  10687. }
  10688. return undefined;
  10689. }
  10690. /**
  10691. * Searches through the 3D object and its children, starting with the 3D object
  10692. * itself, and returns all 3D objects with a matching property value.
  10693. *
  10694. * @param {string} name - The name of the property.
  10695. * @param {any} value - The value.
  10696. * @param {Array<Object3D>} result - The method stores the result in this array.
  10697. * @return {Array<Object3D>} The found 3D objects.
  10698. */
  10699. getObjectsByProperty( name, value, result = [] ) {
  10700. if ( this[ name ] === value ) result.push( this );
  10701. const children = this.children;
  10702. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10703. children[ i ].getObjectsByProperty( name, value, result );
  10704. }
  10705. return result;
  10706. }
  10707. /**
  10708. * Returns a vector representing the position of the 3D object in world space.
  10709. *
  10710. * @param {Vector3} target - The target vector the result is stored to.
  10711. * @return {Vector3} The 3D object's position in world space.
  10712. */
  10713. getWorldPosition( target ) {
  10714. this.updateWorldMatrix( true, false );
  10715. return target.setFromMatrixPosition( this.matrixWorld );
  10716. }
  10717. /**
  10718. * Returns a Quaternion representing the position of the 3D object in world space.
  10719. *
  10720. * @param {Quaternion} target - The target Quaternion the result is stored to.
  10721. * @return {Quaternion} The 3D object's rotation in world space.
  10722. */
  10723. getWorldQuaternion( target ) {
  10724. this.updateWorldMatrix( true, false );
  10725. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  10726. return target;
  10727. }
  10728. /**
  10729. * Returns a vector representing the scale of the 3D object in world space.
  10730. *
  10731. * @param {Vector3} target - The target vector the result is stored to.
  10732. * @return {Vector3} The 3D object's scale in world space.
  10733. */
  10734. getWorldScale( target ) {
  10735. this.updateWorldMatrix( true, false );
  10736. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  10737. return target;
  10738. }
  10739. /**
  10740. * Returns a vector representing the ("look") direction of the 3D object in world space.
  10741. *
  10742. * @param {Vector3} target - The target vector the result is stored to.
  10743. * @return {Vector3} The 3D object's direction in world space.
  10744. */
  10745. getWorldDirection( target ) {
  10746. this.updateWorldMatrix( true, false );
  10747. const e = this.matrixWorld.elements;
  10748. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  10749. }
  10750. /**
  10751. * Abstract method to get intersections between a casted ray and this
  10752. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  10753. * implement this method in order to use raycasting.
  10754. *
  10755. * @abstract
  10756. * @param {Raycaster} raycaster - The raycaster.
  10757. * @param {Array<Object>} intersects - An array holding the result of the method.
  10758. */
  10759. raycast( /* raycaster, intersects */ ) {}
  10760. /**
  10761. * Executes the callback on this 3D object and all descendants.
  10762. *
  10763. * Note: Modifying the scene graph inside the callback is discouraged.
  10764. *
  10765. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10766. */
  10767. traverse( callback ) {
  10768. callback( this );
  10769. const children = this.children;
  10770. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10771. children[ i ].traverse( callback );
  10772. }
  10773. }
  10774. /**
  10775. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  10776. * Descendants of invisible 3D objects are not traversed.
  10777. *
  10778. * Note: Modifying the scene graph inside the callback is discouraged.
  10779. *
  10780. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10781. */
  10782. traverseVisible( callback ) {
  10783. if ( this.visible === false ) return;
  10784. callback( this );
  10785. const children = this.children;
  10786. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10787. children[ i ].traverseVisible( callback );
  10788. }
  10789. }
  10790. /**
  10791. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  10792. *
  10793. * Note: Modifying the scene graph inside the callback is discouraged.
  10794. *
  10795. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10796. */
  10797. traverseAncestors( callback ) {
  10798. const parent = this.parent;
  10799. if ( parent !== null ) {
  10800. callback( parent );
  10801. parent.traverseAncestors( callback );
  10802. }
  10803. }
  10804. /**
  10805. * Updates the transformation matrix in local space by computing it from the current
  10806. * position, rotation and scale values.
  10807. */
  10808. updateMatrix() {
  10809. this.matrix.compose( this.position, this.quaternion, this.scale );
  10810. this.matrixWorldNeedsUpdate = true;
  10811. }
  10812. /**
  10813. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  10814. *
  10815. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  10816. * local space. The computation of the local and world matrix can be controlled with the
  10817. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  10818. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  10819. *
  10820. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  10821. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  10822. */
  10823. updateMatrixWorld( force ) {
  10824. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10825. if ( this.matrixWorldNeedsUpdate || force ) {
  10826. if ( this.matrixWorldAutoUpdate === true ) {
  10827. if ( this.parent === null ) {
  10828. this.matrixWorld.copy( this.matrix );
  10829. } else {
  10830. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10831. }
  10832. }
  10833. this.matrixWorldNeedsUpdate = false;
  10834. force = true;
  10835. }
  10836. // make sure descendants are updated if required
  10837. const children = this.children;
  10838. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10839. const child = children[ i ];
  10840. child.updateMatrixWorld( force );
  10841. }
  10842. }
  10843. /**
  10844. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  10845. * update of ancestor and descendant nodes.
  10846. *
  10847. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  10848. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  10849. */
  10850. updateWorldMatrix( updateParents, updateChildren ) {
  10851. const parent = this.parent;
  10852. if ( updateParents === true && parent !== null ) {
  10853. parent.updateWorldMatrix( true, false );
  10854. }
  10855. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10856. if ( this.matrixWorldAutoUpdate === true ) {
  10857. if ( this.parent === null ) {
  10858. this.matrixWorld.copy( this.matrix );
  10859. } else {
  10860. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10861. }
  10862. }
  10863. // make sure descendants are updated
  10864. if ( updateChildren === true ) {
  10865. const children = this.children;
  10866. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10867. const child = children[ i ];
  10868. child.updateWorldMatrix( false, true );
  10869. }
  10870. }
  10871. }
  10872. /**
  10873. * Serializes the 3D object into JSON.
  10874. *
  10875. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  10876. * @return {Object} A JSON object representing the serialized 3D object.
  10877. * @see {@link ObjectLoader#parse}
  10878. */
  10879. toJSON( meta ) {
  10880. // meta is a string when called from JSON.stringify
  10881. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  10882. const output = {};
  10883. // meta is a hash used to collect geometries, materials.
  10884. // not providing it implies that this is the root object
  10885. // being serialized.
  10886. if ( isRootObject ) {
  10887. // initialize meta obj
  10888. meta = {
  10889. geometries: {},
  10890. materials: {},
  10891. textures: {},
  10892. images: {},
  10893. shapes: {},
  10894. skeletons: {},
  10895. animations: {},
  10896. nodes: {}
  10897. };
  10898. output.metadata = {
  10899. version: 4.7,
  10900. type: 'Object',
  10901. generator: 'Object3D.toJSON'
  10902. };
  10903. }
  10904. // standard Object3D serialization
  10905. const object = {};
  10906. object.uuid = this.uuid;
  10907. object.type = this.type;
  10908. if ( this.name !== '' ) object.name = this.name;
  10909. if ( this.castShadow === true ) object.castShadow = true;
  10910. if ( this.receiveShadow === true ) object.receiveShadow = true;
  10911. if ( this.visible === false ) object.visible = false;
  10912. if ( this.frustumCulled === false ) object.frustumCulled = false;
  10913. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  10914. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  10915. object.layers = this.layers.mask;
  10916. object.matrix = this.matrix.toArray();
  10917. object.up = this.up.toArray();
  10918. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  10919. // object specific properties
  10920. if ( this.isInstancedMesh ) {
  10921. object.type = 'InstancedMesh';
  10922. object.count = this.count;
  10923. object.instanceMatrix = this.instanceMatrix.toJSON();
  10924. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  10925. }
  10926. if ( this.isBatchedMesh ) {
  10927. object.type = 'BatchedMesh';
  10928. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  10929. object.sortObjects = this.sortObjects;
  10930. object.drawRanges = this._drawRanges;
  10931. object.reservedRanges = this._reservedRanges;
  10932. object.geometryInfo = this._geometryInfo.map( info => ( {
  10933. ...info,
  10934. boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
  10935. boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
  10936. } ) );
  10937. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  10938. object.availableInstanceIds = this._availableInstanceIds.slice();
  10939. object.availableGeometryIds = this._availableGeometryIds.slice();
  10940. object.nextIndexStart = this._nextIndexStart;
  10941. object.nextVertexStart = this._nextVertexStart;
  10942. object.geometryCount = this._geometryCount;
  10943. object.maxInstanceCount = this._maxInstanceCount;
  10944. object.maxVertexCount = this._maxVertexCount;
  10945. object.maxIndexCount = this._maxIndexCount;
  10946. object.geometryInitialized = this._geometryInitialized;
  10947. object.matricesTexture = this._matricesTexture.toJSON( meta );
  10948. object.indirectTexture = this._indirectTexture.toJSON( meta );
  10949. if ( this._colorsTexture !== null ) {
  10950. object.colorsTexture = this._colorsTexture.toJSON( meta );
  10951. }
  10952. if ( this.boundingSphere !== null ) {
  10953. object.boundingSphere = this.boundingSphere.toJSON();
  10954. }
  10955. if ( this.boundingBox !== null ) {
  10956. object.boundingBox = this.boundingBox.toJSON();
  10957. }
  10958. }
  10959. //
  10960. function serialize( library, element ) {
  10961. if ( library[ element.uuid ] === undefined ) {
  10962. library[ element.uuid ] = element.toJSON( meta );
  10963. }
  10964. return element.uuid;
  10965. }
  10966. if ( this.isScene ) {
  10967. if ( this.background ) {
  10968. if ( this.background.isColor ) {
  10969. object.background = this.background.toJSON();
  10970. } else if ( this.background.isTexture ) {
  10971. object.background = this.background.toJSON( meta ).uuid;
  10972. }
  10973. }
  10974. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  10975. object.environment = this.environment.toJSON( meta ).uuid;
  10976. }
  10977. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  10978. object.geometry = serialize( meta.geometries, this.geometry );
  10979. const parameters = this.geometry.parameters;
  10980. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  10981. const shapes = parameters.shapes;
  10982. if ( Array.isArray( shapes ) ) {
  10983. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  10984. const shape = shapes[ i ];
  10985. serialize( meta.shapes, shape );
  10986. }
  10987. } else {
  10988. serialize( meta.shapes, shapes );
  10989. }
  10990. }
  10991. }
  10992. if ( this.isSkinnedMesh ) {
  10993. object.bindMode = this.bindMode;
  10994. object.bindMatrix = this.bindMatrix.toArray();
  10995. if ( this.skeleton !== undefined ) {
  10996. serialize( meta.skeletons, this.skeleton );
  10997. object.skeleton = this.skeleton.uuid;
  10998. }
  10999. }
  11000. if ( this.material !== undefined ) {
  11001. if ( Array.isArray( this.material ) ) {
  11002. const uuids = [];
  11003. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  11004. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  11005. }
  11006. object.material = uuids;
  11007. } else {
  11008. object.material = serialize( meta.materials, this.material );
  11009. }
  11010. }
  11011. //
  11012. if ( this.children.length > 0 ) {
  11013. object.children = [];
  11014. for ( let i = 0; i < this.children.length; i ++ ) {
  11015. object.children.push( this.children[ i ].toJSON( meta ).object );
  11016. }
  11017. }
  11018. //
  11019. if ( this.animations.length > 0 ) {
  11020. object.animations = [];
  11021. for ( let i = 0; i < this.animations.length; i ++ ) {
  11022. const animation = this.animations[ i ];
  11023. object.animations.push( serialize( meta.animations, animation ) );
  11024. }
  11025. }
  11026. if ( isRootObject ) {
  11027. const geometries = extractFromCache( meta.geometries );
  11028. const materials = extractFromCache( meta.materials );
  11029. const textures = extractFromCache( meta.textures );
  11030. const images = extractFromCache( meta.images );
  11031. const shapes = extractFromCache( meta.shapes );
  11032. const skeletons = extractFromCache( meta.skeletons );
  11033. const animations = extractFromCache( meta.animations );
  11034. const nodes = extractFromCache( meta.nodes );
  11035. if ( geometries.length > 0 ) output.geometries = geometries;
  11036. if ( materials.length > 0 ) output.materials = materials;
  11037. if ( textures.length > 0 ) output.textures = textures;
  11038. if ( images.length > 0 ) output.images = images;
  11039. if ( shapes.length > 0 ) output.shapes = shapes;
  11040. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  11041. if ( animations.length > 0 ) output.animations = animations;
  11042. if ( nodes.length > 0 ) output.nodes = nodes;
  11043. }
  11044. output.object = object;
  11045. return output;
  11046. // extract data from the cache hash
  11047. // remove metadata on each item
  11048. // and return as array
  11049. function extractFromCache( cache ) {
  11050. const values = [];
  11051. for ( const key in cache ) {
  11052. const data = cache[ key ];
  11053. delete data.metadata;
  11054. values.push( data );
  11055. }
  11056. return values;
  11057. }
  11058. }
  11059. /**
  11060. * Returns a new 3D object with copied values from this instance.
  11061. *
  11062. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  11063. * @return {Object3D} A clone of this instance.
  11064. */
  11065. clone( recursive ) {
  11066. return new this.constructor().copy( this, recursive );
  11067. }
  11068. /**
  11069. * Copies the values of the given 3D object to this instance.
  11070. *
  11071. * @param {Object3D} source - The 3D object to copy.
  11072. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  11073. * @return {Object3D} A reference to this instance.
  11074. */
  11075. copy( source, recursive = true ) {
  11076. this.name = source.name;
  11077. this.up.copy( source.up );
  11078. this.position.copy( source.position );
  11079. this.rotation.order = source.rotation.order;
  11080. this.quaternion.copy( source.quaternion );
  11081. this.scale.copy( source.scale );
  11082. this.matrix.copy( source.matrix );
  11083. this.matrixWorld.copy( source.matrixWorld );
  11084. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11085. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  11086. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  11087. this.layers.mask = source.layers.mask;
  11088. this.visible = source.visible;
  11089. this.castShadow = source.castShadow;
  11090. this.receiveShadow = source.receiveShadow;
  11091. this.frustumCulled = source.frustumCulled;
  11092. this.renderOrder = source.renderOrder;
  11093. this.animations = source.animations.slice();
  11094. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  11095. if ( recursive === true ) {
  11096. for ( let i = 0; i < source.children.length; i ++ ) {
  11097. const child = source.children[ i ];
  11098. this.add( child.clone() );
  11099. }
  11100. }
  11101. return this;
  11102. }
  11103. }
  11104. /**
  11105. * The default up direction for objects, also used as the default
  11106. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  11107. *
  11108. * @static
  11109. * @type {Vector3}
  11110. * @default (0,1,0)
  11111. */
  11112. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  11113. /**
  11114. * The default setting for {@link Object3D#matrixAutoUpdate} for
  11115. * newly created 3D objects.
  11116. *
  11117. * @static
  11118. * @type {boolean}
  11119. * @default true
  11120. */
  11121. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  11122. /**
  11123. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  11124. * newly created 3D objects.
  11125. *
  11126. * @static
  11127. * @type {boolean}
  11128. * @default true
  11129. */
  11130. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  11131. const _v0$2 = /*@__PURE__*/ new Vector3();
  11132. const _v1$3 = /*@__PURE__*/ new Vector3();
  11133. const _v2$2 = /*@__PURE__*/ new Vector3();
  11134. const _v3$2 = /*@__PURE__*/ new Vector3();
  11135. const _vab = /*@__PURE__*/ new Vector3();
  11136. const _vac = /*@__PURE__*/ new Vector3();
  11137. const _vbc = /*@__PURE__*/ new Vector3();
  11138. const _vap = /*@__PURE__*/ new Vector3();
  11139. const _vbp = /*@__PURE__*/ new Vector3();
  11140. const _vcp = /*@__PURE__*/ new Vector3();
  11141. const _v40 = /*@__PURE__*/ new Vector4();
  11142. const _v41 = /*@__PURE__*/ new Vector4();
  11143. const _v42 = /*@__PURE__*/ new Vector4();
  11144. /**
  11145. * A geometric triangle as defined by three vectors representing its three corners.
  11146. */
  11147. class Triangle {
  11148. /**
  11149. * Constructs a new triangle.
  11150. *
  11151. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11152. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11153. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11154. */
  11155. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11156. /**
  11157. * The first corner of the triangle.
  11158. *
  11159. * @type {Vector3}
  11160. */
  11161. this.a = a;
  11162. /**
  11163. * The second corner of the triangle.
  11164. *
  11165. * @type {Vector3}
  11166. */
  11167. this.b = b;
  11168. /**
  11169. * The third corner of the triangle.
  11170. *
  11171. * @type {Vector3}
  11172. */
  11173. this.c = c;
  11174. }
  11175. /**
  11176. * Computes the normal vector of a triangle.
  11177. *
  11178. * @param {Vector3} a - The first corner of the triangle.
  11179. * @param {Vector3} b - The second corner of the triangle.
  11180. * @param {Vector3} c - The third corner of the triangle.
  11181. * @param {Vector3} target - The target vector that is used to store the method's result.
  11182. * @return {Vector3} The triangle's normal.
  11183. */
  11184. static getNormal( a, b, c, target ) {
  11185. target.subVectors( c, b );
  11186. _v0$2.subVectors( a, b );
  11187. target.cross( _v0$2 );
  11188. const targetLengthSq = target.lengthSq();
  11189. if ( targetLengthSq > 0 ) {
  11190. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11191. }
  11192. return target.set( 0, 0, 0 );
  11193. }
  11194. /**
  11195. * Computes a barycentric coordinates from the given vector.
  11196. * Returns `null` if the triangle is degenerate.
  11197. *
  11198. * @param {Vector3} point - A point in 3D space.
  11199. * @param {Vector3} a - The first corner of the triangle.
  11200. * @param {Vector3} b - The second corner of the triangle.
  11201. * @param {Vector3} c - The third corner of the triangle.
  11202. * @param {Vector3} target - The target vector that is used to store the method's result.
  11203. * @return {?Vector3} The barycentric coordinates for the given point
  11204. */
  11205. static getBarycoord( point, a, b, c, target ) {
  11206. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11207. _v0$2.subVectors( c, a );
  11208. _v1$3.subVectors( b, a );
  11209. _v2$2.subVectors( point, a );
  11210. const dot00 = _v0$2.dot( _v0$2 );
  11211. const dot01 = _v0$2.dot( _v1$3 );
  11212. const dot02 = _v0$2.dot( _v2$2 );
  11213. const dot11 = _v1$3.dot( _v1$3 );
  11214. const dot12 = _v1$3.dot( _v2$2 );
  11215. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11216. // collinear or singular triangle
  11217. if ( denom === 0 ) {
  11218. target.set( 0, 0, 0 );
  11219. return null;
  11220. }
  11221. const invDenom = 1 / denom;
  11222. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11223. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11224. // barycentric coordinates must always sum to 1
  11225. return target.set( 1 - u - v, v, u );
  11226. }
  11227. /**
  11228. * Returns `true` if the given point, when projected onto the plane of the
  11229. * triangle, lies within the triangle.
  11230. *
  11231. * @param {Vector3} point - The point in 3D space to test.
  11232. * @param {Vector3} a - The first corner of the triangle.
  11233. * @param {Vector3} b - The second corner of the triangle.
  11234. * @param {Vector3} c - The third corner of the triangle.
  11235. * @return {boolean} Whether the given point, when projected onto the plane of the
  11236. * triangle, lies within the triangle or not.
  11237. */
  11238. static containsPoint( point, a, b, c ) {
  11239. // if the triangle is degenerate then we can't contain a point
  11240. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11241. return false;
  11242. }
  11243. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11244. }
  11245. /**
  11246. * Computes the value barycentrically interpolated for the given point on the
  11247. * triangle. Returns `null` if the triangle is degenerate.
  11248. *
  11249. * @param {Vector3} point - Position of interpolated point.
  11250. * @param {Vector3} p1 - The first corner of the triangle.
  11251. * @param {Vector3} p2 - The second corner of the triangle.
  11252. * @param {Vector3} p3 - The third corner of the triangle.
  11253. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11254. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11255. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11256. * @param {Vector3} target - The target vector that is used to store the method's result.
  11257. * @return {?Vector3} The interpolated value.
  11258. */
  11259. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11260. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11261. target.x = 0;
  11262. target.y = 0;
  11263. if ( 'z' in target ) target.z = 0;
  11264. if ( 'w' in target ) target.w = 0;
  11265. return null;
  11266. }
  11267. target.setScalar( 0 );
  11268. target.addScaledVector( v1, _v3$2.x );
  11269. target.addScaledVector( v2, _v3$2.y );
  11270. target.addScaledVector( v3, _v3$2.z );
  11271. return target;
  11272. }
  11273. /**
  11274. * Computes the value barycentrically interpolated for the given attribute and indices.
  11275. *
  11276. * @param {BufferAttribute} attr - The attribute to interpolate.
  11277. * @param {number} i1 - Index of first vertex.
  11278. * @param {number} i2 - Index of second vertex.
  11279. * @param {number} i3 - Index of third vertex.
  11280. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11281. * @param {Vector3} target - The target vector that is used to store the method's result.
  11282. * @return {Vector3} The interpolated attribute value.
  11283. */
  11284. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11285. _v40.setScalar( 0 );
  11286. _v41.setScalar( 0 );
  11287. _v42.setScalar( 0 );
  11288. _v40.fromBufferAttribute( attr, i1 );
  11289. _v41.fromBufferAttribute( attr, i2 );
  11290. _v42.fromBufferAttribute( attr, i3 );
  11291. target.setScalar( 0 );
  11292. target.addScaledVector( _v40, barycoord.x );
  11293. target.addScaledVector( _v41, barycoord.y );
  11294. target.addScaledVector( _v42, barycoord.z );
  11295. return target;
  11296. }
  11297. /**
  11298. * Returns `true` if the triangle is oriented towards the given direction.
  11299. *
  11300. * @param {Vector3} a - The first corner of the triangle.
  11301. * @param {Vector3} b - The second corner of the triangle.
  11302. * @param {Vector3} c - The third corner of the triangle.
  11303. * @param {Vector3} direction - The (normalized) direction vector.
  11304. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11305. */
  11306. static isFrontFacing( a, b, c, direction ) {
  11307. _v0$2.subVectors( c, b );
  11308. _v1$3.subVectors( a, b );
  11309. // strictly front facing
  11310. return ( _v0$2.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  11311. }
  11312. /**
  11313. * Sets the triangle's vertices by copying the given values.
  11314. *
  11315. * @param {Vector3} a - The first corner of the triangle.
  11316. * @param {Vector3} b - The second corner of the triangle.
  11317. * @param {Vector3} c - The third corner of the triangle.
  11318. * @return {Triangle} A reference to this triangle.
  11319. */
  11320. set( a, b, c ) {
  11321. this.a.copy( a );
  11322. this.b.copy( b );
  11323. this.c.copy( c );
  11324. return this;
  11325. }
  11326. /**
  11327. * Sets the triangle's vertices by copying the given array values.
  11328. *
  11329. * @param {Array<Vector3>} points - An array with 3D points.
  11330. * @param {number} i0 - The array index representing the first corner of the triangle.
  11331. * @param {number} i1 - The array index representing the second corner of the triangle.
  11332. * @param {number} i2 - The array index representing the third corner of the triangle.
  11333. * @return {Triangle} A reference to this triangle.
  11334. */
  11335. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11336. this.a.copy( points[ i0 ] );
  11337. this.b.copy( points[ i1 ] );
  11338. this.c.copy( points[ i2 ] );
  11339. return this;
  11340. }
  11341. /**
  11342. * Sets the triangle's vertices by copying the given attribute values.
  11343. *
  11344. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11345. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11346. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11347. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11348. * @return {Triangle} A reference to this triangle.
  11349. */
  11350. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11351. this.a.fromBufferAttribute( attribute, i0 );
  11352. this.b.fromBufferAttribute( attribute, i1 );
  11353. this.c.fromBufferAttribute( attribute, i2 );
  11354. return this;
  11355. }
  11356. /**
  11357. * Returns a new triangle with copied values from this instance.
  11358. *
  11359. * @return {Triangle} A clone of this instance.
  11360. */
  11361. clone() {
  11362. return new this.constructor().copy( this );
  11363. }
  11364. /**
  11365. * Copies the values of the given triangle to this instance.
  11366. *
  11367. * @param {Triangle} triangle - The triangle to copy.
  11368. * @return {Triangle} A reference to this triangle.
  11369. */
  11370. copy( triangle ) {
  11371. this.a.copy( triangle.a );
  11372. this.b.copy( triangle.b );
  11373. this.c.copy( triangle.c );
  11374. return this;
  11375. }
  11376. /**
  11377. * Computes the area of the triangle.
  11378. *
  11379. * @return {number} The triangle's area.
  11380. */
  11381. getArea() {
  11382. _v0$2.subVectors( this.c, this.b );
  11383. _v1$3.subVectors( this.a, this.b );
  11384. return _v0$2.cross( _v1$3 ).length() * 0.5;
  11385. }
  11386. /**
  11387. * Computes the midpoint of the triangle.
  11388. *
  11389. * @param {Vector3} target - The target vector that is used to store the method's result.
  11390. * @return {Vector3} The triangle's midpoint.
  11391. */
  11392. getMidpoint( target ) {
  11393. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11394. }
  11395. /**
  11396. * Computes the normal of the triangle.
  11397. *
  11398. * @param {Vector3} target - The target vector that is used to store the method's result.
  11399. * @return {Vector3} The triangle's normal.
  11400. */
  11401. getNormal( target ) {
  11402. return Triangle.getNormal( this.a, this.b, this.c, target );
  11403. }
  11404. /**
  11405. * Computes a plane the triangle lies within.
  11406. *
  11407. * @param {Plane} target - The target vector that is used to store the method's result.
  11408. * @return {Plane} The plane the triangle lies within.
  11409. */
  11410. getPlane( target ) {
  11411. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11412. }
  11413. /**
  11414. * Computes a barycentric coordinates from the given vector.
  11415. * Returns `null` if the triangle is degenerate.
  11416. *
  11417. * @param {Vector3} point - A point in 3D space.
  11418. * @param {Vector3} target - The target vector that is used to store the method's result.
  11419. * @return {?Vector3} The barycentric coordinates for the given point
  11420. */
  11421. getBarycoord( point, target ) {
  11422. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11423. }
  11424. /**
  11425. * Computes the value barycentrically interpolated for the given point on the
  11426. * triangle. Returns `null` if the triangle is degenerate.
  11427. *
  11428. * @param {Vector3} point - Position of interpolated point.
  11429. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11430. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11431. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11432. * @param {Vector3} target - The target vector that is used to store the method's result.
  11433. * @return {?Vector3} The interpolated value.
  11434. */
  11435. getInterpolation( point, v1, v2, v3, target ) {
  11436. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11437. }
  11438. /**
  11439. * Returns `true` if the given point, when projected onto the plane of the
  11440. * triangle, lies within the triangle.
  11441. *
  11442. * @param {Vector3} point - The point in 3D space to test.
  11443. * @return {boolean} Whether the given point, when projected onto the plane of the
  11444. * triangle, lies within the triangle or not.
  11445. */
  11446. containsPoint( point ) {
  11447. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11448. }
  11449. /**
  11450. * Returns `true` if the triangle is oriented towards the given direction.
  11451. *
  11452. * @param {Vector3} direction - The (normalized) direction vector.
  11453. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11454. */
  11455. isFrontFacing( direction ) {
  11456. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11457. }
  11458. /**
  11459. * Returns `true` if this triangle intersects with the given box.
  11460. *
  11461. * @param {Box3} box - The box to intersect.
  11462. * @return {boolean} Whether this triangle intersects with the given box or not.
  11463. */
  11464. intersectsBox( box ) {
  11465. return box.intersectsTriangle( this );
  11466. }
  11467. /**
  11468. * Returns the closest point on the triangle to the given point.
  11469. *
  11470. * @param {Vector3} p - The point to compute the closest point for.
  11471. * @param {Vector3} target - The target vector that is used to store the method's result.
  11472. * @return {Vector3} The closest point on the triangle.
  11473. */
  11474. closestPointToPoint( p, target ) {
  11475. const a = this.a, b = this.b, c = this.c;
  11476. let v, w;
  11477. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11478. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11479. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11480. // basically, we're distinguishing which of the voronoi regions of the triangle
  11481. // the point lies in with the minimum amount of redundant computation.
  11482. _vab.subVectors( b, a );
  11483. _vac.subVectors( c, a );
  11484. _vap.subVectors( p, a );
  11485. const d1 = _vab.dot( _vap );
  11486. const d2 = _vac.dot( _vap );
  11487. if ( d1 <= 0 && d2 <= 0 ) {
  11488. // vertex region of A; barycentric coords (1, 0, 0)
  11489. return target.copy( a );
  11490. }
  11491. _vbp.subVectors( p, b );
  11492. const d3 = _vab.dot( _vbp );
  11493. const d4 = _vac.dot( _vbp );
  11494. if ( d3 >= 0 && d4 <= d3 ) {
  11495. // vertex region of B; barycentric coords (0, 1, 0)
  11496. return target.copy( b );
  11497. }
  11498. const vc = d1 * d4 - d3 * d2;
  11499. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11500. v = d1 / ( d1 - d3 );
  11501. // edge region of AB; barycentric coords (1-v, v, 0)
  11502. return target.copy( a ).addScaledVector( _vab, v );
  11503. }
  11504. _vcp.subVectors( p, c );
  11505. const d5 = _vab.dot( _vcp );
  11506. const d6 = _vac.dot( _vcp );
  11507. if ( d6 >= 0 && d5 <= d6 ) {
  11508. // vertex region of C; barycentric coords (0, 0, 1)
  11509. return target.copy( c );
  11510. }
  11511. const vb = d5 * d2 - d1 * d6;
  11512. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11513. w = d2 / ( d2 - d6 );
  11514. // edge region of AC; barycentric coords (1-w, 0, w)
  11515. return target.copy( a ).addScaledVector( _vac, w );
  11516. }
  11517. const va = d3 * d6 - d5 * d4;
  11518. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11519. _vbc.subVectors( c, b );
  11520. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11521. // edge region of BC; barycentric coords (0, 1-w, w)
  11522. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11523. }
  11524. // face region
  11525. const denom = 1 / ( va + vb + vc );
  11526. // u = va * denom
  11527. v = vb * denom;
  11528. w = vc * denom;
  11529. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11530. }
  11531. /**
  11532. * Returns `true` if this triangle is equal with the given one.
  11533. *
  11534. * @param {Triangle} triangle - The triangle to test for equality.
  11535. * @return {boolean} Whether this triangle is equal with the given one.
  11536. */
  11537. equals( triangle ) {
  11538. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11539. }
  11540. }
  11541. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  11542. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  11543. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  11544. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  11545. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  11546. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  11547. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  11548. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  11549. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  11550. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  11551. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  11552. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  11553. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  11554. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  11555. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  11556. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  11557. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  11558. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  11559. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  11560. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  11561. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  11562. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  11563. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  11564. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  11565. const _hslA = { h: 0, s: 0, l: 0 };
  11566. const _hslB = { h: 0, s: 0, l: 0 };
  11567. function hue2rgb( p, q, t ) {
  11568. if ( t < 0 ) t += 1;
  11569. if ( t > 1 ) t -= 1;
  11570. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  11571. if ( t < 1 / 2 ) return q;
  11572. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  11573. return p;
  11574. }
  11575. /**
  11576. * A Color instance is represented by RGB components in the linear <i>working
  11577. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  11578. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  11579. * strings) are converted to the working color space automatically.
  11580. *
  11581. * ```js
  11582. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  11583. * const color = new THREE.Color().setHex( 0x112233 );
  11584. * ```
  11585. * Source color spaces may be specified explicitly, to ensure correct conversions.
  11586. * ```js
  11587. * // assumed already LinearSRGBColorSpace; no conversion
  11588. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  11589. *
  11590. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  11591. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  11592. * ```
  11593. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  11594. * see <i>Color management</i>. Iterating through a Color instance will yield
  11595. * its components (r, g, b) in the corresponding order. A Color can be initialised
  11596. * in any of the following ways:
  11597. * ```js
  11598. * //empty constructor - will default white
  11599. * const color1 = new THREE.Color();
  11600. *
  11601. * //Hexadecimal color (recommended)
  11602. * const color2 = new THREE.Color( 0xff0000 );
  11603. *
  11604. * //RGB string
  11605. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  11606. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  11607. *
  11608. * //X11 color name - all 140 color names are supported.
  11609. * //Note the lack of CamelCase in the name
  11610. * const color5 = new THREE.Color( 'skyblue' );
  11611. * //HSL string
  11612. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  11613. *
  11614. * //Separate RGB values between 0 and 1
  11615. * const color7 = new THREE.Color( 1, 0, 0 );
  11616. * ```
  11617. */
  11618. class Color {
  11619. /**
  11620. * Constructs a new color.
  11621. *
  11622. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  11623. * and that method is used throughout the rest of the documentation.
  11624. *
  11625. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11626. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11627. * @param {number} [g] - The green component.
  11628. * @param {number} [b] - The blue component.
  11629. */
  11630. constructor( r, g, b ) {
  11631. /**
  11632. * This flag can be used for type testing.
  11633. *
  11634. * @type {boolean}
  11635. * @readonly
  11636. * @default true
  11637. */
  11638. this.isColor = true;
  11639. /**
  11640. * The red component.
  11641. *
  11642. * @type {number}
  11643. * @default 1
  11644. */
  11645. this.r = 1;
  11646. /**
  11647. * The green component.
  11648. *
  11649. * @type {number}
  11650. * @default 1
  11651. */
  11652. this.g = 1;
  11653. /**
  11654. * The blue component.
  11655. *
  11656. * @type {number}
  11657. * @default 1
  11658. */
  11659. this.b = 1;
  11660. return this.set( r, g, b );
  11661. }
  11662. /**
  11663. * Sets the colors's components from the given values.
  11664. *
  11665. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11666. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11667. * @param {number} [g] - The green component.
  11668. * @param {number} [b] - The blue component.
  11669. * @return {Color} A reference to this color.
  11670. */
  11671. set( r, g, b ) {
  11672. if ( g === undefined && b === undefined ) {
  11673. // r is THREE.Color, hex or string
  11674. const value = r;
  11675. if ( value && value.isColor ) {
  11676. this.copy( value );
  11677. } else if ( typeof value === 'number' ) {
  11678. this.setHex( value );
  11679. } else if ( typeof value === 'string' ) {
  11680. this.setStyle( value );
  11681. }
  11682. } else {
  11683. this.setRGB( r, g, b );
  11684. }
  11685. return this;
  11686. }
  11687. /**
  11688. * Sets the colors's components to the given scalar value.
  11689. *
  11690. * @param {number} scalar - The scalar value.
  11691. * @return {Color} A reference to this color.
  11692. */
  11693. setScalar( scalar ) {
  11694. this.r = scalar;
  11695. this.g = scalar;
  11696. this.b = scalar;
  11697. return this;
  11698. }
  11699. /**
  11700. * Sets this color from a hexadecimal value.
  11701. *
  11702. * @param {number} hex - The hexadecimal value.
  11703. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11704. * @return {Color} A reference to this color.
  11705. */
  11706. setHex( hex, colorSpace = SRGBColorSpace ) {
  11707. hex = Math.floor( hex );
  11708. this.r = ( hex >> 16 & 255 ) / 255;
  11709. this.g = ( hex >> 8 & 255 ) / 255;
  11710. this.b = ( hex & 255 ) / 255;
  11711. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11712. return this;
  11713. }
  11714. /**
  11715. * Sets this color from RGB values.
  11716. *
  11717. * @param {number} r - Red channel value between `0.0` and `1.0`.
  11718. * @param {number} g - Green channel value between `0.0` and `1.0`.
  11719. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  11720. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11721. * @return {Color} A reference to this color.
  11722. */
  11723. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  11724. this.r = r;
  11725. this.g = g;
  11726. this.b = b;
  11727. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11728. return this;
  11729. }
  11730. /**
  11731. * Sets this color from RGB values.
  11732. *
  11733. * @param {number} h - Hue value between `0.0` and `1.0`.
  11734. * @param {number} s - Saturation value between `0.0` and `1.0`.
  11735. * @param {number} l - Lightness value between `0.0` and `1.0`.
  11736. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11737. * @return {Color} A reference to this color.
  11738. */
  11739. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  11740. // h,s,l ranges are in 0.0 - 1.0
  11741. h = euclideanModulo( h, 1 );
  11742. s = clamp( s, 0, 1 );
  11743. l = clamp( l, 0, 1 );
  11744. if ( s === 0 ) {
  11745. this.r = this.g = this.b = l;
  11746. } else {
  11747. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  11748. const q = ( 2 * l ) - p;
  11749. this.r = hue2rgb( q, p, h + 1 / 3 );
  11750. this.g = hue2rgb( q, p, h );
  11751. this.b = hue2rgb( q, p, h - 1 / 3 );
  11752. }
  11753. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11754. return this;
  11755. }
  11756. /**
  11757. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  11758. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  11759. * any [X11 color name]{@link https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart} -
  11760. * all 140 color names are supported).
  11761. *
  11762. * @param {string} style - Color as a CSS-style string.
  11763. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11764. * @return {Color} A reference to this color.
  11765. */
  11766. setStyle( style, colorSpace = SRGBColorSpace ) {
  11767. function handleAlpha( string ) {
  11768. if ( string === undefined ) return;
  11769. if ( parseFloat( string ) < 1 ) {
  11770. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  11771. }
  11772. }
  11773. let m;
  11774. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  11775. // rgb / hsl
  11776. let color;
  11777. const name = m[ 1 ];
  11778. const components = m[ 2 ];
  11779. switch ( name ) {
  11780. case 'rgb':
  11781. case 'rgba':
  11782. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11783. // rgb(255,0,0) rgba(255,0,0,0.5)
  11784. handleAlpha( color[ 4 ] );
  11785. return this.setRGB(
  11786. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  11787. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  11788. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  11789. colorSpace
  11790. );
  11791. }
  11792. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11793. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  11794. handleAlpha( color[ 4 ] );
  11795. return this.setRGB(
  11796. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  11797. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  11798. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  11799. colorSpace
  11800. );
  11801. }
  11802. break;
  11803. case 'hsl':
  11804. case 'hsla':
  11805. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11806. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  11807. handleAlpha( color[ 4 ] );
  11808. return this.setHSL(
  11809. parseFloat( color[ 1 ] ) / 360,
  11810. parseFloat( color[ 2 ] ) / 100,
  11811. parseFloat( color[ 3 ] ) / 100,
  11812. colorSpace
  11813. );
  11814. }
  11815. break;
  11816. default:
  11817. console.warn( 'THREE.Color: Unknown color model ' + style );
  11818. }
  11819. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  11820. // hex color
  11821. const hex = m[ 1 ];
  11822. const size = hex.length;
  11823. if ( size === 3 ) {
  11824. // #ff0
  11825. return this.setRGB(
  11826. parseInt( hex.charAt( 0 ), 16 ) / 15,
  11827. parseInt( hex.charAt( 1 ), 16 ) / 15,
  11828. parseInt( hex.charAt( 2 ), 16 ) / 15,
  11829. colorSpace
  11830. );
  11831. } else if ( size === 6 ) {
  11832. // #ff0000
  11833. return this.setHex( parseInt( hex, 16 ), colorSpace );
  11834. } else {
  11835. console.warn( 'THREE.Color: Invalid hex color ' + style );
  11836. }
  11837. } else if ( style && style.length > 0 ) {
  11838. return this.setColorName( style, colorSpace );
  11839. }
  11840. return this;
  11841. }
  11842. /**
  11843. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  11844. * you don't need the other CSS-style formats.
  11845. *
  11846. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  11847. * ```js
  11848. * Color.NAMES.aliceblue // returns 0xF0F8FF
  11849. * ```
  11850. *
  11851. * @param {string} style - The color name.
  11852. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11853. * @return {Color} A reference to this color.
  11854. */
  11855. setColorName( style, colorSpace = SRGBColorSpace ) {
  11856. // color keywords
  11857. const hex = _colorKeywords[ style.toLowerCase() ];
  11858. if ( hex !== undefined ) {
  11859. // red
  11860. this.setHex( hex, colorSpace );
  11861. } else {
  11862. // unknown color
  11863. console.warn( 'THREE.Color: Unknown color ' + style );
  11864. }
  11865. return this;
  11866. }
  11867. /**
  11868. * Returns a new color with copied values from this instance.
  11869. *
  11870. * @return {Color} A clone of this instance.
  11871. */
  11872. clone() {
  11873. return new this.constructor( this.r, this.g, this.b );
  11874. }
  11875. /**
  11876. * Copies the values of the given color to this instance.
  11877. *
  11878. * @param {Color} color - The color to copy.
  11879. * @return {Color} A reference to this color.
  11880. */
  11881. copy( color ) {
  11882. this.r = color.r;
  11883. this.g = color.g;
  11884. this.b = color.b;
  11885. return this;
  11886. }
  11887. /**
  11888. * Copies the given color into this color, and then converts this color from
  11889. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11890. *
  11891. * @param {Color} color - The color to copy/convert.
  11892. * @return {Color} A reference to this color.
  11893. */
  11894. copySRGBToLinear( color ) {
  11895. this.r = SRGBToLinear( color.r );
  11896. this.g = SRGBToLinear( color.g );
  11897. this.b = SRGBToLinear( color.b );
  11898. return this;
  11899. }
  11900. /**
  11901. * Copies the given color into this color, and then converts this color from
  11902. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11903. *
  11904. * @param {Color} color - The color to copy/convert.
  11905. * @return {Color} A reference to this color.
  11906. */
  11907. copyLinearToSRGB( color ) {
  11908. this.r = LinearToSRGB( color.r );
  11909. this.g = LinearToSRGB( color.g );
  11910. this.b = LinearToSRGB( color.b );
  11911. return this;
  11912. }
  11913. /**
  11914. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11915. *
  11916. * @return {Color} A reference to this color.
  11917. */
  11918. convertSRGBToLinear() {
  11919. this.copySRGBToLinear( this );
  11920. return this;
  11921. }
  11922. /**
  11923. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11924. *
  11925. * @return {Color} A reference to this color.
  11926. */
  11927. convertLinearToSRGB() {
  11928. this.copyLinearToSRGB( this );
  11929. return this;
  11930. }
  11931. /**
  11932. * Returns the hexadecimal value of this color.
  11933. *
  11934. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11935. * @return {number} The hexadecimal value.
  11936. */
  11937. getHex( colorSpace = SRGBColorSpace ) {
  11938. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  11939. 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 ) );
  11940. }
  11941. /**
  11942. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  11943. *
  11944. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11945. * @return {string} The hexadecimal value as a string.
  11946. */
  11947. getHexString( colorSpace = SRGBColorSpace ) {
  11948. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  11949. }
  11950. /**
  11951. * Converts the colors RGB values into the HSL format and stores them into the
  11952. * given target object.
  11953. *
  11954. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  11955. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11956. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  11957. */
  11958. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  11959. // h,s,l ranges are in 0.0 - 1.0
  11960. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  11961. const r = _color.r, g = _color.g, b = _color.b;
  11962. const max = Math.max( r, g, b );
  11963. const min = Math.min( r, g, b );
  11964. let hue, saturation;
  11965. const lightness = ( min + max ) / 2.0;
  11966. if ( min === max ) {
  11967. hue = 0;
  11968. saturation = 0;
  11969. } else {
  11970. const delta = max - min;
  11971. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  11972. switch ( max ) {
  11973. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  11974. case g: hue = ( b - r ) / delta + 2; break;
  11975. case b: hue = ( r - g ) / delta + 4; break;
  11976. }
  11977. hue /= 6;
  11978. }
  11979. target.h = hue;
  11980. target.s = saturation;
  11981. target.l = lightness;
  11982. return target;
  11983. }
  11984. /**
  11985. * Returns the RGB values of this color and stores them into the given target object.
  11986. *
  11987. * @param {Color} target - The target color that is used to store the method's result.
  11988. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11989. * @return {Color} The RGB representation of this color.
  11990. */
  11991. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  11992. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  11993. target.r = _color.r;
  11994. target.g = _color.g;
  11995. target.b = _color.b;
  11996. return target;
  11997. }
  11998. /**
  11999. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  12000. *
  12001. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12002. * @return {string} The CSS representation of this color.
  12003. */
  12004. getStyle( colorSpace = SRGBColorSpace ) {
  12005. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12006. const r = _color.r, g = _color.g, b = _color.b;
  12007. if ( colorSpace !== SRGBColorSpace ) {
  12008. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  12009. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  12010. }
  12011. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  12012. }
  12013. /**
  12014. * Adds the given HSL values to this color's values.
  12015. * Internally, this converts the color's RGB values to HSL, adds HSL
  12016. * and then converts the color back to RGB.
  12017. *
  12018. * @param {number} h - Hue value between `0.0` and `1.0`.
  12019. * @param {number} s - Saturation value between `0.0` and `1.0`.
  12020. * @param {number} l - Lightness value between `0.0` and `1.0`.
  12021. * @return {Color} A reference to this color.
  12022. */
  12023. offsetHSL( h, s, l ) {
  12024. this.getHSL( _hslA );
  12025. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  12026. }
  12027. /**
  12028. * Adds the RGB values of the given color to the RGB values of this color.
  12029. *
  12030. * @param {Color} color - The color to add.
  12031. * @return {Color} A reference to this color.
  12032. */
  12033. add( color ) {
  12034. this.r += color.r;
  12035. this.g += color.g;
  12036. this.b += color.b;
  12037. return this;
  12038. }
  12039. /**
  12040. * Adds the RGB values of the given colors and stores the result in this instance.
  12041. *
  12042. * @param {Color} color1 - The first color.
  12043. * @param {Color} color2 - The second color.
  12044. * @return {Color} A reference to this color.
  12045. */
  12046. addColors( color1, color2 ) {
  12047. this.r = color1.r + color2.r;
  12048. this.g = color1.g + color2.g;
  12049. this.b = color1.b + color2.b;
  12050. return this;
  12051. }
  12052. /**
  12053. * Adds the given scalar value to the RGB values of this color.
  12054. *
  12055. * @param {number} s - The scalar to add.
  12056. * @return {Color} A reference to this color.
  12057. */
  12058. addScalar( s ) {
  12059. this.r += s;
  12060. this.g += s;
  12061. this.b += s;
  12062. return this;
  12063. }
  12064. /**
  12065. * Subtracts the RGB values of the given color from the RGB values of this color.
  12066. *
  12067. * @param {Color} color - The color to subtract.
  12068. * @return {Color} A reference to this color.
  12069. */
  12070. sub( color ) {
  12071. this.r = Math.max( 0, this.r - color.r );
  12072. this.g = Math.max( 0, this.g - color.g );
  12073. this.b = Math.max( 0, this.b - color.b );
  12074. return this;
  12075. }
  12076. /**
  12077. * Multiplies the RGB values of the given color with the RGB values of this color.
  12078. *
  12079. * @param {Color} color - The color to multiply.
  12080. * @return {Color} A reference to this color.
  12081. */
  12082. multiply( color ) {
  12083. this.r *= color.r;
  12084. this.g *= color.g;
  12085. this.b *= color.b;
  12086. return this;
  12087. }
  12088. /**
  12089. * Multiplies the given scalar value with the RGB values of this color.
  12090. *
  12091. * @param {number} s - The scalar to multiply.
  12092. * @return {Color} A reference to this color.
  12093. */
  12094. multiplyScalar( s ) {
  12095. this.r *= s;
  12096. this.g *= s;
  12097. this.b *= s;
  12098. return this;
  12099. }
  12100. /**
  12101. * Linearly interpolates this color's RGB values toward the RGB values of the
  12102. * given color. The alpha argument can be thought of as the ratio between
  12103. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  12104. *
  12105. * @param {Color} color - The color to converge on.
  12106. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12107. * @return {Color} A reference to this color.
  12108. */
  12109. lerp( color, alpha ) {
  12110. this.r += ( color.r - this.r ) * alpha;
  12111. this.g += ( color.g - this.g ) * alpha;
  12112. this.b += ( color.b - this.b ) * alpha;
  12113. return this;
  12114. }
  12115. /**
  12116. * Linearly interpolates between the given colors and stores the result in this instance.
  12117. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  12118. * is the first and `1.0` is the second color.
  12119. *
  12120. * @param {Color} color1 - The first color.
  12121. * @param {Color} color2 - The second color.
  12122. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12123. * @return {Color} A reference to this color.
  12124. */
  12125. lerpColors( color1, color2, alpha ) {
  12126. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  12127. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  12128. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  12129. return this;
  12130. }
  12131. /**
  12132. * Linearly interpolates this color's HSL values toward the HSL values of the
  12133. * given color. It differs from {@link Color#lerp} by not interpolating straight
  12134. * from one color to the other, but instead going through all the hues in between
  12135. * those two colors. The alpha argument can be thought of as the ratio between
  12136. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  12137. *
  12138. * @param {Color} color - The color to converge on.
  12139. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12140. * @return {Color} A reference to this color.
  12141. */
  12142. lerpHSL( color, alpha ) {
  12143. this.getHSL( _hslA );
  12144. color.getHSL( _hslB );
  12145. const h = lerp( _hslA.h, _hslB.h, alpha );
  12146. const s = lerp( _hslA.s, _hslB.s, alpha );
  12147. const l = lerp( _hslA.l, _hslB.l, alpha );
  12148. this.setHSL( h, s, l );
  12149. return this;
  12150. }
  12151. /**
  12152. * Sets the color's RGB components from the given 3D vector.
  12153. *
  12154. * @param {Vector3} v - The vector to set.
  12155. * @return {Color} A reference to this color.
  12156. */
  12157. setFromVector3( v ) {
  12158. this.r = v.x;
  12159. this.g = v.y;
  12160. this.b = v.z;
  12161. return this;
  12162. }
  12163. /**
  12164. * Transforms this color with the given 3x3 matrix.
  12165. *
  12166. * @param {Matrix3} m - The matrix.
  12167. * @return {Color} A reference to this color.
  12168. */
  12169. applyMatrix3( m ) {
  12170. const r = this.r, g = this.g, b = this.b;
  12171. const e = m.elements;
  12172. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  12173. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  12174. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  12175. return this;
  12176. }
  12177. /**
  12178. * Returns `true` if this color is equal with the given one.
  12179. *
  12180. * @param {Color} c - The color to test for equality.
  12181. * @return {boolean} Whether this bounding color is equal with the given one.
  12182. */
  12183. equals( c ) {
  12184. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  12185. }
  12186. /**
  12187. * Sets this color's RGB components from the given array.
  12188. *
  12189. * @param {Array<number>} array - An array holding the RGB values.
  12190. * @param {number} [offset=0] - The offset into the array.
  12191. * @return {Color} A reference to this color.
  12192. */
  12193. fromArray( array, offset = 0 ) {
  12194. this.r = array[ offset ];
  12195. this.g = array[ offset + 1 ];
  12196. this.b = array[ offset + 2 ];
  12197. return this;
  12198. }
  12199. /**
  12200. * Writes the RGB components of this color to the given array. If no array is provided,
  12201. * the method returns a new instance.
  12202. *
  12203. * @param {Array<number>} [array=[]] - The target array holding the color components.
  12204. * @param {number} [offset=0] - Index of the first element in the array.
  12205. * @return {Array<number>} The color components.
  12206. */
  12207. toArray( array = [], offset = 0 ) {
  12208. array[ offset ] = this.r;
  12209. array[ offset + 1 ] = this.g;
  12210. array[ offset + 2 ] = this.b;
  12211. return array;
  12212. }
  12213. /**
  12214. * Sets the components of this color from the given buffer attribute.
  12215. *
  12216. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  12217. * @param {number} index - The index into the attribute.
  12218. * @return {Color} A reference to this color.
  12219. */
  12220. fromBufferAttribute( attribute, index ) {
  12221. this.r = attribute.getX( index );
  12222. this.g = attribute.getY( index );
  12223. this.b = attribute.getZ( index );
  12224. return this;
  12225. }
  12226. /**
  12227. * This methods defines the serialization result of this class. Returns the color
  12228. * as a hexadecimal value.
  12229. *
  12230. * @return {number} The hexadecimal value.
  12231. */
  12232. toJSON() {
  12233. return this.getHex();
  12234. }
  12235. *[ Symbol.iterator ]() {
  12236. yield this.r;
  12237. yield this.g;
  12238. yield this.b;
  12239. }
  12240. }
  12241. const _color = /*@__PURE__*/ new Color();
  12242. /**
  12243. * A dictionary with X11 color names.
  12244. *
  12245. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  12246. *
  12247. * @static
  12248. * @type {Object}
  12249. */
  12250. Color.NAMES = _colorKeywords;
  12251. let _materialId = 0;
  12252. /**
  12253. * Abstract base class for materials.
  12254. *
  12255. * Materials define the appearance of renderable 3D objects.
  12256. *
  12257. * @abstract
  12258. * @augments EventDispatcher
  12259. */
  12260. class Material extends EventDispatcher {
  12261. /**
  12262. * Constructs a new material.
  12263. */
  12264. constructor() {
  12265. super();
  12266. /**
  12267. * This flag can be used for type testing.
  12268. *
  12269. * @type {boolean}
  12270. * @readonly
  12271. * @default true
  12272. */
  12273. this.isMaterial = true;
  12274. /**
  12275. * The ID of the material.
  12276. *
  12277. * @name Material#id
  12278. * @type {number}
  12279. * @readonly
  12280. */
  12281. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  12282. /**
  12283. * The UUID of the material.
  12284. *
  12285. * @type {string}
  12286. * @readonly
  12287. */
  12288. this.uuid = generateUUID();
  12289. /**
  12290. * The name of the material.
  12291. *
  12292. * @type {string}
  12293. */
  12294. this.name = '';
  12295. /**
  12296. * The type property is used for detecting the object type
  12297. * in context of serialization/deserialization.
  12298. *
  12299. * @type {string}
  12300. * @readonly
  12301. */
  12302. this.type = 'Material';
  12303. /**
  12304. * Defines the blending type of the material.
  12305. *
  12306. * It must be set to `CustomBlending` if custom blending properties like
  12307. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  12308. * should have any effect.
  12309. *
  12310. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  12311. * @default NormalBlending
  12312. */
  12313. this.blending = NormalBlending;
  12314. /**
  12315. * Defines which side of faces will be rendered - front, back or both.
  12316. *
  12317. * @type {(FrontSide|BackSide|DoubleSide)}
  12318. * @default FrontSide
  12319. */
  12320. this.side = FrontSide;
  12321. /**
  12322. * If set to `true`, vertex colors should be used.
  12323. *
  12324. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  12325. * four (RGBA) component color buffer attribute is used.
  12326. *
  12327. * @type {boolean}
  12328. * @default false
  12329. */
  12330. this.vertexColors = false;
  12331. /**
  12332. * Defines how transparent the material is.
  12333. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  12334. *
  12335. * If the {@link Material#transparent} is not set to `true`,
  12336. * the material will remain fully opaque and this value will only affect its color.
  12337. *
  12338. * @type {number}
  12339. * @default 1
  12340. */
  12341. this.opacity = 1;
  12342. /**
  12343. * Defines whether this material is transparent. This has an effect on
  12344. * rendering as transparent objects need special treatment and are rendered
  12345. * after non-transparent objects.
  12346. *
  12347. * When set to true, the extent to which the material is transparent is
  12348. * controlled by {@link Material#opacity}.
  12349. *
  12350. * @type {boolean}
  12351. * @default false
  12352. */
  12353. this.transparent = false;
  12354. /**
  12355. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  12356. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  12357. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  12358. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  12359. *
  12360. * @type {boolean}
  12361. * @default false
  12362. */
  12363. this.alphaHash = false;
  12364. /**
  12365. * Defines the blending source factor.
  12366. *
  12367. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12368. * @default SrcAlphaFactor
  12369. */
  12370. this.blendSrc = SrcAlphaFactor;
  12371. /**
  12372. * Defines the blending destination factor.
  12373. *
  12374. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12375. * @default OneMinusSrcAlphaFactor
  12376. */
  12377. this.blendDst = OneMinusSrcAlphaFactor;
  12378. /**
  12379. * Defines the blending equation.
  12380. *
  12381. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12382. * @default AddEquation
  12383. */
  12384. this.blendEquation = AddEquation;
  12385. /**
  12386. * Defines the blending source alpha factor.
  12387. *
  12388. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12389. * @default null
  12390. */
  12391. this.blendSrcAlpha = null;
  12392. /**
  12393. * Defines the blending destination 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.blendDstAlpha = null;
  12399. /**
  12400. * Defines the blending equation of the alpha channel.
  12401. *
  12402. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12403. * @default null
  12404. */
  12405. this.blendEquationAlpha = null;
  12406. /**
  12407. * Represents the RGB values of the constant blend color.
  12408. *
  12409. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  12410. *
  12411. * @type {Color}
  12412. * @default (0,0,0)
  12413. */
  12414. this.blendColor = new Color( 0, 0, 0 );
  12415. /**
  12416. * Represents the alpha value of the constant blend color.
  12417. *
  12418. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  12419. *
  12420. * @type {number}
  12421. * @default 0
  12422. */
  12423. this.blendAlpha = 0;
  12424. /**
  12425. * Defines the depth function.
  12426. *
  12427. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  12428. * @default LessEqualDepth
  12429. */
  12430. this.depthFunc = LessEqualDepth;
  12431. /**
  12432. * Whether to have depth test enabled when rendering this material.
  12433. * When the depth test is disabled, the depth write will also be implicitly disabled.
  12434. *
  12435. * @type {boolean}
  12436. * @default true
  12437. */
  12438. this.depthTest = true;
  12439. /**
  12440. * Whether rendering this material has any effect on the depth buffer.
  12441. *
  12442. * When drawing 2D overlays it can be useful to disable the depth writing in
  12443. * order to layer several things together without creating z-index artifacts.
  12444. *
  12445. * @type {boolean}
  12446. * @default true
  12447. */
  12448. this.depthWrite = true;
  12449. /**
  12450. * The bit mask to use when writing to the stencil buffer.
  12451. *
  12452. * @type {number}
  12453. * @default 0xff
  12454. */
  12455. this.stencilWriteMask = 0xff;
  12456. /**
  12457. * The stencil comparison function to use.
  12458. *
  12459. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  12460. * @default AlwaysStencilFunc
  12461. */
  12462. this.stencilFunc = AlwaysStencilFunc;
  12463. /**
  12464. * The value to use when performing stencil comparisons or stencil operations.
  12465. *
  12466. * @type {number}
  12467. * @default 0
  12468. */
  12469. this.stencilRef = 0;
  12470. /**
  12471. * The bit mask to use when comparing against the stencil buffer.
  12472. *
  12473. * @type {number}
  12474. * @default 0xff
  12475. */
  12476. this.stencilFuncMask = 0xff;
  12477. /**
  12478. * Which stencil operation to perform when the comparison function returns `false`.
  12479. *
  12480. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12481. * @default KeepStencilOp
  12482. */
  12483. this.stencilFail = KeepStencilOp;
  12484. /**
  12485. * Which stencil operation to perform when the comparison function returns
  12486. * `true` but the depth test fails.
  12487. *
  12488. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12489. * @default KeepStencilOp
  12490. */
  12491. this.stencilZFail = KeepStencilOp;
  12492. /**
  12493. * Which stencil operation to perform when the comparison function returns
  12494. * `true` and the depth test passes.
  12495. *
  12496. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12497. * @default KeepStencilOp
  12498. */
  12499. this.stencilZPass = KeepStencilOp;
  12500. /**
  12501. * Whether stencil operations are performed against the stencil buffer. In
  12502. * order to perform writes or comparisons against the stencil buffer this
  12503. * value must be `true`.
  12504. *
  12505. * @type {boolean}
  12506. * @default false
  12507. */
  12508. this.stencilWrite = false;
  12509. /**
  12510. * User-defined clipping planes specified as THREE.Plane objects in world
  12511. * space. These planes apply to the objects this material is attached to.
  12512. * Points in space whose signed distance to the plane is negative are clipped
  12513. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  12514. * be `true`.
  12515. *
  12516. * @type {?Array<Plane>}
  12517. * @default null
  12518. */
  12519. this.clippingPlanes = null;
  12520. /**
  12521. * Changes the behavior of clipping planes so that only their intersection is
  12522. * clipped, rather than their union.
  12523. *
  12524. * @type {boolean}
  12525. * @default false
  12526. */
  12527. this.clipIntersection = false;
  12528. /**
  12529. * Defines whether to clip shadows according to the clipping planes specified
  12530. * on this material.
  12531. *
  12532. * @type {boolean}
  12533. * @default false
  12534. */
  12535. this.clipShadows = false;
  12536. /**
  12537. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  12538. * is determined as follows:
  12539. *
  12540. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  12541. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  12542. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  12543. *
  12544. * @type {?(FrontSide|BackSide|DoubleSide)}
  12545. * @default null
  12546. */
  12547. this.shadowSide = null;
  12548. /**
  12549. * Whether to render the material's color.
  12550. *
  12551. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  12552. * objects that occlude other objects.
  12553. *
  12554. * @type {boolean}
  12555. * @default true
  12556. */
  12557. this.colorWrite = true;
  12558. /**
  12559. * Override the renderer's default precision for this material.
  12560. *
  12561. * @type {?('highp'|'mediump'|'lowp')}
  12562. * @default null
  12563. */
  12564. this.precision = null;
  12565. /**
  12566. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  12567. * be offset after it is interpolated from the depth values of the appropriate vertices.
  12568. * The offset is added before the depth test is performed and before the value is written
  12569. * into the depth buffer.
  12570. *
  12571. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  12572. * rendering solids with highlighted edges.
  12573. *
  12574. * @type {boolean}
  12575. * @default false
  12576. */
  12577. this.polygonOffset = false;
  12578. /**
  12579. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  12580. *
  12581. * @type {number}
  12582. * @default 0
  12583. */
  12584. this.polygonOffsetFactor = 0;
  12585. /**
  12586. * Is multiplied by an implementation-specific value to create a constant depth offset.
  12587. *
  12588. * @type {number}
  12589. * @default 0
  12590. */
  12591. this.polygonOffsetUnits = 0;
  12592. /**
  12593. * Whether to apply dithering to the color to remove the appearance of banding.
  12594. *
  12595. * @type {boolean}
  12596. * @default false
  12597. */
  12598. this.dithering = false;
  12599. /**
  12600. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  12601. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  12602. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  12603. *
  12604. * @type {boolean}
  12605. * @default false
  12606. */
  12607. this.alphaToCoverage = false;
  12608. /**
  12609. * Whether to premultiply the alpha (transparency) value.
  12610. *
  12611. * @type {boolean}
  12612. * @default false
  12613. */
  12614. this.premultipliedAlpha = false;
  12615. /**
  12616. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  12617. *
  12618. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  12619. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  12620. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  12621. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  12622. * disable the two pass rendering to avoid performance issues.
  12623. *
  12624. * @type {boolean}
  12625. * @default false
  12626. */
  12627. this.forceSinglePass = false;
  12628. /**
  12629. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  12630. *
  12631. * @type {boolean}
  12632. * @default true
  12633. */
  12634. this.allowOverride = true;
  12635. /**
  12636. * Defines whether 3D objects using this material are visible.
  12637. *
  12638. * @type {boolean}
  12639. * @default true
  12640. */
  12641. this.visible = true;
  12642. /**
  12643. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  12644. *
  12645. * It is ignored when rendering to a render target or using post processing or when using
  12646. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  12647. *
  12648. * @type {boolean}
  12649. * @default true
  12650. */
  12651. this.toneMapped = true;
  12652. /**
  12653. * An object that can be used to store custom data about the Material. It
  12654. * should not hold references to functions as these will not be cloned.
  12655. *
  12656. * @type {Object}
  12657. */
  12658. this.userData = {};
  12659. /**
  12660. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  12661. *
  12662. * @type {number}
  12663. * @readonly
  12664. * @default 0
  12665. */
  12666. this.version = 0;
  12667. this._alphaTest = 0;
  12668. }
  12669. /**
  12670. * Sets the alpha value to be used when running an alpha test. The material
  12671. * will not be rendered if the opacity is lower than this value.
  12672. *
  12673. * @type {number}
  12674. * @readonly
  12675. * @default 0
  12676. */
  12677. get alphaTest() {
  12678. return this._alphaTest;
  12679. }
  12680. set alphaTest( value ) {
  12681. if ( this._alphaTest > 0 !== value > 0 ) {
  12682. this.version ++;
  12683. }
  12684. this._alphaTest = value;
  12685. }
  12686. /**
  12687. * An optional callback that is executed immediately before the material is used to render a 3D object.
  12688. *
  12689. * This method can only be used when rendering with {@link WebGLRenderer}.
  12690. *
  12691. * @param {WebGLRenderer} renderer - The renderer.
  12692. * @param {Scene} scene - The scene.
  12693. * @param {Camera} camera - The camera that is used to render the scene.
  12694. * @param {BufferGeometry} geometry - The 3D object's geometry.
  12695. * @param {Object3D} object - The 3D object.
  12696. * @param {Object} group - The geometry group data.
  12697. */
  12698. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  12699. /**
  12700. * An optional callback that is executed immediately before the shader
  12701. * program is compiled. This function is called with the shader source code
  12702. * as a parameter. Useful for the modification of built-in materials.
  12703. *
  12704. * This method can only be used when rendering with {@link WebGLRenderer}. The
  12705. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  12706. * Node Material system and [TSL]{@link https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language}.
  12707. *
  12708. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  12709. * @param {WebGLRenderer} renderer - A reference to the renderer.
  12710. */
  12711. onBeforeCompile( /* shaderobject, renderer */ ) {}
  12712. /**
  12713. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  12714. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  12715. * shader or recompile the shader for this material as needed.
  12716. *
  12717. * This method can only be used when rendering with {@link WebGLRenderer}.
  12718. *
  12719. * @return {string} The custom program cache key.
  12720. */
  12721. customProgramCacheKey() {
  12722. return this.onBeforeCompile.toString();
  12723. }
  12724. /**
  12725. * This method can be used to set default values from parameter objects.
  12726. * It is a generic implementation so it can be used with different types
  12727. * of materials.
  12728. *
  12729. * @param {Object} [values] - The material values to set.
  12730. */
  12731. setValues( values ) {
  12732. if ( values === undefined ) return;
  12733. for ( const key in values ) {
  12734. const newValue = values[ key ];
  12735. if ( newValue === undefined ) {
  12736. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  12737. continue;
  12738. }
  12739. const currentValue = this[ key ];
  12740. if ( currentValue === undefined ) {
  12741. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  12742. continue;
  12743. }
  12744. if ( currentValue && currentValue.isColor ) {
  12745. currentValue.set( newValue );
  12746. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  12747. currentValue.copy( newValue );
  12748. } else {
  12749. this[ key ] = newValue;
  12750. }
  12751. }
  12752. }
  12753. /**
  12754. * Serializes the material into JSON.
  12755. *
  12756. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  12757. * @return {Object} A JSON object representing the serialized material.
  12758. * @see {@link ObjectLoader#parse}
  12759. */
  12760. toJSON( meta ) {
  12761. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  12762. if ( isRootObject ) {
  12763. meta = {
  12764. textures: {},
  12765. images: {}
  12766. };
  12767. }
  12768. const data = {
  12769. metadata: {
  12770. version: 4.7,
  12771. type: 'Material',
  12772. generator: 'Material.toJSON'
  12773. }
  12774. };
  12775. // standard Material serialization
  12776. data.uuid = this.uuid;
  12777. data.type = this.type;
  12778. if ( this.name !== '' ) data.name = this.name;
  12779. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  12780. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  12781. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  12782. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  12783. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  12784. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  12785. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  12786. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  12787. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  12788. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  12789. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  12790. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  12791. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  12792. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  12793. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  12794. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  12795. }
  12796. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  12797. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  12798. }
  12799. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  12800. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  12801. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  12802. }
  12803. if ( this.sheenColorMap && this.sheenColorMap.isTexture ) {
  12804. data.sheenColorMap = this.sheenColorMap.toJSON( meta ).uuid;
  12805. }
  12806. if ( this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture ) {
  12807. data.sheenRoughnessMap = this.sheenRoughnessMap.toJSON( meta ).uuid;
  12808. }
  12809. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  12810. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  12811. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  12812. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  12813. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  12814. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  12815. }
  12816. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  12817. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  12818. }
  12819. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  12820. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  12821. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  12822. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  12823. }
  12824. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  12825. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  12826. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  12827. if ( this.lightMap && this.lightMap.isTexture ) {
  12828. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  12829. data.lightMapIntensity = this.lightMapIntensity;
  12830. }
  12831. if ( this.aoMap && this.aoMap.isTexture ) {
  12832. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  12833. data.aoMapIntensity = this.aoMapIntensity;
  12834. }
  12835. if ( this.bumpMap && this.bumpMap.isTexture ) {
  12836. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  12837. data.bumpScale = this.bumpScale;
  12838. }
  12839. if ( this.normalMap && this.normalMap.isTexture ) {
  12840. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  12841. data.normalMapType = this.normalMapType;
  12842. data.normalScale = this.normalScale.toArray();
  12843. }
  12844. if ( this.displacementMap && this.displacementMap.isTexture ) {
  12845. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  12846. data.displacementScale = this.displacementScale;
  12847. data.displacementBias = this.displacementBias;
  12848. }
  12849. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  12850. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  12851. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  12852. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  12853. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  12854. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  12855. if ( this.envMap && this.envMap.isTexture ) {
  12856. data.envMap = this.envMap.toJSON( meta ).uuid;
  12857. if ( this.combine !== undefined ) data.combine = this.combine;
  12858. }
  12859. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  12860. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  12861. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  12862. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  12863. if ( this.gradientMap && this.gradientMap.isTexture ) {
  12864. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  12865. }
  12866. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  12867. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  12868. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  12869. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  12870. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  12871. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  12872. if ( this.size !== undefined ) data.size = this.size;
  12873. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  12874. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  12875. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  12876. if ( this.side !== FrontSide ) data.side = this.side;
  12877. if ( this.vertexColors === true ) data.vertexColors = true;
  12878. if ( this.opacity < 1 ) data.opacity = this.opacity;
  12879. if ( this.transparent === true ) data.transparent = true;
  12880. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  12881. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  12882. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  12883. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  12884. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  12885. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  12886. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  12887. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  12888. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  12889. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  12890. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  12891. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  12892. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  12893. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  12894. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  12895. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  12896. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  12897. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  12898. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  12899. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  12900. // rotation (SpriteMaterial)
  12901. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  12902. if ( this.polygonOffset === true ) data.polygonOffset = true;
  12903. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  12904. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  12905. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  12906. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  12907. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  12908. if ( this.scale !== undefined ) data.scale = this.scale;
  12909. if ( this.dithering === true ) data.dithering = true;
  12910. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  12911. if ( this.alphaHash === true ) data.alphaHash = true;
  12912. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  12913. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  12914. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  12915. if ( this.wireframe === true ) data.wireframe = true;
  12916. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  12917. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  12918. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  12919. if ( this.flatShading === true ) data.flatShading = true;
  12920. if ( this.visible === false ) data.visible = false;
  12921. if ( this.toneMapped === false ) data.toneMapped = false;
  12922. if ( this.fog === false ) data.fog = false;
  12923. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  12924. // TODO: Copied from Object3D.toJSON
  12925. function extractFromCache( cache ) {
  12926. const values = [];
  12927. for ( const key in cache ) {
  12928. const data = cache[ key ];
  12929. delete data.metadata;
  12930. values.push( data );
  12931. }
  12932. return values;
  12933. }
  12934. if ( isRootObject ) {
  12935. const textures = extractFromCache( meta.textures );
  12936. const images = extractFromCache( meta.images );
  12937. if ( textures.length > 0 ) data.textures = textures;
  12938. if ( images.length > 0 ) data.images = images;
  12939. }
  12940. return data;
  12941. }
  12942. /**
  12943. * Returns a new material with copied values from this instance.
  12944. *
  12945. * @return {Material} A clone of this instance.
  12946. */
  12947. clone() {
  12948. return new this.constructor().copy( this );
  12949. }
  12950. /**
  12951. * Copies the values of the given material to this instance.
  12952. *
  12953. * @param {Material} source - The material to copy.
  12954. * @return {Material} A reference to this instance.
  12955. */
  12956. copy( source ) {
  12957. this.name = source.name;
  12958. this.blending = source.blending;
  12959. this.side = source.side;
  12960. this.vertexColors = source.vertexColors;
  12961. this.opacity = source.opacity;
  12962. this.transparent = source.transparent;
  12963. this.blendSrc = source.blendSrc;
  12964. this.blendDst = source.blendDst;
  12965. this.blendEquation = source.blendEquation;
  12966. this.blendSrcAlpha = source.blendSrcAlpha;
  12967. this.blendDstAlpha = source.blendDstAlpha;
  12968. this.blendEquationAlpha = source.blendEquationAlpha;
  12969. this.blendColor.copy( source.blendColor );
  12970. this.blendAlpha = source.blendAlpha;
  12971. this.depthFunc = source.depthFunc;
  12972. this.depthTest = source.depthTest;
  12973. this.depthWrite = source.depthWrite;
  12974. this.stencilWriteMask = source.stencilWriteMask;
  12975. this.stencilFunc = source.stencilFunc;
  12976. this.stencilRef = source.stencilRef;
  12977. this.stencilFuncMask = source.stencilFuncMask;
  12978. this.stencilFail = source.stencilFail;
  12979. this.stencilZFail = source.stencilZFail;
  12980. this.stencilZPass = source.stencilZPass;
  12981. this.stencilWrite = source.stencilWrite;
  12982. const srcPlanes = source.clippingPlanes;
  12983. let dstPlanes = null;
  12984. if ( srcPlanes !== null ) {
  12985. const n = srcPlanes.length;
  12986. dstPlanes = new Array( n );
  12987. for ( let i = 0; i !== n; ++ i ) {
  12988. dstPlanes[ i ] = srcPlanes[ i ].clone();
  12989. }
  12990. }
  12991. this.clippingPlanes = dstPlanes;
  12992. this.clipIntersection = source.clipIntersection;
  12993. this.clipShadows = source.clipShadows;
  12994. this.shadowSide = source.shadowSide;
  12995. this.colorWrite = source.colorWrite;
  12996. this.precision = source.precision;
  12997. this.polygonOffset = source.polygonOffset;
  12998. this.polygonOffsetFactor = source.polygonOffsetFactor;
  12999. this.polygonOffsetUnits = source.polygonOffsetUnits;
  13000. this.dithering = source.dithering;
  13001. this.alphaTest = source.alphaTest;
  13002. this.alphaHash = source.alphaHash;
  13003. this.alphaToCoverage = source.alphaToCoverage;
  13004. this.premultipliedAlpha = source.premultipliedAlpha;
  13005. this.forceSinglePass = source.forceSinglePass;
  13006. this.visible = source.visible;
  13007. this.toneMapped = source.toneMapped;
  13008. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  13009. return this;
  13010. }
  13011. /**
  13012. * Frees the GPU-related resources allocated by this instance. Call this
  13013. * method whenever this instance is no longer used in your app.
  13014. *
  13015. * @fires Material#dispose
  13016. */
  13017. dispose() {
  13018. /**
  13019. * Fires when the material has been disposed of.
  13020. *
  13021. * @event Material#dispose
  13022. * @type {Object}
  13023. */
  13024. this.dispatchEvent( { type: 'dispose' } );
  13025. }
  13026. /**
  13027. * Setting this property to `true` indicates the engine the material
  13028. * needs to be recompiled.
  13029. *
  13030. * @type {boolean}
  13031. * @default false
  13032. * @param {boolean} value
  13033. */
  13034. set needsUpdate( value ) {
  13035. if ( value === true ) this.version ++;
  13036. }
  13037. }
  13038. /**
  13039. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  13040. *
  13041. * This material is not affected by lights.
  13042. *
  13043. * @augments Material
  13044. */
  13045. class MeshBasicMaterial extends Material {
  13046. /**
  13047. * Constructs a new mesh basic material.
  13048. *
  13049. * @param {Object} [parameters] - An object with one or more properties
  13050. * defining the material's appearance. Any property of the material
  13051. * (including any property from inherited materials) can be passed
  13052. * in here. Color values can be passed any type of value accepted
  13053. * by {@link Color#set}.
  13054. */
  13055. constructor( parameters ) {
  13056. super();
  13057. /**
  13058. * This flag can be used for type testing.
  13059. *
  13060. * @type {boolean}
  13061. * @readonly
  13062. * @default true
  13063. */
  13064. this.isMeshBasicMaterial = true;
  13065. this.type = 'MeshBasicMaterial';
  13066. /**
  13067. * Color of the material.
  13068. *
  13069. * @type {Color}
  13070. * @default (1,1,1)
  13071. */
  13072. this.color = new Color( 0xffffff ); // diffuse
  13073. /**
  13074. * The color map. May optionally include an alpha channel, typically combined
  13075. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  13076. * color is modulated by the diffuse `color`.
  13077. *
  13078. * @type {?Texture}
  13079. * @default null
  13080. */
  13081. this.map = null;
  13082. /**
  13083. * The light map. Requires a second set of UVs.
  13084. *
  13085. * @type {?Texture}
  13086. * @default null
  13087. */
  13088. this.lightMap = null;
  13089. /**
  13090. * Intensity of the baked light.
  13091. *
  13092. * @type {number}
  13093. * @default 1
  13094. */
  13095. this.lightMapIntensity = 1.0;
  13096. /**
  13097. * The red channel of this texture is used as the ambient occlusion map.
  13098. * Requires a second set of UVs.
  13099. *
  13100. * @type {?Texture}
  13101. * @default null
  13102. */
  13103. this.aoMap = null;
  13104. /**
  13105. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  13106. * disables ambient occlusion. Where intensity is `1` and the AO map's
  13107. * red channel is also `1`, ambient light is fully occluded on a surface.
  13108. *
  13109. * @type {number}
  13110. * @default 1
  13111. */
  13112. this.aoMapIntensity = 1.0;
  13113. /**
  13114. * Specular map used by the material.
  13115. *
  13116. * @type {?Texture}
  13117. * @default null
  13118. */
  13119. this.specularMap = null;
  13120. /**
  13121. * The alpha map is a grayscale texture that controls the opacity across the
  13122. * surface (black: fully transparent; white: fully opaque).
  13123. *
  13124. * Only the color of the texture is used, ignoring the alpha channel if one
  13125. * exists. For RGB and RGBA textures, the renderer will use the green channel
  13126. * when sampling this texture due to the extra bit of precision provided for
  13127. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  13128. * luminance/alpha textures will also still work as expected.
  13129. *
  13130. * @type {?Texture}
  13131. * @default null
  13132. */
  13133. this.alphaMap = null;
  13134. /**
  13135. * The environment map.
  13136. *
  13137. * @type {?Texture}
  13138. * @default null
  13139. */
  13140. this.envMap = null;
  13141. /**
  13142. * The rotation of the environment map in radians.
  13143. *
  13144. * @type {Euler}
  13145. * @default (0,0,0)
  13146. */
  13147. this.envMapRotation = new Euler();
  13148. /**
  13149. * How to combine the result of the surface's color with the environment map, if any.
  13150. *
  13151. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  13152. * blend between the two colors.
  13153. *
  13154. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  13155. * @default MultiplyOperation
  13156. */
  13157. this.combine = MultiplyOperation;
  13158. /**
  13159. * How much the environment map affects the surface.
  13160. * The valid range is between `0` (no reflections) and `1` (full reflections).
  13161. *
  13162. * @type {number}
  13163. * @default 1
  13164. */
  13165. this.reflectivity = 1;
  13166. /**
  13167. * The index of refraction (IOR) of air (approximately 1) divided by the
  13168. * index of refraction of the material. It is used with environment mapping
  13169. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  13170. * The refraction ratio should not exceed `1`.
  13171. *
  13172. * @type {number}
  13173. * @default 0.98
  13174. */
  13175. this.refractionRatio = 0.98;
  13176. /**
  13177. * Renders the geometry as a wireframe.
  13178. *
  13179. * @type {boolean}
  13180. * @default false
  13181. */
  13182. this.wireframe = false;
  13183. /**
  13184. * Controls the thickness of the wireframe.
  13185. *
  13186. * Can only be used with {@link SVGRenderer}.
  13187. *
  13188. * @type {number}
  13189. * @default 1
  13190. */
  13191. this.wireframeLinewidth = 1;
  13192. /**
  13193. * Defines appearance of wireframe ends.
  13194. *
  13195. * Can only be used with {@link SVGRenderer}.
  13196. *
  13197. * @type {('round'|'bevel'|'miter')}
  13198. * @default 'round'
  13199. */
  13200. this.wireframeLinecap = 'round';
  13201. /**
  13202. * Defines appearance of wireframe joints.
  13203. *
  13204. * Can only be used with {@link SVGRenderer}.
  13205. *
  13206. * @type {('round'|'bevel'|'miter')}
  13207. * @default 'round'
  13208. */
  13209. this.wireframeLinejoin = 'round';
  13210. /**
  13211. * Whether the material is affected by fog or not.
  13212. *
  13213. * @type {boolean}
  13214. * @default true
  13215. */
  13216. this.fog = true;
  13217. this.setValues( parameters );
  13218. }
  13219. copy( source ) {
  13220. super.copy( source );
  13221. this.color.copy( source.color );
  13222. this.map = source.map;
  13223. this.lightMap = source.lightMap;
  13224. this.lightMapIntensity = source.lightMapIntensity;
  13225. this.aoMap = source.aoMap;
  13226. this.aoMapIntensity = source.aoMapIntensity;
  13227. this.specularMap = source.specularMap;
  13228. this.alphaMap = source.alphaMap;
  13229. this.envMap = source.envMap;
  13230. this.envMapRotation.copy( source.envMapRotation );
  13231. this.combine = source.combine;
  13232. this.reflectivity = source.reflectivity;
  13233. this.refractionRatio = source.refractionRatio;
  13234. this.wireframe = source.wireframe;
  13235. this.wireframeLinewidth = source.wireframeLinewidth;
  13236. this.wireframeLinecap = source.wireframeLinecap;
  13237. this.wireframeLinejoin = source.wireframeLinejoin;
  13238. this.fog = source.fog;
  13239. return this;
  13240. }
  13241. }
  13242. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  13243. const _tables = /*@__PURE__*/ _generateTables();
  13244. function _generateTables() {
  13245. // float32 to float16 helpers
  13246. const buffer = new ArrayBuffer( 4 );
  13247. const floatView = new Float32Array( buffer );
  13248. const uint32View = new Uint32Array( buffer );
  13249. const baseTable = new Uint32Array( 512 );
  13250. const shiftTable = new Uint32Array( 512 );
  13251. for ( let i = 0; i < 256; ++ i ) {
  13252. const e = i - 127;
  13253. // very small number (0, -0)
  13254. if ( e < -27 ) {
  13255. baseTable[ i ] = 0x0000;
  13256. baseTable[ i | 0x100 ] = 0x8000;
  13257. shiftTable[ i ] = 24;
  13258. shiftTable[ i | 0x100 ] = 24;
  13259. // small number (denorm)
  13260. } else if ( e < -14 ) {
  13261. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  13262. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  13263. shiftTable[ i ] = - e - 1;
  13264. shiftTable[ i | 0x100 ] = - e - 1;
  13265. // normal number
  13266. } else if ( e <= 15 ) {
  13267. baseTable[ i ] = ( e + 15 ) << 10;
  13268. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  13269. shiftTable[ i ] = 13;
  13270. shiftTable[ i | 0x100 ] = 13;
  13271. // large number (Infinity, -Infinity)
  13272. } else if ( e < 128 ) {
  13273. baseTable[ i ] = 0x7c00;
  13274. baseTable[ i | 0x100 ] = 0xfc00;
  13275. shiftTable[ i ] = 24;
  13276. shiftTable[ i | 0x100 ] = 24;
  13277. // stay (NaN, Infinity, -Infinity)
  13278. } else {
  13279. baseTable[ i ] = 0x7c00;
  13280. baseTable[ i | 0x100 ] = 0xfc00;
  13281. shiftTable[ i ] = 13;
  13282. shiftTable[ i | 0x100 ] = 13;
  13283. }
  13284. }
  13285. // float16 to float32 helpers
  13286. const mantissaTable = new Uint32Array( 2048 );
  13287. const exponentTable = new Uint32Array( 64 );
  13288. const offsetTable = new Uint32Array( 64 );
  13289. for ( let i = 1; i < 1024; ++ i ) {
  13290. let m = i << 13; // zero pad mantissa bits
  13291. let e = 0; // zero exponent
  13292. // normalized
  13293. while ( ( m & 0x00800000 ) === 0 ) {
  13294. m <<= 1;
  13295. e -= 0x00800000; // decrement exponent
  13296. }
  13297. m &= -8388609; // clear leading 1 bit
  13298. e += 0x38800000; // adjust bias
  13299. mantissaTable[ i ] = m | e;
  13300. }
  13301. for ( let i = 1024; i < 2048; ++ i ) {
  13302. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  13303. }
  13304. for ( let i = 1; i < 31; ++ i ) {
  13305. exponentTable[ i ] = i << 23;
  13306. }
  13307. exponentTable[ 31 ] = 0x47800000;
  13308. exponentTable[ 32 ] = 0x80000000;
  13309. for ( let i = 33; i < 63; ++ i ) {
  13310. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  13311. }
  13312. exponentTable[ 63 ] = 0xc7800000;
  13313. for ( let i = 1; i < 64; ++ i ) {
  13314. if ( i !== 32 ) {
  13315. offsetTable[ i ] = 1024;
  13316. }
  13317. }
  13318. return {
  13319. floatView: floatView,
  13320. uint32View: uint32View,
  13321. baseTable: baseTable,
  13322. shiftTable: shiftTable,
  13323. mantissaTable: mantissaTable,
  13324. exponentTable: exponentTable,
  13325. offsetTable: offsetTable
  13326. };
  13327. }
  13328. /**
  13329. * Returns a half precision floating point value (FP16) from the given single
  13330. * precision floating point value (FP32).
  13331. *
  13332. * @param {number} val - A single precision floating point value.
  13333. * @return {number} The FP16 value.
  13334. */
  13335. function toHalfFloat( val ) {
  13336. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  13337. val = clamp( val, -65504, 65504 );
  13338. _tables.floatView[ 0 ] = val;
  13339. const f = _tables.uint32View[ 0 ];
  13340. const e = ( f >> 23 ) & 0x1ff;
  13341. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  13342. }
  13343. /**
  13344. * Returns a single precision floating point value (FP32) from the given half
  13345. * precision floating point value (FP16).
  13346. *
  13347. * @param {number} val - A half precision floating point value.
  13348. * @return {number} The FP32 value.
  13349. */
  13350. function fromHalfFloat( val ) {
  13351. const m = val >> 10;
  13352. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  13353. return _tables.floatView[ 0 ];
  13354. }
  13355. /**
  13356. * A class containing utility functions for data.
  13357. *
  13358. * @hideconstructor
  13359. */
  13360. class DataUtils {
  13361. /**
  13362. * Returns a half precision floating point value (FP16) from the given single
  13363. * precision floating point value (FP32).
  13364. *
  13365. * @param {number} val - A single precision floating point value.
  13366. * @return {number} The FP16 value.
  13367. */
  13368. static toHalfFloat( val ) {
  13369. return toHalfFloat( val );
  13370. }
  13371. /**
  13372. * Returns a single precision floating point value (FP32) from the given half
  13373. * precision floating point value (FP16).
  13374. *
  13375. * @param {number} val - A half precision floating point value.
  13376. * @return {number} The FP32 value.
  13377. */
  13378. static fromHalfFloat( val ) {
  13379. return fromHalfFloat( val );
  13380. }
  13381. }
  13382. const _vector$9 = /*@__PURE__*/ new Vector3();
  13383. const _vector2$1 = /*@__PURE__*/ new Vector2();
  13384. let _id$3 = 0;
  13385. /**
  13386. * This class stores data for an attribute (such as vertex positions, face
  13387. * indices, normals, colors, UVs, and any custom attributes ) associated with
  13388. * a geometry, which allows for more efficient passing of data to the GPU.
  13389. *
  13390. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  13391. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  13392. */
  13393. class BufferAttribute {
  13394. /**
  13395. * Constructs a new buffer attribute.
  13396. *
  13397. * @param {TypedArray} array - The array holding the attribute data.
  13398. * @param {number} itemSize - The item size.
  13399. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13400. */
  13401. constructor( array, itemSize, normalized = false ) {
  13402. if ( Array.isArray( array ) ) {
  13403. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  13404. }
  13405. /**
  13406. * This flag can be used for type testing.
  13407. *
  13408. * @type {boolean}
  13409. * @readonly
  13410. * @default true
  13411. */
  13412. this.isBufferAttribute = true;
  13413. /**
  13414. * The ID of the buffer attribute.
  13415. *
  13416. * @name BufferAttribute#id
  13417. * @type {number}
  13418. * @readonly
  13419. */
  13420. Object.defineProperty( this, 'id', { value: _id$3 ++ } );
  13421. /**
  13422. * The name of the buffer attribute.
  13423. *
  13424. * @type {string}
  13425. */
  13426. this.name = '';
  13427. /**
  13428. * The array holding the attribute data. It should have `itemSize * numVertices`
  13429. * elements, where `numVertices` is the number of vertices in the associated geometry.
  13430. *
  13431. * @type {TypedArray}
  13432. */
  13433. this.array = array;
  13434. /**
  13435. * The number of values of the array that should be associated with a particular vertex.
  13436. * For instance, if this attribute is storing a 3-component vector (such as a position,
  13437. * normal, or color), then the value should be `3`.
  13438. *
  13439. * @type {number}
  13440. */
  13441. this.itemSize = itemSize;
  13442. /**
  13443. * Represents the number of items this buffer attribute stores. It is internally computed
  13444. * by dividing the `array` length by the `itemSize`.
  13445. *
  13446. * @type {number}
  13447. * @readonly
  13448. */
  13449. this.count = array !== undefined ? array.length / itemSize : 0;
  13450. /**
  13451. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  13452. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  13453. * and `normalized` is `true`, the values `0 - +65535` in the array data will be mapped to
  13454. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  13455. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  13456. *
  13457. * @type {boolean}
  13458. */
  13459. this.normalized = normalized;
  13460. /**
  13461. * Defines the intended usage pattern of the data store for optimization purposes.
  13462. *
  13463. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  13464. * instantiate a new one and set the desired usage before the next render.
  13465. *
  13466. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  13467. * @default StaticDrawUsage
  13468. */
  13469. this.usage = StaticDrawUsage;
  13470. /**
  13471. * This can be used to only update some components of stored vectors (for example, just the
  13472. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  13473. *
  13474. * @type {Array<Object>}
  13475. */
  13476. this.updateRanges = [];
  13477. /**
  13478. * Configures the bound GPU type for use in shaders.
  13479. *
  13480. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  13481. * For lower precision float types, use `Float16BufferAttribute`.
  13482. *
  13483. * @type {(FloatType|IntType)}
  13484. * @default FloatType
  13485. */
  13486. this.gpuType = FloatType;
  13487. /**
  13488. * A version number, incremented every time the `needsUpdate` is set to `true`.
  13489. *
  13490. * @type {number}
  13491. */
  13492. this.version = 0;
  13493. }
  13494. /**
  13495. * A callback function that is executed after the renderer has transferred the attribute
  13496. * array data to the GPU.
  13497. */
  13498. onUploadCallback() {}
  13499. /**
  13500. * Flag to indicate that this attribute has changed and should be re-sent to
  13501. * the GPU. Set this to `true` when you modify the value of the array.
  13502. *
  13503. * @type {number}
  13504. * @default false
  13505. * @param {boolean} value
  13506. */
  13507. set needsUpdate( value ) {
  13508. if ( value === true ) this.version ++;
  13509. }
  13510. /**
  13511. * Sets the usage of this buffer attribute.
  13512. *
  13513. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  13514. * @return {BufferAttribute} A reference to this buffer attribute.
  13515. */
  13516. setUsage( value ) {
  13517. this.usage = value;
  13518. return this;
  13519. }
  13520. /**
  13521. * Adds a range of data in the data array to be updated on the GPU.
  13522. *
  13523. * @param {number} start - Position at which to start update.
  13524. * @param {number} count - The number of components to update.
  13525. */
  13526. addUpdateRange( start, count ) {
  13527. this.updateRanges.push( { start, count } );
  13528. }
  13529. /**
  13530. * Clears the update ranges.
  13531. */
  13532. clearUpdateRanges() {
  13533. this.updateRanges.length = 0;
  13534. }
  13535. /**
  13536. * Copies the values of the given buffer attribute to this instance.
  13537. *
  13538. * @param {BufferAttribute} source - The buffer attribute to copy.
  13539. * @return {BufferAttribute} A reference to this instance.
  13540. */
  13541. copy( source ) {
  13542. this.name = source.name;
  13543. this.array = new source.array.constructor( source.array );
  13544. this.itemSize = source.itemSize;
  13545. this.count = source.count;
  13546. this.normalized = source.normalized;
  13547. this.usage = source.usage;
  13548. this.gpuType = source.gpuType;
  13549. return this;
  13550. }
  13551. /**
  13552. * Copies a vector from the given buffer attribute to this one. The start
  13553. * and destination position in the attribute buffers are represented by the
  13554. * given indices.
  13555. *
  13556. * @param {number} index1 - The destination index into this buffer attribute.
  13557. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  13558. * @param {number} index2 - The source index into the given buffer attribute.
  13559. * @return {BufferAttribute} A reference to this instance.
  13560. */
  13561. copyAt( index1, attribute, index2 ) {
  13562. index1 *= this.itemSize;
  13563. index2 *= attribute.itemSize;
  13564. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  13565. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13566. }
  13567. return this;
  13568. }
  13569. /**
  13570. * Copies the given array data into this buffer attribute.
  13571. *
  13572. * @param {(TypedArray|Array)} array - The array to copy.
  13573. * @return {BufferAttribute} A reference to this instance.
  13574. */
  13575. copyArray( array ) {
  13576. this.array.set( array );
  13577. return this;
  13578. }
  13579. /**
  13580. * Applies the given 3x3 matrix to the given attribute. Works with
  13581. * item size `2` and `3`.
  13582. *
  13583. * @param {Matrix3} m - The matrix to apply.
  13584. * @return {BufferAttribute} A reference to this instance.
  13585. */
  13586. applyMatrix3( m ) {
  13587. if ( this.itemSize === 2 ) {
  13588. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13589. _vector2$1.fromBufferAttribute( this, i );
  13590. _vector2$1.applyMatrix3( m );
  13591. this.setXY( i, _vector2$1.x, _vector2$1.y );
  13592. }
  13593. } else if ( this.itemSize === 3 ) {
  13594. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13595. _vector$9.fromBufferAttribute( this, i );
  13596. _vector$9.applyMatrix3( m );
  13597. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13598. }
  13599. }
  13600. return this;
  13601. }
  13602. /**
  13603. * Applies the given 4x4 matrix to the given attribute. Only works with
  13604. * item size `3`.
  13605. *
  13606. * @param {Matrix4} m - The matrix to apply.
  13607. * @return {BufferAttribute} A reference to this instance.
  13608. */
  13609. applyMatrix4( m ) {
  13610. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13611. _vector$9.fromBufferAttribute( this, i );
  13612. _vector$9.applyMatrix4( m );
  13613. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13614. }
  13615. return this;
  13616. }
  13617. /**
  13618. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  13619. * item size `3`.
  13620. *
  13621. * @param {Matrix3} m - The normal matrix to apply.
  13622. * @return {BufferAttribute} A reference to this instance.
  13623. */
  13624. applyNormalMatrix( m ) {
  13625. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13626. _vector$9.fromBufferAttribute( this, i );
  13627. _vector$9.applyNormalMatrix( m );
  13628. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13629. }
  13630. return this;
  13631. }
  13632. /**
  13633. * Applies the given 4x4 matrix to the given attribute. Only works with
  13634. * item size `3` and with direction vectors.
  13635. *
  13636. * @param {Matrix4} m - The matrix to apply.
  13637. * @return {BufferAttribute} A reference to this instance.
  13638. */
  13639. transformDirection( m ) {
  13640. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13641. _vector$9.fromBufferAttribute( this, i );
  13642. _vector$9.transformDirection( m );
  13643. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13644. }
  13645. return this;
  13646. }
  13647. /**
  13648. * Sets the given array data in the buffer attribute.
  13649. *
  13650. * @param {(TypedArray|Array)} value - The array data to set.
  13651. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  13652. * @return {BufferAttribute} A reference to this instance.
  13653. */
  13654. set( value, offset = 0 ) {
  13655. // Matching BufferAttribute constructor, do not normalize the array.
  13656. this.array.set( value, offset );
  13657. return this;
  13658. }
  13659. /**
  13660. * Returns the given component of the vector at the given index.
  13661. *
  13662. * @param {number} index - The index into the buffer attribute.
  13663. * @param {number} component - The component index.
  13664. * @return {number} The returned value.
  13665. */
  13666. getComponent( index, component ) {
  13667. let value = this.array[ index * this.itemSize + component ];
  13668. if ( this.normalized ) value = denormalize( value, this.array );
  13669. return value;
  13670. }
  13671. /**
  13672. * Sets the given value to the given component of the vector at the given index.
  13673. *
  13674. * @param {number} index - The index into the buffer attribute.
  13675. * @param {number} component - The component index.
  13676. * @param {number} value - The value to set.
  13677. * @return {BufferAttribute} A reference to this instance.
  13678. */
  13679. setComponent( index, component, value ) {
  13680. if ( this.normalized ) value = normalize( value, this.array );
  13681. this.array[ index * this.itemSize + component ] = value;
  13682. return this;
  13683. }
  13684. /**
  13685. * Returns the x component of the vector at the given index.
  13686. *
  13687. * @param {number} index - The index into the buffer attribute.
  13688. * @return {number} The x component.
  13689. */
  13690. getX( index ) {
  13691. let x = this.array[ index * this.itemSize ];
  13692. if ( this.normalized ) x = denormalize( x, this.array );
  13693. return x;
  13694. }
  13695. /**
  13696. * Sets the x component of the vector at the given index.
  13697. *
  13698. * @param {number} index - The index into the buffer attribute.
  13699. * @param {number} x - The value to set.
  13700. * @return {BufferAttribute} A reference to this instance.
  13701. */
  13702. setX( index, x ) {
  13703. if ( this.normalized ) x = normalize( x, this.array );
  13704. this.array[ index * this.itemSize ] = x;
  13705. return this;
  13706. }
  13707. /**
  13708. * Returns the y component of the vector at the given index.
  13709. *
  13710. * @param {number} index - The index into the buffer attribute.
  13711. * @return {number} The y component.
  13712. */
  13713. getY( index ) {
  13714. let y = this.array[ index * this.itemSize + 1 ];
  13715. if ( this.normalized ) y = denormalize( y, this.array );
  13716. return y;
  13717. }
  13718. /**
  13719. * Sets the y component of the vector at the given index.
  13720. *
  13721. * @param {number} index - The index into the buffer attribute.
  13722. * @param {number} y - The value to set.
  13723. * @return {BufferAttribute} A reference to this instance.
  13724. */
  13725. setY( index, y ) {
  13726. if ( this.normalized ) y = normalize( y, this.array );
  13727. this.array[ index * this.itemSize + 1 ] = y;
  13728. return this;
  13729. }
  13730. /**
  13731. * Returns the z component of the vector at the given index.
  13732. *
  13733. * @param {number} index - The index into the buffer attribute.
  13734. * @return {number} The z component.
  13735. */
  13736. getZ( index ) {
  13737. let z = this.array[ index * this.itemSize + 2 ];
  13738. if ( this.normalized ) z = denormalize( z, this.array );
  13739. return z;
  13740. }
  13741. /**
  13742. * Sets the z component of the vector at the given index.
  13743. *
  13744. * @param {number} index - The index into the buffer attribute.
  13745. * @param {number} z - The value to set.
  13746. * @return {BufferAttribute} A reference to this instance.
  13747. */
  13748. setZ( index, z ) {
  13749. if ( this.normalized ) z = normalize( z, this.array );
  13750. this.array[ index * this.itemSize + 2 ] = z;
  13751. return this;
  13752. }
  13753. /**
  13754. * Returns the w component of the vector at the given index.
  13755. *
  13756. * @param {number} index - The index into the buffer attribute.
  13757. * @return {number} The w component.
  13758. */
  13759. getW( index ) {
  13760. let w = this.array[ index * this.itemSize + 3 ];
  13761. if ( this.normalized ) w = denormalize( w, this.array );
  13762. return w;
  13763. }
  13764. /**
  13765. * Sets the w component of the vector at the given index.
  13766. *
  13767. * @param {number} index - The index into the buffer attribute.
  13768. * @param {number} w - The value to set.
  13769. * @return {BufferAttribute} A reference to this instance.
  13770. */
  13771. setW( index, w ) {
  13772. if ( this.normalized ) w = normalize( w, this.array );
  13773. this.array[ index * this.itemSize + 3 ] = w;
  13774. return this;
  13775. }
  13776. /**
  13777. * Sets the x and y component of the vector at the given index.
  13778. *
  13779. * @param {number} index - The index into the buffer attribute.
  13780. * @param {number} x - The value for the x component to set.
  13781. * @param {number} y - The value for the y component to set.
  13782. * @return {BufferAttribute} A reference to this instance.
  13783. */
  13784. setXY( index, x, y ) {
  13785. index *= this.itemSize;
  13786. if ( this.normalized ) {
  13787. x = normalize( x, this.array );
  13788. y = normalize( y, this.array );
  13789. }
  13790. this.array[ index + 0 ] = x;
  13791. this.array[ index + 1 ] = y;
  13792. return this;
  13793. }
  13794. /**
  13795. * Sets the x, y and z component of the vector at the given index.
  13796. *
  13797. * @param {number} index - The index into the buffer attribute.
  13798. * @param {number} x - The value for the x component to set.
  13799. * @param {number} y - The value for the y component to set.
  13800. * @param {number} z - The value for the z component to set.
  13801. * @return {BufferAttribute} A reference to this instance.
  13802. */
  13803. setXYZ( index, x, y, z ) {
  13804. index *= this.itemSize;
  13805. if ( this.normalized ) {
  13806. x = normalize( x, this.array );
  13807. y = normalize( y, this.array );
  13808. z = normalize( z, this.array );
  13809. }
  13810. this.array[ index + 0 ] = x;
  13811. this.array[ index + 1 ] = y;
  13812. this.array[ index + 2 ] = z;
  13813. return this;
  13814. }
  13815. /**
  13816. * Sets the x, y, z and w component of the vector at the given index.
  13817. *
  13818. * @param {number} index - The index into the buffer attribute.
  13819. * @param {number} x - The value for the x component to set.
  13820. * @param {number} y - The value for the y component to set.
  13821. * @param {number} z - The value for the z component to set.
  13822. * @param {number} w - The value for the w component to set.
  13823. * @return {BufferAttribute} A reference to this instance.
  13824. */
  13825. setXYZW( index, x, y, z, w ) {
  13826. index *= this.itemSize;
  13827. if ( this.normalized ) {
  13828. x = normalize( x, this.array );
  13829. y = normalize( y, this.array );
  13830. z = normalize( z, this.array );
  13831. w = normalize( w, this.array );
  13832. }
  13833. this.array[ index + 0 ] = x;
  13834. this.array[ index + 1 ] = y;
  13835. this.array[ index + 2 ] = z;
  13836. this.array[ index + 3 ] = w;
  13837. return this;
  13838. }
  13839. /**
  13840. * Sets the given callback function that is executed after the Renderer has transferred
  13841. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  13842. * the upload when attribute data are not needed anymore on the CPU side.
  13843. *
  13844. * @param {Function} callback - The `onUpload()` callback.
  13845. * @return {BufferAttribute} A reference to this instance.
  13846. */
  13847. onUpload( callback ) {
  13848. this.onUploadCallback = callback;
  13849. return this;
  13850. }
  13851. /**
  13852. * Returns a new buffer attribute with copied values from this instance.
  13853. *
  13854. * @return {BufferAttribute} A clone of this instance.
  13855. */
  13856. clone() {
  13857. return new this.constructor( this.array, this.itemSize ).copy( this );
  13858. }
  13859. /**
  13860. * Serializes the buffer attribute into JSON.
  13861. *
  13862. * @return {Object} A JSON object representing the serialized buffer attribute.
  13863. */
  13864. toJSON() {
  13865. const data = {
  13866. itemSize: this.itemSize,
  13867. type: this.array.constructor.name,
  13868. array: Array.from( this.array ),
  13869. normalized: this.normalized
  13870. };
  13871. if ( this.name !== '' ) data.name = this.name;
  13872. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  13873. return data;
  13874. }
  13875. }
  13876. /**
  13877. * Convenient class that can be used when creating a `Int8` buffer attribute with
  13878. * a plain `Array` instance.
  13879. *
  13880. * @augments BufferAttribute
  13881. */
  13882. class Int8BufferAttribute extends BufferAttribute {
  13883. /**
  13884. * Constructs a new buffer attribute.
  13885. *
  13886. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  13887. * @param {number} itemSize - The item size.
  13888. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13889. */
  13890. constructor( array, itemSize, normalized ) {
  13891. super( new Int8Array( array ), itemSize, normalized );
  13892. }
  13893. }
  13894. /**
  13895. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  13896. * a plain `Array` instance.
  13897. *
  13898. * @augments BufferAttribute
  13899. */
  13900. class Uint8BufferAttribute extends BufferAttribute {
  13901. /**
  13902. * Constructs a new buffer attribute.
  13903. *
  13904. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  13905. * @param {number} itemSize - The item size.
  13906. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13907. */
  13908. constructor( array, itemSize, normalized ) {
  13909. super( new Uint8Array( array ), itemSize, normalized );
  13910. }
  13911. }
  13912. /**
  13913. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  13914. * a plain `Array` instance.
  13915. *
  13916. * @augments BufferAttribute
  13917. */
  13918. class Uint8ClampedBufferAttribute extends BufferAttribute {
  13919. /**
  13920. * Constructs a new buffer attribute.
  13921. *
  13922. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  13923. * @param {number} itemSize - The item size.
  13924. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13925. */
  13926. constructor( array, itemSize, normalized ) {
  13927. super( new Uint8ClampedArray( array ), itemSize, normalized );
  13928. }
  13929. }
  13930. /**
  13931. * Convenient class that can be used when creating a `Int16` buffer attribute with
  13932. * a plain `Array` instance.
  13933. *
  13934. * @augments BufferAttribute
  13935. */
  13936. class Int16BufferAttribute extends BufferAttribute {
  13937. /**
  13938. * Constructs a new buffer attribute.
  13939. *
  13940. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  13941. * @param {number} itemSize - The item size.
  13942. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13943. */
  13944. constructor( array, itemSize, normalized ) {
  13945. super( new Int16Array( array ), itemSize, normalized );
  13946. }
  13947. }
  13948. /**
  13949. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  13950. * a plain `Array` instance.
  13951. *
  13952. * @augments BufferAttribute
  13953. */
  13954. class Uint16BufferAttribute extends BufferAttribute {
  13955. /**
  13956. * Constructs a new buffer attribute.
  13957. *
  13958. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13959. * @param {number} itemSize - The item size.
  13960. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13961. */
  13962. constructor( array, itemSize, normalized ) {
  13963. super( new Uint16Array( array ), itemSize, normalized );
  13964. }
  13965. }
  13966. /**
  13967. * Convenient class that can be used when creating a `Int32` buffer attribute with
  13968. * a plain `Array` instance.
  13969. *
  13970. * @augments BufferAttribute
  13971. */
  13972. class Int32BufferAttribute extends BufferAttribute {
  13973. /**
  13974. * Constructs a new buffer attribute.
  13975. *
  13976. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  13977. * @param {number} itemSize - The item size.
  13978. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13979. */
  13980. constructor( array, itemSize, normalized ) {
  13981. super( new Int32Array( array ), itemSize, normalized );
  13982. }
  13983. }
  13984. /**
  13985. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  13986. * a plain `Array` instance.
  13987. *
  13988. * @augments BufferAttribute
  13989. */
  13990. class Uint32BufferAttribute extends BufferAttribute {
  13991. /**
  13992. * Constructs a new buffer attribute.
  13993. *
  13994. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  13995. * @param {number} itemSize - The item size.
  13996. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13997. */
  13998. constructor( array, itemSize, normalized ) {
  13999. super( new Uint32Array( array ), itemSize, normalized );
  14000. }
  14001. }
  14002. /**
  14003. * Convenient class that can be used when creating a `Float16` buffer attribute with
  14004. * a plain `Array` instance.
  14005. *
  14006. * This class automatically converts to and from FP16 via `Uint16Array` since `Float16Array`
  14007. * browser support is still problematic.
  14008. *
  14009. * @augments BufferAttribute
  14010. */
  14011. class Float16BufferAttribute extends BufferAttribute {
  14012. /**
  14013. * Constructs a new buffer attribute.
  14014. *
  14015. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14016. * @param {number} itemSize - The item size.
  14017. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14018. */
  14019. constructor( array, itemSize, normalized ) {
  14020. super( new Uint16Array( array ), itemSize, normalized );
  14021. this.isFloat16BufferAttribute = true;
  14022. }
  14023. getX( index ) {
  14024. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  14025. if ( this.normalized ) x = denormalize( x, this.array );
  14026. return x;
  14027. }
  14028. setX( index, x ) {
  14029. if ( this.normalized ) x = normalize( x, this.array );
  14030. this.array[ index * this.itemSize ] = toHalfFloat( x );
  14031. return this;
  14032. }
  14033. getY( index ) {
  14034. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  14035. if ( this.normalized ) y = denormalize( y, this.array );
  14036. return y;
  14037. }
  14038. setY( index, y ) {
  14039. if ( this.normalized ) y = normalize( y, this.array );
  14040. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  14041. return this;
  14042. }
  14043. getZ( index ) {
  14044. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  14045. if ( this.normalized ) z = denormalize( z, this.array );
  14046. return z;
  14047. }
  14048. setZ( index, z ) {
  14049. if ( this.normalized ) z = normalize( z, this.array );
  14050. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  14051. return this;
  14052. }
  14053. getW( index ) {
  14054. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  14055. if ( this.normalized ) w = denormalize( w, this.array );
  14056. return w;
  14057. }
  14058. setW( index, w ) {
  14059. if ( this.normalized ) w = normalize( w, this.array );
  14060. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  14061. return this;
  14062. }
  14063. setXY( index, x, y ) {
  14064. index *= this.itemSize;
  14065. if ( this.normalized ) {
  14066. x = normalize( x, this.array );
  14067. y = normalize( y, this.array );
  14068. }
  14069. this.array[ index + 0 ] = toHalfFloat( x );
  14070. this.array[ index + 1 ] = toHalfFloat( y );
  14071. return this;
  14072. }
  14073. setXYZ( index, x, y, z ) {
  14074. index *= this.itemSize;
  14075. if ( this.normalized ) {
  14076. x = normalize( x, this.array );
  14077. y = normalize( y, this.array );
  14078. z = normalize( z, this.array );
  14079. }
  14080. this.array[ index + 0 ] = toHalfFloat( x );
  14081. this.array[ index + 1 ] = toHalfFloat( y );
  14082. this.array[ index + 2 ] = toHalfFloat( z );
  14083. return this;
  14084. }
  14085. setXYZW( index, x, y, z, w ) {
  14086. index *= this.itemSize;
  14087. if ( this.normalized ) {
  14088. x = normalize( x, this.array );
  14089. y = normalize( y, this.array );
  14090. z = normalize( z, this.array );
  14091. w = normalize( w, this.array );
  14092. }
  14093. this.array[ index + 0 ] = toHalfFloat( x );
  14094. this.array[ index + 1 ] = toHalfFloat( y );
  14095. this.array[ index + 2 ] = toHalfFloat( z );
  14096. this.array[ index + 3 ] = toHalfFloat( w );
  14097. return this;
  14098. }
  14099. }
  14100. /**
  14101. * Convenient class that can be used when creating a `Float32` buffer attribute with
  14102. * a plain `Array` instance.
  14103. *
  14104. * @augments BufferAttribute
  14105. */
  14106. class Float32BufferAttribute extends BufferAttribute {
  14107. /**
  14108. * Constructs a new buffer attribute.
  14109. *
  14110. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  14111. * @param {number} itemSize - The item size.
  14112. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14113. */
  14114. constructor( array, itemSize, normalized ) {
  14115. super( new Float32Array( array ), itemSize, normalized );
  14116. }
  14117. }
  14118. let _id$2 = 0;
  14119. const _m1$2 = /*@__PURE__*/ new Matrix4();
  14120. const _obj = /*@__PURE__*/ new Object3D();
  14121. const _offset = /*@__PURE__*/ new Vector3();
  14122. const _box$2 = /*@__PURE__*/ new Box3();
  14123. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  14124. const _vector$8 = /*@__PURE__*/ new Vector3();
  14125. /**
  14126. * A representation of mesh, line, or point geometry. Includes vertex
  14127. * positions, face indices, normals, colors, UVs, and custom attributes
  14128. * within buffers, reducing the cost of passing all this data to the GPU.
  14129. *
  14130. * ```js
  14131. * const geometry = new THREE.BufferGeometry();
  14132. * // create a simple square shape. We duplicate the top left and bottom right
  14133. * // vertices because each vertex needs to appear once per triangle.
  14134. * const vertices = new Float32Array( [
  14135. * -1.0, -1.0, 1.0, // v0
  14136. * 1.0, -1.0, 1.0, // v1
  14137. * 1.0, 1.0, 1.0, // v2
  14138. *
  14139. * 1.0, 1.0, 1.0, // v3
  14140. * -1.0, 1.0, 1.0, // v4
  14141. * -1.0, -1.0, 1.0 // v5
  14142. * ] );
  14143. * // itemSize = 3 because there are 3 values (components) per vertex
  14144. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  14145. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  14146. * const mesh = new THREE.Mesh( geometry, material );
  14147. * ```
  14148. *
  14149. * @augments EventDispatcher
  14150. */
  14151. class BufferGeometry extends EventDispatcher {
  14152. /**
  14153. * Constructs a new geometry.
  14154. */
  14155. constructor() {
  14156. super();
  14157. /**
  14158. * This flag can be used for type testing.
  14159. *
  14160. * @type {boolean}
  14161. * @readonly
  14162. * @default true
  14163. */
  14164. this.isBufferGeometry = true;
  14165. /**
  14166. * The ID of the geometry.
  14167. *
  14168. * @name BufferGeometry#id
  14169. * @type {number}
  14170. * @readonly
  14171. */
  14172. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  14173. /**
  14174. * The UUID of the geometry.
  14175. *
  14176. * @type {string}
  14177. * @readonly
  14178. */
  14179. this.uuid = generateUUID();
  14180. /**
  14181. * The name of the geometry.
  14182. *
  14183. * @type {string}
  14184. */
  14185. this.name = '';
  14186. this.type = 'BufferGeometry';
  14187. /**
  14188. * Allows for vertices to be re-used across multiple triangles; this is
  14189. * called using "indexed triangles". Each triangle is associated with the
  14190. * indices of three vertices. This attribute therefore stores the index of
  14191. * each vertex for each triangular face. If this attribute is not set, the
  14192. * renderer assumes that each three contiguous positions represent a single triangle.
  14193. *
  14194. * @type {?BufferAttribute}
  14195. * @default null
  14196. */
  14197. this.index = null;
  14198. /**
  14199. * A (storage) buffer attribute which was generated with a compute shader and
  14200. * now defines indirect draw calls.
  14201. *
  14202. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14203. *
  14204. * @type {?BufferAttribute}
  14205. * @default null
  14206. */
  14207. this.indirect = null;
  14208. /**
  14209. * This dictionary has as id the name of the attribute to be set and as value
  14210. * the buffer attribute to set it to. Rather than accessing this property directly,
  14211. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  14212. *
  14213. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  14214. */
  14215. this.attributes = {};
  14216. /**
  14217. * This dictionary holds the morph targets of the geometry.
  14218. *
  14219. * Note: Once the geometry has been rendered, the morph attribute data cannot
  14220. * be changed. You will have to call `dispose()?, and create a new geometry instance.
  14221. *
  14222. * @type {Object}
  14223. */
  14224. this.morphAttributes = {};
  14225. /**
  14226. * Used to control the morph target behavior; when set to `true`, the morph
  14227. * target data is treated as relative offsets, rather than as absolute
  14228. * positions/normals.
  14229. *
  14230. * @type {boolean}
  14231. * @default false
  14232. */
  14233. this.morphTargetsRelative = false;
  14234. /**
  14235. * Split the geometry into groups, each of which will be rendered in a
  14236. * separate draw call. This allows an array of materials to be used with the geometry.
  14237. *
  14238. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  14239. *
  14240. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  14241. * indices, and must not leave vertices or indices unused.
  14242. *
  14243. * @type {Array<Object>}
  14244. */
  14245. this.groups = [];
  14246. /**
  14247. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  14248. *
  14249. * @type {Box3}
  14250. * @default null
  14251. */
  14252. this.boundingBox = null;
  14253. /**
  14254. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  14255. *
  14256. * @type {Sphere}
  14257. * @default null
  14258. */
  14259. this.boundingSphere = null;
  14260. /**
  14261. * Determines the part of the geometry to render. This should not be set directly,
  14262. * instead use `setDrawRange()`.
  14263. *
  14264. * @type {{start:number,count:number}}
  14265. */
  14266. this.drawRange = { start: 0, count: Infinity };
  14267. /**
  14268. * An object that can be used to store custom data about the geometry.
  14269. * It should not hold references to functions as these will not be cloned.
  14270. *
  14271. * @type {Object}
  14272. */
  14273. this.userData = {};
  14274. }
  14275. /**
  14276. * Returns the index of this geometry.
  14277. *
  14278. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  14279. */
  14280. getIndex() {
  14281. return this.index;
  14282. }
  14283. /**
  14284. * Sets the given index to this geometry.
  14285. *
  14286. * @param {Array<number>|BufferAttribute} index - The index to set.
  14287. * @return {BufferGeometry} A reference to this instance.
  14288. */
  14289. setIndex( index ) {
  14290. if ( Array.isArray( index ) ) {
  14291. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  14292. } else {
  14293. this.index = index;
  14294. }
  14295. return this;
  14296. }
  14297. /**
  14298. * Sets the given indirect attribute to this geometry.
  14299. *
  14300. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  14301. * @return {BufferGeometry} A reference to this instance.
  14302. */
  14303. setIndirect( indirect ) {
  14304. this.indirect = indirect;
  14305. return this;
  14306. }
  14307. /**
  14308. * Returns the indirect attribute of this geometry.
  14309. *
  14310. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  14311. */
  14312. getIndirect() {
  14313. return this.indirect;
  14314. }
  14315. /**
  14316. * Returns the buffer attribute for the given name.
  14317. *
  14318. * @param {string} name - The attribute name.
  14319. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  14320. * Returns `undefined` if not attribute has been found.
  14321. */
  14322. getAttribute( name ) {
  14323. return this.attributes[ name ];
  14324. }
  14325. /**
  14326. * Sets the given attribute for the given name.
  14327. *
  14328. * @param {string} name - The attribute name.
  14329. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  14330. * @return {BufferGeometry} A reference to this instance.
  14331. */
  14332. setAttribute( name, attribute ) {
  14333. this.attributes[ name ] = attribute;
  14334. return this;
  14335. }
  14336. /**
  14337. * Deletes the attribute for the given name.
  14338. *
  14339. * @param {string} name - The attribute name to delete.
  14340. * @return {BufferGeometry} A reference to this instance.
  14341. */
  14342. deleteAttribute( name ) {
  14343. delete this.attributes[ name ];
  14344. return this;
  14345. }
  14346. /**
  14347. * Returns `true` if this geometry has an attribute for the given name.
  14348. *
  14349. * @param {string} name - The attribute name.
  14350. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  14351. */
  14352. hasAttribute( name ) {
  14353. return this.attributes[ name ] !== undefined;
  14354. }
  14355. /**
  14356. * Adds a group to this geometry.
  14357. *
  14358. * @param {number} start - The first element in this draw call. That is the first
  14359. * vertex for non-indexed geometry, otherwise the first triangle index.
  14360. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  14361. * @param {number} [materialIndex=0] - The material array index to use.
  14362. */
  14363. addGroup( start, count, materialIndex = 0 ) {
  14364. this.groups.push( {
  14365. start: start,
  14366. count: count,
  14367. materialIndex: materialIndex
  14368. } );
  14369. }
  14370. /**
  14371. * Clears all groups.
  14372. */
  14373. clearGroups() {
  14374. this.groups = [];
  14375. }
  14376. /**
  14377. * Sets the draw range for this geometry.
  14378. *
  14379. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  14380. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  14381. * For indexed BufferGeometry, `count` is the number of indices to render.
  14382. */
  14383. setDrawRange( start, count ) {
  14384. this.drawRange.start = start;
  14385. this.drawRange.count = count;
  14386. }
  14387. /**
  14388. * Applies the given 4x4 transformation matrix to the geometry.
  14389. *
  14390. * @param {Matrix4} matrix - The matrix to apply.
  14391. * @return {BufferGeometry} A reference to this instance.
  14392. */
  14393. applyMatrix4( matrix ) {
  14394. const position = this.attributes.position;
  14395. if ( position !== undefined ) {
  14396. position.applyMatrix4( matrix );
  14397. position.needsUpdate = true;
  14398. }
  14399. const normal = this.attributes.normal;
  14400. if ( normal !== undefined ) {
  14401. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  14402. normal.applyNormalMatrix( normalMatrix );
  14403. normal.needsUpdate = true;
  14404. }
  14405. const tangent = this.attributes.tangent;
  14406. if ( tangent !== undefined ) {
  14407. tangent.transformDirection( matrix );
  14408. tangent.needsUpdate = true;
  14409. }
  14410. if ( this.boundingBox !== null ) {
  14411. this.computeBoundingBox();
  14412. }
  14413. if ( this.boundingSphere !== null ) {
  14414. this.computeBoundingSphere();
  14415. }
  14416. return this;
  14417. }
  14418. /**
  14419. * Applies the rotation represented by the Quaternion to the geometry.
  14420. *
  14421. * @param {Quaternion} q - The Quaternion to apply.
  14422. * @return {BufferGeometry} A reference to this instance.
  14423. */
  14424. applyQuaternion( q ) {
  14425. _m1$2.makeRotationFromQuaternion( q );
  14426. this.applyMatrix4( _m1$2 );
  14427. return this;
  14428. }
  14429. /**
  14430. * Rotates the geometry about the X axis. This is typically done as a one time
  14431. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14432. * real-time mesh rotation.
  14433. *
  14434. * @param {number} angle - The angle in radians.
  14435. * @return {BufferGeometry} A reference to this instance.
  14436. */
  14437. rotateX( angle ) {
  14438. // rotate geometry around world x-axis
  14439. _m1$2.makeRotationX( angle );
  14440. this.applyMatrix4( _m1$2 );
  14441. return this;
  14442. }
  14443. /**
  14444. * Rotates the geometry about the Y axis. This is typically done as a one time
  14445. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14446. * real-time mesh rotation.
  14447. *
  14448. * @param {number} angle - The angle in radians.
  14449. * @return {BufferGeometry} A reference to this instance.
  14450. */
  14451. rotateY( angle ) {
  14452. // rotate geometry around world y-axis
  14453. _m1$2.makeRotationY( angle );
  14454. this.applyMatrix4( _m1$2 );
  14455. return this;
  14456. }
  14457. /**
  14458. * Rotates the geometry about the Z axis. This is typically done as a one time
  14459. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14460. * real-time mesh rotation.
  14461. *
  14462. * @param {number} angle - The angle in radians.
  14463. * @return {BufferGeometry} A reference to this instance.
  14464. */
  14465. rotateZ( angle ) {
  14466. // rotate geometry around world z-axis
  14467. _m1$2.makeRotationZ( angle );
  14468. this.applyMatrix4( _m1$2 );
  14469. return this;
  14470. }
  14471. /**
  14472. * Translates the geometry. This is typically done as a one time
  14473. * operation, and not during a loop. Use {@link Object3D#position} for typical
  14474. * real-time mesh rotation.
  14475. *
  14476. * @param {number} x - The x offset.
  14477. * @param {number} y - The y offset.
  14478. * @param {number} z - The z offset.
  14479. * @return {BufferGeometry} A reference to this instance.
  14480. */
  14481. translate( x, y, z ) {
  14482. // translate geometry
  14483. _m1$2.makeTranslation( x, y, z );
  14484. this.applyMatrix4( _m1$2 );
  14485. return this;
  14486. }
  14487. /**
  14488. * Scales the geometry. This is typically done as a one time
  14489. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14490. * real-time mesh rotation.
  14491. *
  14492. * @param {number} x - The x scale.
  14493. * @param {number} y - The y scale.
  14494. * @param {number} z - The z scale.
  14495. * @return {BufferGeometry} A reference to this instance.
  14496. */
  14497. scale( x, y, z ) {
  14498. // scale geometry
  14499. _m1$2.makeScale( x, y, z );
  14500. this.applyMatrix4( _m1$2 );
  14501. return this;
  14502. }
  14503. /**
  14504. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14505. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14506. * real-time mesh rotation.
  14507. *
  14508. * @param {Vector3} vector - The target point.
  14509. * @return {BufferGeometry} A reference to this instance.
  14510. */
  14511. lookAt( vector ) {
  14512. _obj.lookAt( vector );
  14513. _obj.updateMatrix();
  14514. this.applyMatrix4( _obj.matrix );
  14515. return this;
  14516. }
  14517. /**
  14518. * Center the geometry based on its bounding box.
  14519. *
  14520. * @return {BufferGeometry} A reference to this instance.
  14521. */
  14522. center() {
  14523. this.computeBoundingBox();
  14524. this.boundingBox.getCenter( _offset ).negate();
  14525. this.translate( _offset.x, _offset.y, _offset.z );
  14526. return this;
  14527. }
  14528. /**
  14529. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14530. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14531. * set to `0`.
  14532. *
  14533. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14534. * data from the array. The length of the array must match the vertex count.
  14535. *
  14536. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14537. * @return {BufferGeometry} A reference to this instance.
  14538. */
  14539. setFromPoints( points ) {
  14540. const positionAttribute = this.getAttribute( 'position' );
  14541. if ( positionAttribute === undefined ) {
  14542. const position = [];
  14543. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14544. const point = points[ i ];
  14545. position.push( point.x, point.y, point.z || 0 );
  14546. }
  14547. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14548. } else {
  14549. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14550. for ( let i = 0; i < l; i ++ ) {
  14551. const point = points[ i ];
  14552. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14553. }
  14554. if ( points.length > positionAttribute.count ) {
  14555. console.warn( 'THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14556. }
  14557. positionAttribute.needsUpdate = true;
  14558. }
  14559. return this;
  14560. }
  14561. /**
  14562. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14563. * The bounding box is not computed by the engine; it must be computed by your app.
  14564. * You may need to recompute the bounding box if the geometry vertices are modified.
  14565. */
  14566. computeBoundingBox() {
  14567. if ( this.boundingBox === null ) {
  14568. this.boundingBox = new Box3();
  14569. }
  14570. const position = this.attributes.position;
  14571. const morphAttributesPosition = this.morphAttributes.position;
  14572. if ( position && position.isGLBufferAttribute ) {
  14573. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14574. this.boundingBox.set(
  14575. new Vector3( - Infinity, - Infinity, - Infinity ),
  14576. new Vector3( + Infinity, + Infinity, + Infinity )
  14577. );
  14578. return;
  14579. }
  14580. if ( position !== undefined ) {
  14581. this.boundingBox.setFromBufferAttribute( position );
  14582. // process morph attributes if present
  14583. if ( morphAttributesPosition ) {
  14584. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14585. const morphAttribute = morphAttributesPosition[ i ];
  14586. _box$2.setFromBufferAttribute( morphAttribute );
  14587. if ( this.morphTargetsRelative ) {
  14588. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  14589. this.boundingBox.expandByPoint( _vector$8 );
  14590. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  14591. this.boundingBox.expandByPoint( _vector$8 );
  14592. } else {
  14593. this.boundingBox.expandByPoint( _box$2.min );
  14594. this.boundingBox.expandByPoint( _box$2.max );
  14595. }
  14596. }
  14597. }
  14598. } else {
  14599. this.boundingBox.makeEmpty();
  14600. }
  14601. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14602. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14603. }
  14604. }
  14605. /**
  14606. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14607. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14608. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14609. */
  14610. computeBoundingSphere() {
  14611. if ( this.boundingSphere === null ) {
  14612. this.boundingSphere = new Sphere();
  14613. }
  14614. const position = this.attributes.position;
  14615. const morphAttributesPosition = this.morphAttributes.position;
  14616. if ( position && position.isGLBufferAttribute ) {
  14617. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14618. this.boundingSphere.set( new Vector3(), Infinity );
  14619. return;
  14620. }
  14621. if ( position ) {
  14622. // first, find the center of the bounding sphere
  14623. const center = this.boundingSphere.center;
  14624. _box$2.setFromBufferAttribute( position );
  14625. // process morph attributes if present
  14626. if ( morphAttributesPosition ) {
  14627. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14628. const morphAttribute = morphAttributesPosition[ i ];
  14629. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14630. if ( this.morphTargetsRelative ) {
  14631. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  14632. _box$2.expandByPoint( _vector$8 );
  14633. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  14634. _box$2.expandByPoint( _vector$8 );
  14635. } else {
  14636. _box$2.expandByPoint( _boxMorphTargets.min );
  14637. _box$2.expandByPoint( _boxMorphTargets.max );
  14638. }
  14639. }
  14640. }
  14641. _box$2.getCenter( center );
  14642. // second, try to find a boundingSphere with a radius smaller than the
  14643. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14644. let maxRadiusSq = 0;
  14645. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14646. _vector$8.fromBufferAttribute( position, i );
  14647. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14648. }
  14649. // process morph attributes if present
  14650. if ( morphAttributesPosition ) {
  14651. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14652. const morphAttribute = morphAttributesPosition[ i ];
  14653. const morphTargetsRelative = this.morphTargetsRelative;
  14654. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14655. _vector$8.fromBufferAttribute( morphAttribute, j );
  14656. if ( morphTargetsRelative ) {
  14657. _offset.fromBufferAttribute( position, j );
  14658. _vector$8.add( _offset );
  14659. }
  14660. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14661. }
  14662. }
  14663. }
  14664. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14665. if ( isNaN( this.boundingSphere.radius ) ) {
  14666. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14667. }
  14668. }
  14669. }
  14670. /**
  14671. * Calculates and adds a tangent attribute to this geometry.
  14672. *
  14673. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14674. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14675. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14676. */
  14677. computeTangents() {
  14678. const index = this.index;
  14679. const attributes = this.attributes;
  14680. // based on http://www.terathon.com/code/tangent.html
  14681. // (per vertex tangents)
  14682. if ( index === null ||
  14683. attributes.position === undefined ||
  14684. attributes.normal === undefined ||
  14685. attributes.uv === undefined ) {
  14686. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14687. return;
  14688. }
  14689. const positionAttribute = attributes.position;
  14690. const normalAttribute = attributes.normal;
  14691. const uvAttribute = attributes.uv;
  14692. if ( this.hasAttribute( 'tangent' ) === false ) {
  14693. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14694. }
  14695. const tangentAttribute = this.getAttribute( 'tangent' );
  14696. const tan1 = [], tan2 = [];
  14697. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14698. tan1[ i ] = new Vector3();
  14699. tan2[ i ] = new Vector3();
  14700. }
  14701. const vA = new Vector3(),
  14702. vB = new Vector3(),
  14703. vC = new Vector3(),
  14704. uvA = new Vector2(),
  14705. uvB = new Vector2(),
  14706. uvC = new Vector2(),
  14707. sdir = new Vector3(),
  14708. tdir = new Vector3();
  14709. function handleTriangle( a, b, c ) {
  14710. vA.fromBufferAttribute( positionAttribute, a );
  14711. vB.fromBufferAttribute( positionAttribute, b );
  14712. vC.fromBufferAttribute( positionAttribute, c );
  14713. uvA.fromBufferAttribute( uvAttribute, a );
  14714. uvB.fromBufferAttribute( uvAttribute, b );
  14715. uvC.fromBufferAttribute( uvAttribute, c );
  14716. vB.sub( vA );
  14717. vC.sub( vA );
  14718. uvB.sub( uvA );
  14719. uvC.sub( uvA );
  14720. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14721. // silently ignore degenerate uv triangles having coincident or colinear vertices
  14722. if ( ! isFinite( r ) ) return;
  14723. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  14724. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  14725. tan1[ a ].add( sdir );
  14726. tan1[ b ].add( sdir );
  14727. tan1[ c ].add( sdir );
  14728. tan2[ a ].add( tdir );
  14729. tan2[ b ].add( tdir );
  14730. tan2[ c ].add( tdir );
  14731. }
  14732. let groups = this.groups;
  14733. if ( groups.length === 0 ) {
  14734. groups = [ {
  14735. start: 0,
  14736. count: index.count
  14737. } ];
  14738. }
  14739. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14740. const group = groups[ i ];
  14741. const start = group.start;
  14742. const count = group.count;
  14743. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14744. handleTriangle(
  14745. index.getX( j + 0 ),
  14746. index.getX( j + 1 ),
  14747. index.getX( j + 2 )
  14748. );
  14749. }
  14750. }
  14751. const tmp = new Vector3(), tmp2 = new Vector3();
  14752. const n = new Vector3(), n2 = new Vector3();
  14753. function handleVertex( v ) {
  14754. n.fromBufferAttribute( normalAttribute, v );
  14755. n2.copy( n );
  14756. const t = tan1[ v ];
  14757. // Gram-Schmidt orthogonalize
  14758. tmp.copy( t );
  14759. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  14760. // Calculate handedness
  14761. tmp2.crossVectors( n2, t );
  14762. const test = tmp2.dot( tan2[ v ] );
  14763. const w = ( test < 0.0 ) ? -1 : 1.0;
  14764. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  14765. }
  14766. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14767. const group = groups[ i ];
  14768. const start = group.start;
  14769. const count = group.count;
  14770. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14771. handleVertex( index.getX( j + 0 ) );
  14772. handleVertex( index.getX( j + 1 ) );
  14773. handleVertex( index.getX( j + 2 ) );
  14774. }
  14775. }
  14776. }
  14777. /**
  14778. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  14779. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  14780. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  14781. * to be the same as the face normal.
  14782. */
  14783. computeVertexNormals() {
  14784. const index = this.index;
  14785. const positionAttribute = this.getAttribute( 'position' );
  14786. if ( positionAttribute !== undefined ) {
  14787. let normalAttribute = this.getAttribute( 'normal' );
  14788. if ( normalAttribute === undefined ) {
  14789. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  14790. this.setAttribute( 'normal', normalAttribute );
  14791. } else {
  14792. // reset existing normals to zero
  14793. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  14794. normalAttribute.setXYZ( i, 0, 0, 0 );
  14795. }
  14796. }
  14797. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  14798. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  14799. const cb = new Vector3(), ab = new Vector3();
  14800. // indexed elements
  14801. if ( index ) {
  14802. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  14803. const vA = index.getX( i + 0 );
  14804. const vB = index.getX( i + 1 );
  14805. const vC = index.getX( i + 2 );
  14806. pA.fromBufferAttribute( positionAttribute, vA );
  14807. pB.fromBufferAttribute( positionAttribute, vB );
  14808. pC.fromBufferAttribute( positionAttribute, vC );
  14809. cb.subVectors( pC, pB );
  14810. ab.subVectors( pA, pB );
  14811. cb.cross( ab );
  14812. nA.fromBufferAttribute( normalAttribute, vA );
  14813. nB.fromBufferAttribute( normalAttribute, vB );
  14814. nC.fromBufferAttribute( normalAttribute, vC );
  14815. nA.add( cb );
  14816. nB.add( cb );
  14817. nC.add( cb );
  14818. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  14819. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  14820. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  14821. }
  14822. } else {
  14823. // non-indexed elements (unconnected triangle soup)
  14824. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  14825. pA.fromBufferAttribute( positionAttribute, i + 0 );
  14826. pB.fromBufferAttribute( positionAttribute, i + 1 );
  14827. pC.fromBufferAttribute( positionAttribute, i + 2 );
  14828. cb.subVectors( pC, pB );
  14829. ab.subVectors( pA, pB );
  14830. cb.cross( ab );
  14831. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  14832. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  14833. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  14834. }
  14835. }
  14836. this.normalizeNormals();
  14837. normalAttribute.needsUpdate = true;
  14838. }
  14839. }
  14840. /**
  14841. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  14842. * correct lighting on the geometry surfaces.
  14843. */
  14844. normalizeNormals() {
  14845. const normals = this.attributes.normal;
  14846. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  14847. _vector$8.fromBufferAttribute( normals, i );
  14848. _vector$8.normalize();
  14849. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14850. }
  14851. }
  14852. /**
  14853. * Return a new non-index version of this indexed geometry. If the geometry
  14854. * is already non-indexed, the method is a NOOP.
  14855. *
  14856. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  14857. */
  14858. toNonIndexed() {
  14859. function convertBufferAttribute( attribute, indices ) {
  14860. const array = attribute.array;
  14861. const itemSize = attribute.itemSize;
  14862. const normalized = attribute.normalized;
  14863. const array2 = new array.constructor( indices.length * itemSize );
  14864. let index = 0, index2 = 0;
  14865. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  14866. if ( attribute.isInterleavedBufferAttribute ) {
  14867. index = indices[ i ] * attribute.data.stride + attribute.offset;
  14868. } else {
  14869. index = indices[ i ] * itemSize;
  14870. }
  14871. for ( let j = 0; j < itemSize; j ++ ) {
  14872. array2[ index2 ++ ] = array[ index ++ ];
  14873. }
  14874. }
  14875. return new BufferAttribute( array2, itemSize, normalized );
  14876. }
  14877. //
  14878. if ( this.index === null ) {
  14879. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  14880. return this;
  14881. }
  14882. const geometry2 = new BufferGeometry();
  14883. const indices = this.index.array;
  14884. const attributes = this.attributes;
  14885. // attributes
  14886. for ( const name in attributes ) {
  14887. const attribute = attributes[ name ];
  14888. const newAttribute = convertBufferAttribute( attribute, indices );
  14889. geometry2.setAttribute( name, newAttribute );
  14890. }
  14891. // morph attributes
  14892. const morphAttributes = this.morphAttributes;
  14893. for ( const name in morphAttributes ) {
  14894. const morphArray = [];
  14895. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14896. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  14897. const attribute = morphAttribute[ i ];
  14898. const newAttribute = convertBufferAttribute( attribute, indices );
  14899. morphArray.push( newAttribute );
  14900. }
  14901. geometry2.morphAttributes[ name ] = morphArray;
  14902. }
  14903. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  14904. // groups
  14905. const groups = this.groups;
  14906. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14907. const group = groups[ i ];
  14908. geometry2.addGroup( group.start, group.count, group.materialIndex );
  14909. }
  14910. return geometry2;
  14911. }
  14912. /**
  14913. * Serializes the geometry into JSON.
  14914. *
  14915. * @return {Object} A JSON object representing the serialized geometry.
  14916. */
  14917. toJSON() {
  14918. const data = {
  14919. metadata: {
  14920. version: 4.7,
  14921. type: 'BufferGeometry',
  14922. generator: 'BufferGeometry.toJSON'
  14923. }
  14924. };
  14925. // standard BufferGeometry serialization
  14926. data.uuid = this.uuid;
  14927. data.type = this.type;
  14928. if ( this.name !== '' ) data.name = this.name;
  14929. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  14930. if ( this.parameters !== undefined ) {
  14931. const parameters = this.parameters;
  14932. for ( const key in parameters ) {
  14933. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  14934. }
  14935. return data;
  14936. }
  14937. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  14938. data.data = { attributes: {} };
  14939. const index = this.index;
  14940. if ( index !== null ) {
  14941. data.data.index = {
  14942. type: index.array.constructor.name,
  14943. array: Array.prototype.slice.call( index.array )
  14944. };
  14945. }
  14946. const attributes = this.attributes;
  14947. for ( const key in attributes ) {
  14948. const attribute = attributes[ key ];
  14949. data.data.attributes[ key ] = attribute.toJSON( data.data );
  14950. }
  14951. const morphAttributes = {};
  14952. let hasMorphAttributes = false;
  14953. for ( const key in this.morphAttributes ) {
  14954. const attributeArray = this.morphAttributes[ key ];
  14955. const array = [];
  14956. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  14957. const attribute = attributeArray[ i ];
  14958. array.push( attribute.toJSON( data.data ) );
  14959. }
  14960. if ( array.length > 0 ) {
  14961. morphAttributes[ key ] = array;
  14962. hasMorphAttributes = true;
  14963. }
  14964. }
  14965. if ( hasMorphAttributes ) {
  14966. data.data.morphAttributes = morphAttributes;
  14967. data.data.morphTargetsRelative = this.morphTargetsRelative;
  14968. }
  14969. const groups = this.groups;
  14970. if ( groups.length > 0 ) {
  14971. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  14972. }
  14973. const boundingSphere = this.boundingSphere;
  14974. if ( boundingSphere !== null ) {
  14975. data.data.boundingSphere = boundingSphere.toJSON();
  14976. }
  14977. return data;
  14978. }
  14979. /**
  14980. * Returns a new geometry with copied values from this instance.
  14981. *
  14982. * @return {BufferGeometry} A clone of this instance.
  14983. */
  14984. clone() {
  14985. return new this.constructor().copy( this );
  14986. }
  14987. /**
  14988. * Copies the values of the given geometry to this instance.
  14989. *
  14990. * @param {BufferGeometry} source - The geometry to copy.
  14991. * @return {BufferGeometry} A reference to this instance.
  14992. */
  14993. copy( source ) {
  14994. // reset
  14995. this.index = null;
  14996. this.attributes = {};
  14997. this.morphAttributes = {};
  14998. this.groups = [];
  14999. this.boundingBox = null;
  15000. this.boundingSphere = null;
  15001. // used for storing cloned, shared data
  15002. const data = {};
  15003. // name
  15004. this.name = source.name;
  15005. // index
  15006. const index = source.index;
  15007. if ( index !== null ) {
  15008. this.setIndex( index.clone() );
  15009. }
  15010. // attributes
  15011. const attributes = source.attributes;
  15012. for ( const name in attributes ) {
  15013. const attribute = attributes[ name ];
  15014. this.setAttribute( name, attribute.clone( data ) );
  15015. }
  15016. // morph attributes
  15017. const morphAttributes = source.morphAttributes;
  15018. for ( const name in morphAttributes ) {
  15019. const array = [];
  15020. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  15021. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  15022. array.push( morphAttribute[ i ].clone( data ) );
  15023. }
  15024. this.morphAttributes[ name ] = array;
  15025. }
  15026. this.morphTargetsRelative = source.morphTargetsRelative;
  15027. // groups
  15028. const groups = source.groups;
  15029. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15030. const group = groups[ i ];
  15031. this.addGroup( group.start, group.count, group.materialIndex );
  15032. }
  15033. // bounding box
  15034. const boundingBox = source.boundingBox;
  15035. if ( boundingBox !== null ) {
  15036. this.boundingBox = boundingBox.clone();
  15037. }
  15038. // bounding sphere
  15039. const boundingSphere = source.boundingSphere;
  15040. if ( boundingSphere !== null ) {
  15041. this.boundingSphere = boundingSphere.clone();
  15042. }
  15043. // draw range
  15044. this.drawRange.start = source.drawRange.start;
  15045. this.drawRange.count = source.drawRange.count;
  15046. // user data
  15047. this.userData = source.userData;
  15048. return this;
  15049. }
  15050. /**
  15051. * Frees the GPU-related resources allocated by this instance. Call this
  15052. * method whenever this instance is no longer used in your app.
  15053. *
  15054. * @fires BufferGeometry#dispose
  15055. */
  15056. dispose() {
  15057. this.dispatchEvent( { type: 'dispose' } );
  15058. }
  15059. }
  15060. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  15061. const _ray$3 = /*@__PURE__*/ new Ray();
  15062. const _sphere$6 = /*@__PURE__*/ new Sphere();
  15063. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  15064. const _vA$1 = /*@__PURE__*/ new Vector3();
  15065. const _vB$1 = /*@__PURE__*/ new Vector3();
  15066. const _vC$1 = /*@__PURE__*/ new Vector3();
  15067. const _tempA = /*@__PURE__*/ new Vector3();
  15068. const _morphA = /*@__PURE__*/ new Vector3();
  15069. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  15070. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  15071. /**
  15072. * Class representing triangular polygon mesh based objects.
  15073. *
  15074. * ```js
  15075. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15076. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  15077. * const mesh = new THREE.Mesh( geometry, material );
  15078. * scene.add( mesh );
  15079. * ```
  15080. *
  15081. * @augments Object3D
  15082. */
  15083. class Mesh extends Object3D {
  15084. /**
  15085. * Constructs a new mesh.
  15086. *
  15087. * @param {BufferGeometry} [geometry] - The mesh geometry.
  15088. * @param {Material|Array<Material>} [material] - The mesh material.
  15089. */
  15090. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  15091. super();
  15092. /**
  15093. * This flag can be used for type testing.
  15094. *
  15095. * @type {boolean}
  15096. * @readonly
  15097. * @default true
  15098. */
  15099. this.isMesh = true;
  15100. this.type = 'Mesh';
  15101. /**
  15102. * The mesh geometry.
  15103. *
  15104. * @type {BufferGeometry}
  15105. */
  15106. this.geometry = geometry;
  15107. /**
  15108. * The mesh material.
  15109. *
  15110. * @type {Material|Array<Material>}
  15111. * @default MeshBasicMaterial
  15112. */
  15113. this.material = material;
  15114. /**
  15115. * A dictionary representing the morph targets in the geometry. The key is the
  15116. * morph targets name, the value its attribute index. This member is `undefined`
  15117. * by default and only set when morph targets are detected in the geometry.
  15118. *
  15119. * @type {Object<String,number>|undefined}
  15120. * @default undefined
  15121. */
  15122. this.morphTargetDictionary = undefined;
  15123. /**
  15124. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  15125. * is applied. This member is `undefined` by default and only set when morph targets are
  15126. * detected in the geometry.
  15127. *
  15128. * @type {Array<number>|undefined}
  15129. * @default undefined
  15130. */
  15131. this.morphTargetInfluences = undefined;
  15132. /**
  15133. * The number of instances of this mesh.
  15134. * Can only be used with {@link WebGPURenderer}.
  15135. *
  15136. * @type {number}
  15137. * @default 1
  15138. */
  15139. this.count = 1;
  15140. this.updateMorphTargets();
  15141. }
  15142. copy( source, recursive ) {
  15143. super.copy( source, recursive );
  15144. if ( source.morphTargetInfluences !== undefined ) {
  15145. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  15146. }
  15147. if ( source.morphTargetDictionary !== undefined ) {
  15148. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  15149. }
  15150. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  15151. this.geometry = source.geometry;
  15152. return this;
  15153. }
  15154. /**
  15155. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  15156. * to make sure existing morph targets can influence this 3D object.
  15157. */
  15158. updateMorphTargets() {
  15159. const geometry = this.geometry;
  15160. const morphAttributes = geometry.morphAttributes;
  15161. const keys = Object.keys( morphAttributes );
  15162. if ( keys.length > 0 ) {
  15163. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  15164. if ( morphAttribute !== undefined ) {
  15165. this.morphTargetInfluences = [];
  15166. this.morphTargetDictionary = {};
  15167. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  15168. const name = morphAttribute[ m ].name || String( m );
  15169. this.morphTargetInfluences.push( 0 );
  15170. this.morphTargetDictionary[ name ] = m;
  15171. }
  15172. }
  15173. }
  15174. }
  15175. /**
  15176. * Returns the local-space position of the vertex at the given index, taking into
  15177. * account the current animation state of both morph targets and skinning.
  15178. *
  15179. * @param {number} index - The vertex index.
  15180. * @param {Vector3} target - The target object that is used to store the method's result.
  15181. * @return {Vector3} The vertex position in local space.
  15182. */
  15183. getVertexPosition( index, target ) {
  15184. const geometry = this.geometry;
  15185. const position = geometry.attributes.position;
  15186. const morphPosition = geometry.morphAttributes.position;
  15187. const morphTargetsRelative = geometry.morphTargetsRelative;
  15188. target.fromBufferAttribute( position, index );
  15189. const morphInfluences = this.morphTargetInfluences;
  15190. if ( morphPosition && morphInfluences ) {
  15191. _morphA.set( 0, 0, 0 );
  15192. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  15193. const influence = morphInfluences[ i ];
  15194. const morphAttribute = morphPosition[ i ];
  15195. if ( influence === 0 ) continue;
  15196. _tempA.fromBufferAttribute( morphAttribute, index );
  15197. if ( morphTargetsRelative ) {
  15198. _morphA.addScaledVector( _tempA, influence );
  15199. } else {
  15200. _morphA.addScaledVector( _tempA.sub( target ), influence );
  15201. }
  15202. }
  15203. target.add( _morphA );
  15204. }
  15205. return target;
  15206. }
  15207. /**
  15208. * Computes intersection points between a casted ray and this line.
  15209. *
  15210. * @param {Raycaster} raycaster - The raycaster.
  15211. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  15212. */
  15213. raycast( raycaster, intersects ) {
  15214. const geometry = this.geometry;
  15215. const material = this.material;
  15216. const matrixWorld = this.matrixWorld;
  15217. if ( material === undefined ) return;
  15218. // test with bounding sphere in world space
  15219. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15220. _sphere$6.copy( geometry.boundingSphere );
  15221. _sphere$6.applyMatrix4( matrixWorld );
  15222. // check distance from ray origin to bounding sphere
  15223. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  15224. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  15225. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  15226. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  15227. }
  15228. // convert ray to local space of mesh
  15229. _inverseMatrix$3.copy( matrixWorld ).invert();
  15230. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  15231. // test with bounding box in local space
  15232. if ( geometry.boundingBox !== null ) {
  15233. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  15234. }
  15235. // test for intersections with geometry
  15236. this._computeIntersections( raycaster, intersects, _ray$3 );
  15237. }
  15238. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  15239. let intersection;
  15240. const geometry = this.geometry;
  15241. const material = this.material;
  15242. const index = geometry.index;
  15243. const position = geometry.attributes.position;
  15244. const uv = geometry.attributes.uv;
  15245. const uv1 = geometry.attributes.uv1;
  15246. const normal = geometry.attributes.normal;
  15247. const groups = geometry.groups;
  15248. const drawRange = geometry.drawRange;
  15249. if ( index !== null ) {
  15250. // indexed buffer geometry
  15251. if ( Array.isArray( material ) ) {
  15252. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15253. const group = groups[ i ];
  15254. const groupMaterial = material[ group.materialIndex ];
  15255. const start = Math.max( group.start, drawRange.start );
  15256. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15257. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15258. const a = index.getX( j );
  15259. const b = index.getX( j + 1 );
  15260. const c = index.getX( j + 2 );
  15261. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15262. if ( intersection ) {
  15263. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  15264. intersection.face.materialIndex = group.materialIndex;
  15265. intersects.push( intersection );
  15266. }
  15267. }
  15268. }
  15269. } else {
  15270. const start = Math.max( 0, drawRange.start );
  15271. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15272. for ( let i = start, il = end; i < il; i += 3 ) {
  15273. const a = index.getX( i );
  15274. const b = index.getX( i + 1 );
  15275. const c = index.getX( i + 2 );
  15276. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15277. if ( intersection ) {
  15278. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  15279. intersects.push( intersection );
  15280. }
  15281. }
  15282. }
  15283. } else if ( position !== undefined ) {
  15284. // non-indexed buffer geometry
  15285. if ( Array.isArray( material ) ) {
  15286. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15287. const group = groups[ i ];
  15288. const groupMaterial = material[ group.materialIndex ];
  15289. const start = Math.max( group.start, drawRange.start );
  15290. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15291. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15292. const a = j;
  15293. const b = j + 1;
  15294. const c = j + 2;
  15295. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15296. if ( intersection ) {
  15297. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  15298. intersection.face.materialIndex = group.materialIndex;
  15299. intersects.push( intersection );
  15300. }
  15301. }
  15302. }
  15303. } else {
  15304. const start = Math.max( 0, drawRange.start );
  15305. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  15306. for ( let i = start, il = end; i < il; i += 3 ) {
  15307. const a = i;
  15308. const b = i + 1;
  15309. const c = i + 2;
  15310. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15311. if ( intersection ) {
  15312. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  15313. intersects.push( intersection );
  15314. }
  15315. }
  15316. }
  15317. }
  15318. }
  15319. }
  15320. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  15321. let intersect;
  15322. if ( material.side === BackSide ) {
  15323. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  15324. } else {
  15325. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  15326. }
  15327. if ( intersect === null ) return null;
  15328. _intersectionPointWorld.copy( point );
  15329. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  15330. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  15331. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  15332. return {
  15333. distance: distance,
  15334. point: _intersectionPointWorld.clone(),
  15335. object: object
  15336. };
  15337. }
  15338. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  15339. object.getVertexPosition( a, _vA$1 );
  15340. object.getVertexPosition( b, _vB$1 );
  15341. object.getVertexPosition( c, _vC$1 );
  15342. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  15343. if ( intersection ) {
  15344. const barycoord = new Vector3();
  15345. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  15346. if ( uv ) {
  15347. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  15348. }
  15349. if ( uv1 ) {
  15350. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  15351. }
  15352. if ( normal ) {
  15353. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  15354. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  15355. intersection.normal.multiplyScalar( -1 );
  15356. }
  15357. }
  15358. const face = {
  15359. a: a,
  15360. b: b,
  15361. c: c,
  15362. normal: new Vector3(),
  15363. materialIndex: 0
  15364. };
  15365. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  15366. intersection.face = face;
  15367. intersection.barycoord = barycoord;
  15368. }
  15369. return intersection;
  15370. }
  15371. /**
  15372. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  15373. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  15374. * of the axes.
  15375. *
  15376. * ```js
  15377. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15378. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  15379. * const cube = new THREE.Mesh( geometry, material );
  15380. * scene.add( cube );
  15381. * ```
  15382. *
  15383. * @augments BufferGeometry
  15384. */
  15385. class BoxGeometry extends BufferGeometry {
  15386. /**
  15387. * Constructs a new box geometry.
  15388. *
  15389. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  15390. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  15391. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  15392. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  15393. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  15394. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  15395. */
  15396. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  15397. super();
  15398. this.type = 'BoxGeometry';
  15399. /**
  15400. * Holds the constructor parameters that have been
  15401. * used to generate the geometry. Any modification
  15402. * after instantiation does not change the geometry.
  15403. *
  15404. * @type {Object}
  15405. */
  15406. this.parameters = {
  15407. width: width,
  15408. height: height,
  15409. depth: depth,
  15410. widthSegments: widthSegments,
  15411. heightSegments: heightSegments,
  15412. depthSegments: depthSegments
  15413. };
  15414. const scope = this;
  15415. // segments
  15416. widthSegments = Math.floor( widthSegments );
  15417. heightSegments = Math.floor( heightSegments );
  15418. depthSegments = Math.floor( depthSegments );
  15419. // buffers
  15420. const indices = [];
  15421. const vertices = [];
  15422. const normals = [];
  15423. const uvs = [];
  15424. // helper variables
  15425. let numberOfVertices = 0;
  15426. let groupStart = 0;
  15427. // build each side of the box geometry
  15428. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  15429. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  15430. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  15431. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  15432. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  15433. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  15434. // build geometry
  15435. this.setIndex( indices );
  15436. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15437. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15438. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15439. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  15440. const segmentWidth = width / gridX;
  15441. const segmentHeight = height / gridY;
  15442. const widthHalf = width / 2;
  15443. const heightHalf = height / 2;
  15444. const depthHalf = depth / 2;
  15445. const gridX1 = gridX + 1;
  15446. const gridY1 = gridY + 1;
  15447. let vertexCounter = 0;
  15448. let groupCount = 0;
  15449. const vector = new Vector3();
  15450. // generate vertices, normals and uvs
  15451. for ( let iy = 0; iy < gridY1; iy ++ ) {
  15452. const y = iy * segmentHeight - heightHalf;
  15453. for ( let ix = 0; ix < gridX1; ix ++ ) {
  15454. const x = ix * segmentWidth - widthHalf;
  15455. // set values to correct vector component
  15456. vector[ u ] = x * udir;
  15457. vector[ v ] = y * vdir;
  15458. vector[ w ] = depthHalf;
  15459. // now apply vector to vertex buffer
  15460. vertices.push( vector.x, vector.y, vector.z );
  15461. // set values to correct vector component
  15462. vector[ u ] = 0;
  15463. vector[ v ] = 0;
  15464. vector[ w ] = depth > 0 ? 1 : -1;
  15465. // now apply vector to normal buffer
  15466. normals.push( vector.x, vector.y, vector.z );
  15467. // uvs
  15468. uvs.push( ix / gridX );
  15469. uvs.push( 1 - ( iy / gridY ) );
  15470. // counters
  15471. vertexCounter += 1;
  15472. }
  15473. }
  15474. // indices
  15475. // 1. you need three indices to draw a single face
  15476. // 2. a single segment consists of two faces
  15477. // 3. so we need to generate six (2*3) indices per segment
  15478. for ( let iy = 0; iy < gridY; iy ++ ) {
  15479. for ( let ix = 0; ix < gridX; ix ++ ) {
  15480. const a = numberOfVertices + ix + gridX1 * iy;
  15481. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  15482. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  15483. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  15484. // faces
  15485. indices.push( a, b, d );
  15486. indices.push( b, c, d );
  15487. // increase counter
  15488. groupCount += 6;
  15489. }
  15490. }
  15491. // add a group to the geometry. this will ensure multi material support
  15492. scope.addGroup( groupStart, groupCount, materialIndex );
  15493. // calculate new start value for groups
  15494. groupStart += groupCount;
  15495. // update total number of vertices
  15496. numberOfVertices += vertexCounter;
  15497. }
  15498. }
  15499. copy( source ) {
  15500. super.copy( source );
  15501. this.parameters = Object.assign( {}, source.parameters );
  15502. return this;
  15503. }
  15504. /**
  15505. * Factory method for creating an instance of this class from the given
  15506. * JSON object.
  15507. *
  15508. * @param {Object} data - A JSON object representing the serialized geometry.
  15509. * @return {BoxGeometry} A new instance.
  15510. */
  15511. static fromJSON( data ) {
  15512. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  15513. }
  15514. }
  15515. // Uniform Utilities
  15516. function cloneUniforms( src ) {
  15517. const dst = {};
  15518. for ( const u in src ) {
  15519. dst[ u ] = {};
  15520. for ( const p in src[ u ] ) {
  15521. const property = src[ u ][ p ];
  15522. if ( property && ( property.isColor ||
  15523. property.isMatrix3 || property.isMatrix4 ||
  15524. property.isVector2 || property.isVector3 || property.isVector4 ||
  15525. property.isTexture || property.isQuaternion ) ) {
  15526. if ( property.isRenderTargetTexture ) {
  15527. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  15528. dst[ u ][ p ] = null;
  15529. } else {
  15530. dst[ u ][ p ] = property.clone();
  15531. }
  15532. } else if ( Array.isArray( property ) ) {
  15533. dst[ u ][ p ] = property.slice();
  15534. } else {
  15535. dst[ u ][ p ] = property;
  15536. }
  15537. }
  15538. }
  15539. return dst;
  15540. }
  15541. function mergeUniforms( uniforms ) {
  15542. const merged = {};
  15543. for ( let u = 0; u < uniforms.length; u ++ ) {
  15544. const tmp = cloneUniforms( uniforms[ u ] );
  15545. for ( const p in tmp ) {
  15546. merged[ p ] = tmp[ p ];
  15547. }
  15548. }
  15549. return merged;
  15550. }
  15551. function cloneUniformsGroups( src ) {
  15552. const dst = [];
  15553. for ( let u = 0; u < src.length; u ++ ) {
  15554. dst.push( src[ u ].clone() );
  15555. }
  15556. return dst;
  15557. }
  15558. function getUnlitUniformColorSpace( renderer ) {
  15559. const currentRenderTarget = renderer.getRenderTarget();
  15560. if ( currentRenderTarget === null ) {
  15561. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  15562. return renderer.outputColorSpace;
  15563. }
  15564. // https://github.com/mrdoob/three.js/issues/27868
  15565. if ( currentRenderTarget.isXRRenderTarget === true ) {
  15566. return currentRenderTarget.texture.colorSpace;
  15567. }
  15568. return ColorManagement.workingColorSpace;
  15569. }
  15570. // Legacy
  15571. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  15572. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  15573. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  15574. /**
  15575. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  15576. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  15577. * effect not included with any of the built-in materials.
  15578. *
  15579. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  15580. *
  15581. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  15582. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  15583. * you don't want that, use {@link RawShaderMaterial} instead.
  15584. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  15585. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  15586. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  15587. * - The loop has to be [normalized]{@link https://en.wikipedia.org/wiki/Normalized_loop}.
  15588. * - The loop variable has to be *i*.
  15589. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  15590. * value of *i* for the given iteration and can be used in preprocessor
  15591. * statements.
  15592. *
  15593. * ```js
  15594. * const material = new THREE.ShaderMaterial( {
  15595. * uniforms: {
  15596. * time: { value: 1.0 },
  15597. * resolution: { value: new THREE.Vector2() }
  15598. * },
  15599. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  15600. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  15601. * } );
  15602. * ```
  15603. *
  15604. * @augments Material
  15605. */
  15606. class ShaderMaterial extends Material {
  15607. /**
  15608. * Constructs a new shader material.
  15609. *
  15610. * @param {Object} [parameters] - An object with one or more properties
  15611. * defining the material's appearance. Any property of the material
  15612. * (including any property from inherited materials) can be passed
  15613. * in here. Color values can be passed any type of value accepted
  15614. * by {@link Color#set}.
  15615. */
  15616. constructor( parameters ) {
  15617. super();
  15618. /**
  15619. * This flag can be used for type testing.
  15620. *
  15621. * @type {boolean}
  15622. * @readonly
  15623. * @default true
  15624. */
  15625. this.isShaderMaterial = true;
  15626. this.type = 'ShaderMaterial';
  15627. /**
  15628. * Defines custom constants using `#define` directives within the GLSL code
  15629. * for both the vertex shader and the fragment shader; each key/value pair
  15630. * yields another directive.
  15631. * ```js
  15632. * defines: {
  15633. * FOO: 15,
  15634. * BAR: true
  15635. * }
  15636. * ```
  15637. * Yields the lines:
  15638. * ```
  15639. * #define FOO 15
  15640. * #define BAR true
  15641. * ```
  15642. *
  15643. * @type {Object}
  15644. */
  15645. this.defines = {};
  15646. /**
  15647. * An object of the form:
  15648. * ```js
  15649. * {
  15650. * "uniform1": { value: 1.0 },
  15651. * "uniform2": { value: 2 }
  15652. * }
  15653. * ```
  15654. * specifying the uniforms to be passed to the shader code; keys are uniform
  15655. * names, values are definitions of the form
  15656. * ```
  15657. * {
  15658. * value: 1.0
  15659. * }
  15660. * ```
  15661. * where `value` is the value of the uniform. Names must match the name of
  15662. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  15663. * on every frame, so updating the value of the uniform will immediately
  15664. * update the value available to the GLSL code.
  15665. *
  15666. * @type {Object}
  15667. */
  15668. this.uniforms = {};
  15669. /**
  15670. * An array holding uniforms groups for configuring UBOs.
  15671. *
  15672. * @type {Array<UniformsGroup>}
  15673. */
  15674. this.uniformsGroups = [];
  15675. /**
  15676. * Vertex shader GLSL code. This is the actual code for the shader.
  15677. *
  15678. * @type {string}
  15679. */
  15680. this.vertexShader = default_vertex;
  15681. /**
  15682. * Fragment shader GLSL code. This is the actual code for the shader.
  15683. *
  15684. * @type {string}
  15685. */
  15686. this.fragmentShader = default_fragment;
  15687. /**
  15688. * Controls line thickness or lines.
  15689. *
  15690. * WebGL and WebGPU ignore this setting and always render line primitives with a
  15691. * width of one pixel.
  15692. *
  15693. * @type {number}
  15694. * @default 1
  15695. */
  15696. this.linewidth = 1;
  15697. /**
  15698. * Renders the geometry as a wireframe.
  15699. *
  15700. * @type {boolean}
  15701. * @default false
  15702. */
  15703. this.wireframe = false;
  15704. /**
  15705. * Controls the thickness of the wireframe.
  15706. *
  15707. * WebGL and WebGPU ignore this property and always render
  15708. * 1 pixel wide lines.
  15709. *
  15710. * @type {number}
  15711. * @default 1
  15712. */
  15713. this.wireframeLinewidth = 1;
  15714. /**
  15715. * Define whether the material color is affected by global fog settings; `true`
  15716. * to pass fog uniforms to the shader.
  15717. *
  15718. * @type {boolean}
  15719. * @default false
  15720. */
  15721. this.fog = false;
  15722. /**
  15723. * Defines whether this material uses lighting; `true` to pass uniform data
  15724. * related to lighting to this shader.
  15725. *
  15726. * @type {boolean}
  15727. * @default false
  15728. */
  15729. this.lights = false;
  15730. /**
  15731. * Defines whether this material supports clipping; `true` to let the renderer
  15732. * pass the clippingPlanes uniform.
  15733. *
  15734. * @type {boolean}
  15735. * @default false
  15736. */
  15737. this.clipping = false;
  15738. /**
  15739. * Overwritten and set to `true` by default.
  15740. *
  15741. * @type {boolean}
  15742. * @default true
  15743. */
  15744. this.forceSinglePass = true;
  15745. /**
  15746. * This object allows to enable certain WebGL 2 extensions.
  15747. *
  15748. * - clipCullDistance: set to `true` to use vertex shader clipping
  15749. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  15750. *
  15751. * @type {{clipCullDistance:false,multiDraw:false}}
  15752. */
  15753. this.extensions = {
  15754. clipCullDistance: false, // set to use vertex shader clipping
  15755. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  15756. };
  15757. /**
  15758. * When the rendered geometry doesn't include these attributes but the
  15759. * material does, these default values will be passed to the shaders. This
  15760. * avoids errors when buffer data is missing.
  15761. *
  15762. * - color: [ 1, 1, 1 ]
  15763. * - uv: [ 0, 0 ]
  15764. * - uv1: [ 0, 0 ]
  15765. *
  15766. * @type {Object}
  15767. */
  15768. this.defaultAttributeValues = {
  15769. 'color': [ 1, 1, 1 ],
  15770. 'uv': [ 0, 0 ],
  15771. 'uv1': [ 0, 0 ]
  15772. };
  15773. /**
  15774. * If set, this calls [gl.bindAttribLocation]{@link https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation}
  15775. * to bind a generic vertex index to an attribute variable.
  15776. *
  15777. * @type {string|undefined}
  15778. * @default undefined
  15779. */
  15780. this.index0AttributeName = undefined;
  15781. /**
  15782. * Can be used to force a uniform update while changing uniforms in
  15783. * {@link Object3D#onBeforeRender}.
  15784. *
  15785. * @type {boolean}
  15786. * @default false
  15787. */
  15788. this.uniformsNeedUpdate = false;
  15789. /**
  15790. * Defines the GLSL version of custom shader code.
  15791. *
  15792. * @type {?(GLSL1|GLSL3)}
  15793. * @default null
  15794. */
  15795. this.glslVersion = null;
  15796. if ( parameters !== undefined ) {
  15797. this.setValues( parameters );
  15798. }
  15799. }
  15800. copy( source ) {
  15801. super.copy( source );
  15802. this.fragmentShader = source.fragmentShader;
  15803. this.vertexShader = source.vertexShader;
  15804. this.uniforms = cloneUniforms( source.uniforms );
  15805. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  15806. this.defines = Object.assign( {}, source.defines );
  15807. this.wireframe = source.wireframe;
  15808. this.wireframeLinewidth = source.wireframeLinewidth;
  15809. this.fog = source.fog;
  15810. this.lights = source.lights;
  15811. this.clipping = source.clipping;
  15812. this.extensions = Object.assign( {}, source.extensions );
  15813. this.glslVersion = source.glslVersion;
  15814. return this;
  15815. }
  15816. toJSON( meta ) {
  15817. const data = super.toJSON( meta );
  15818. data.glslVersion = this.glslVersion;
  15819. data.uniforms = {};
  15820. for ( const name in this.uniforms ) {
  15821. const uniform = this.uniforms[ name ];
  15822. const value = uniform.value;
  15823. if ( value && value.isTexture ) {
  15824. data.uniforms[ name ] = {
  15825. type: 't',
  15826. value: value.toJSON( meta ).uuid
  15827. };
  15828. } else if ( value && value.isColor ) {
  15829. data.uniforms[ name ] = {
  15830. type: 'c',
  15831. value: value.getHex()
  15832. };
  15833. } else if ( value && value.isVector2 ) {
  15834. data.uniforms[ name ] = {
  15835. type: 'v2',
  15836. value: value.toArray()
  15837. };
  15838. } else if ( value && value.isVector3 ) {
  15839. data.uniforms[ name ] = {
  15840. type: 'v3',
  15841. value: value.toArray()
  15842. };
  15843. } else if ( value && value.isVector4 ) {
  15844. data.uniforms[ name ] = {
  15845. type: 'v4',
  15846. value: value.toArray()
  15847. };
  15848. } else if ( value && value.isMatrix3 ) {
  15849. data.uniforms[ name ] = {
  15850. type: 'm3',
  15851. value: value.toArray()
  15852. };
  15853. } else if ( value && value.isMatrix4 ) {
  15854. data.uniforms[ name ] = {
  15855. type: 'm4',
  15856. value: value.toArray()
  15857. };
  15858. } else {
  15859. data.uniforms[ name ] = {
  15860. value: value
  15861. };
  15862. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  15863. }
  15864. }
  15865. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  15866. data.vertexShader = this.vertexShader;
  15867. data.fragmentShader = this.fragmentShader;
  15868. data.lights = this.lights;
  15869. data.clipping = this.clipping;
  15870. const extensions = {};
  15871. for ( const key in this.extensions ) {
  15872. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  15873. }
  15874. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  15875. return data;
  15876. }
  15877. }
  15878. /**
  15879. * Abstract base class for cameras. This class should always be inherited
  15880. * when you build a new camera.
  15881. *
  15882. * @abstract
  15883. * @augments Object3D
  15884. */
  15885. class Camera extends Object3D {
  15886. /**
  15887. * Constructs a new camera.
  15888. */
  15889. constructor() {
  15890. super();
  15891. /**
  15892. * This flag can be used for type testing.
  15893. *
  15894. * @type {boolean}
  15895. * @readonly
  15896. * @default true
  15897. */
  15898. this.isCamera = true;
  15899. this.type = 'Camera';
  15900. /**
  15901. * The inverse of the camera's world matrix.
  15902. *
  15903. * @type {Matrix4}
  15904. */
  15905. this.matrixWorldInverse = new Matrix4();
  15906. /**
  15907. * The camera's projection matrix.
  15908. *
  15909. * @type {Matrix4}
  15910. */
  15911. this.projectionMatrix = new Matrix4();
  15912. /**
  15913. * The inverse of the camera's projection matrix.
  15914. *
  15915. * @type {Matrix4}
  15916. */
  15917. this.projectionMatrixInverse = new Matrix4();
  15918. /**
  15919. * The coordinate system in which the camera is used.
  15920. *
  15921. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  15922. */
  15923. this.coordinateSystem = WebGLCoordinateSystem;
  15924. this._reversedDepth = false;
  15925. }
  15926. /**
  15927. * The flag that indicates whether the camera uses a reversed depth buffer.
  15928. *
  15929. * @type {boolean}
  15930. * @default false
  15931. */
  15932. get reversedDepth() {
  15933. return this._reversedDepth;
  15934. }
  15935. copy( source, recursive ) {
  15936. super.copy( source, recursive );
  15937. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  15938. this.projectionMatrix.copy( source.projectionMatrix );
  15939. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  15940. this.coordinateSystem = source.coordinateSystem;
  15941. return this;
  15942. }
  15943. /**
  15944. * Returns a vector representing the ("look") direction of the 3D object in world space.
  15945. *
  15946. * This method is overwritten since cameras have a different forward vector compared to other
  15947. * 3D objects. A camera looks down its local, negative z-axis by default.
  15948. *
  15949. * @param {Vector3} target - The target vector the result is stored to.
  15950. * @return {Vector3} The 3D object's direction in world space.
  15951. */
  15952. getWorldDirection( target ) {
  15953. return super.getWorldDirection( target ).negate();
  15954. }
  15955. updateMatrixWorld( force ) {
  15956. super.updateMatrixWorld( force );
  15957. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  15958. }
  15959. updateWorldMatrix( updateParents, updateChildren ) {
  15960. super.updateWorldMatrix( updateParents, updateChildren );
  15961. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  15962. }
  15963. clone() {
  15964. return new this.constructor().copy( this );
  15965. }
  15966. }
  15967. const _v3$1 = /*@__PURE__*/ new Vector3();
  15968. const _minTarget = /*@__PURE__*/ new Vector2();
  15969. const _maxTarget = /*@__PURE__*/ new Vector2();
  15970. /**
  15971. * Camera that uses [perspective projection]{@link https://en.wikipedia.org/wiki/Perspective_(graphical)}.
  15972. *
  15973. * This projection mode is designed to mimic the way the human eye sees. It
  15974. * is the most common projection mode used for rendering a 3D scene.
  15975. *
  15976. * ```js
  15977. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  15978. * scene.add( camera );
  15979. * ```
  15980. *
  15981. * @augments Camera
  15982. */
  15983. class PerspectiveCamera extends Camera {
  15984. /**
  15985. * Constructs a new perspective camera.
  15986. *
  15987. * @param {number} [fov=50] - The vertical field of view.
  15988. * @param {number} [aspect=1] - The aspect ratio.
  15989. * @param {number} [near=0.1] - The camera's near plane.
  15990. * @param {number} [far=2000] - The camera's far plane.
  15991. */
  15992. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  15993. super();
  15994. /**
  15995. * This flag can be used for type testing.
  15996. *
  15997. * @type {boolean}
  15998. * @readonly
  15999. * @default true
  16000. */
  16001. this.isPerspectiveCamera = true;
  16002. this.type = 'PerspectiveCamera';
  16003. /**
  16004. * The vertical field of view, from bottom to top of view,
  16005. * in degrees.
  16006. *
  16007. * @type {number}
  16008. * @default 50
  16009. */
  16010. this.fov = fov;
  16011. /**
  16012. * The zoom factor of the camera.
  16013. *
  16014. * @type {number}
  16015. * @default 1
  16016. */
  16017. this.zoom = 1;
  16018. /**
  16019. * The camera's near plane. The valid range is greater than `0`
  16020. * and less than the current value of {@link PerspectiveCamera#far}.
  16021. *
  16022. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  16023. * valid value for a perspective camera's near plane.
  16024. *
  16025. * @type {number}
  16026. * @default 0.1
  16027. */
  16028. this.near = near;
  16029. /**
  16030. * The camera's far plane. Must be greater than the
  16031. * current value of {@link PerspectiveCamera#near}.
  16032. *
  16033. * @type {number}
  16034. * @default 2000
  16035. */
  16036. this.far = far;
  16037. /**
  16038. * Object distance used for stereoscopy and depth-of-field effects. This
  16039. * parameter does not influence the projection matrix unless a
  16040. * {@link StereoCamera} is being used.
  16041. *
  16042. * @type {number}
  16043. * @default 10
  16044. */
  16045. this.focus = 10;
  16046. /**
  16047. * The aspect ratio, usually the canvas width / canvas height.
  16048. *
  16049. * @type {number}
  16050. * @default 1
  16051. */
  16052. this.aspect = aspect;
  16053. /**
  16054. * Represents the frustum window specification. This property should not be edited
  16055. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  16056. *
  16057. * @type {?Object}
  16058. * @default null
  16059. */
  16060. this.view = null;
  16061. /**
  16062. * Film size used for the larger axis. Default is `35` (millimeters). This
  16063. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  16064. * is set to a nonzero value.
  16065. *
  16066. * @type {number}
  16067. * @default 35
  16068. */
  16069. this.filmGauge = 35;
  16070. /**
  16071. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  16072. *
  16073. * @type {number}
  16074. * @default 0
  16075. */
  16076. this.filmOffset = 0;
  16077. this.updateProjectionMatrix();
  16078. }
  16079. copy( source, recursive ) {
  16080. super.copy( source, recursive );
  16081. this.fov = source.fov;
  16082. this.zoom = source.zoom;
  16083. this.near = source.near;
  16084. this.far = source.far;
  16085. this.focus = source.focus;
  16086. this.aspect = source.aspect;
  16087. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16088. this.filmGauge = source.filmGauge;
  16089. this.filmOffset = source.filmOffset;
  16090. return this;
  16091. }
  16092. /**
  16093. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  16094. *
  16095. * The default film gauge is 35, so that the focal length can be specified for
  16096. * a 35mm (full frame) camera.
  16097. *
  16098. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  16099. */
  16100. setFocalLength( focalLength ) {
  16101. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  16102. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  16103. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  16104. this.updateProjectionMatrix();
  16105. }
  16106. /**
  16107. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  16108. * {@link PerspectiveCamera#filmGauge}.
  16109. *
  16110. * @return {number} The computed focal length.
  16111. */
  16112. getFocalLength() {
  16113. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  16114. return 0.5 * this.getFilmHeight() / vExtentSlope;
  16115. }
  16116. /**
  16117. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  16118. *
  16119. * @return {number} The effective FOV.
  16120. */
  16121. getEffectiveFOV() {
  16122. return RAD2DEG * 2 * Math.atan(
  16123. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  16124. }
  16125. /**
  16126. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16127. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16128. *
  16129. * @return {number} The film width.
  16130. */
  16131. getFilmWidth() {
  16132. // film not completely covered in portrait format (aspect < 1)
  16133. return this.filmGauge * Math.min( this.aspect, 1 );
  16134. }
  16135. /**
  16136. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16137. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16138. *
  16139. * @return {number} The film width.
  16140. */
  16141. getFilmHeight() {
  16142. // film not completely covered in landscape format (aspect > 1)
  16143. return this.filmGauge / Math.max( this.aspect, 1 );
  16144. }
  16145. /**
  16146. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  16147. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  16148. *
  16149. * @param {number} distance - The viewing distance.
  16150. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  16151. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  16152. */
  16153. getViewBounds( distance, minTarget, maxTarget ) {
  16154. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16155. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16156. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16157. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16158. }
  16159. /**
  16160. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  16161. *
  16162. * @param {number} distance - The viewing distance.
  16163. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  16164. * @returns {Vector2} The view size.
  16165. */
  16166. getViewSize( distance, target ) {
  16167. this.getViewBounds( distance, _minTarget, _maxTarget );
  16168. return target.subVectors( _maxTarget, _minTarget );
  16169. }
  16170. /**
  16171. * Sets an offset in a larger frustum. This is useful for multi-window or
  16172. * multi-monitor/multi-machine setups.
  16173. *
  16174. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  16175. * the monitors are in grid like this
  16176. *```
  16177. * +---+---+---+
  16178. * | A | B | C |
  16179. * +---+---+---+
  16180. * | D | E | F |
  16181. * +---+---+---+
  16182. *```
  16183. * then for each monitor you would call it like this:
  16184. *```js
  16185. * const w = 1920;
  16186. * const h = 1080;
  16187. * const fullWidth = w * 3;
  16188. * const fullHeight = h * 2;
  16189. *
  16190. * // --A--
  16191. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  16192. * // --B--
  16193. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  16194. * // --C--
  16195. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  16196. * // --D--
  16197. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  16198. * // --E--
  16199. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  16200. * // --F--
  16201. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  16202. * ```
  16203. *
  16204. * Note there is no reason monitors have to be the same size or in a grid.
  16205. *
  16206. * @param {number} fullWidth - The full width of multiview setup.
  16207. * @param {number} fullHeight - The full height of multiview setup.
  16208. * @param {number} x - The horizontal offset of the subcamera.
  16209. * @param {number} y - The vertical offset of the subcamera.
  16210. * @param {number} width - The width of subcamera.
  16211. * @param {number} height - The height of subcamera.
  16212. */
  16213. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16214. this.aspect = fullWidth / fullHeight;
  16215. if ( this.view === null ) {
  16216. this.view = {
  16217. enabled: true,
  16218. fullWidth: 1,
  16219. fullHeight: 1,
  16220. offsetX: 0,
  16221. offsetY: 0,
  16222. width: 1,
  16223. height: 1
  16224. };
  16225. }
  16226. this.view.enabled = true;
  16227. this.view.fullWidth = fullWidth;
  16228. this.view.fullHeight = fullHeight;
  16229. this.view.offsetX = x;
  16230. this.view.offsetY = y;
  16231. this.view.width = width;
  16232. this.view.height = height;
  16233. this.updateProjectionMatrix();
  16234. }
  16235. /**
  16236. * Removes the view offset from the projection matrix.
  16237. */
  16238. clearViewOffset() {
  16239. if ( this.view !== null ) {
  16240. this.view.enabled = false;
  16241. }
  16242. this.updateProjectionMatrix();
  16243. }
  16244. /**
  16245. * Updates the camera's projection matrix. Must be called after any change of
  16246. * camera properties.
  16247. */
  16248. updateProjectionMatrix() {
  16249. const near = this.near;
  16250. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  16251. let height = 2 * top;
  16252. let width = this.aspect * height;
  16253. let left = -0.5 * width;
  16254. const view = this.view;
  16255. if ( this.view !== null && this.view.enabled ) {
  16256. const fullWidth = view.fullWidth,
  16257. fullHeight = view.fullHeight;
  16258. left += view.offsetX * width / fullWidth;
  16259. top -= view.offsetY * height / fullHeight;
  16260. width *= view.width / fullWidth;
  16261. height *= view.height / fullHeight;
  16262. }
  16263. const skew = this.filmOffset;
  16264. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16265. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth );
  16266. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16267. }
  16268. toJSON( meta ) {
  16269. const data = super.toJSON( meta );
  16270. data.object.fov = this.fov;
  16271. data.object.zoom = this.zoom;
  16272. data.object.near = this.near;
  16273. data.object.far = this.far;
  16274. data.object.focus = this.focus;
  16275. data.object.aspect = this.aspect;
  16276. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16277. data.object.filmGauge = this.filmGauge;
  16278. data.object.filmOffset = this.filmOffset;
  16279. return data;
  16280. }
  16281. }
  16282. const fov = -90; // negative fov is not an error
  16283. const aspect = 1;
  16284. /**
  16285. * A special type of camera that is positioned in 3D space to render its surroundings into a
  16286. * cube render target. The render target can then be used as an environment map for rendering
  16287. * realtime reflections in your scene.
  16288. *
  16289. * ```js
  16290. * // Create cube render target
  16291. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  16292. *
  16293. * // Create cube camera
  16294. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  16295. * scene.add( cubeCamera );
  16296. *
  16297. * // Create car
  16298. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  16299. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  16300. * scene.add( car );
  16301. *
  16302. * // Update the render target cube
  16303. * car.visible = false;
  16304. * cubeCamera.position.copy( car.position );
  16305. * cubeCamera.update( renderer, scene );
  16306. *
  16307. * // Render the scene
  16308. * car.visible = true;
  16309. * renderer.render( scene, camera );
  16310. * ```
  16311. *
  16312. * @augments Object3D
  16313. */
  16314. class CubeCamera extends Object3D {
  16315. /**
  16316. * Constructs a new cube camera.
  16317. *
  16318. * @param {number} near - The camera's near plane.
  16319. * @param {number} far - The camera's far plane.
  16320. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  16321. */
  16322. constructor( near, far, renderTarget ) {
  16323. super();
  16324. this.type = 'CubeCamera';
  16325. /**
  16326. * A reference to the cube render target.
  16327. *
  16328. * @type {WebGLCubeRenderTarget}
  16329. */
  16330. this.renderTarget = renderTarget;
  16331. /**
  16332. * The current active coordinate system.
  16333. *
  16334. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16335. * @default null
  16336. */
  16337. this.coordinateSystem = null;
  16338. /**
  16339. * The current active mipmap level
  16340. *
  16341. * @type {number}
  16342. * @default 0
  16343. */
  16344. this.activeMipmapLevel = 0;
  16345. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  16346. cameraPX.layers = this.layers;
  16347. this.add( cameraPX );
  16348. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  16349. cameraNX.layers = this.layers;
  16350. this.add( cameraNX );
  16351. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  16352. cameraPY.layers = this.layers;
  16353. this.add( cameraPY );
  16354. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  16355. cameraNY.layers = this.layers;
  16356. this.add( cameraNY );
  16357. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  16358. cameraPZ.layers = this.layers;
  16359. this.add( cameraPZ );
  16360. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  16361. cameraNZ.layers = this.layers;
  16362. this.add( cameraNZ );
  16363. }
  16364. /**
  16365. * Must be called when the coordinate system of the cube camera is changed.
  16366. */
  16367. updateCoordinateSystem() {
  16368. const coordinateSystem = this.coordinateSystem;
  16369. const cameras = this.children.concat();
  16370. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  16371. for ( const camera of cameras ) this.remove( camera );
  16372. if ( coordinateSystem === WebGLCoordinateSystem ) {
  16373. cameraPX.up.set( 0, 1, 0 );
  16374. cameraPX.lookAt( 1, 0, 0 );
  16375. cameraNX.up.set( 0, 1, 0 );
  16376. cameraNX.lookAt( -1, 0, 0 );
  16377. cameraPY.up.set( 0, 0, -1 );
  16378. cameraPY.lookAt( 0, 1, 0 );
  16379. cameraNY.up.set( 0, 0, 1 );
  16380. cameraNY.lookAt( 0, -1, 0 );
  16381. cameraPZ.up.set( 0, 1, 0 );
  16382. cameraPZ.lookAt( 0, 0, 1 );
  16383. cameraNZ.up.set( 0, 1, 0 );
  16384. cameraNZ.lookAt( 0, 0, -1 );
  16385. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  16386. cameraPX.up.set( 0, -1, 0 );
  16387. cameraPX.lookAt( -1, 0, 0 );
  16388. cameraNX.up.set( 0, -1, 0 );
  16389. cameraNX.lookAt( 1, 0, 0 );
  16390. cameraPY.up.set( 0, 0, 1 );
  16391. cameraPY.lookAt( 0, 1, 0 );
  16392. cameraNY.up.set( 0, 0, -1 );
  16393. cameraNY.lookAt( 0, -1, 0 );
  16394. cameraPZ.up.set( 0, -1, 0 );
  16395. cameraPZ.lookAt( 0, 0, 1 );
  16396. cameraNZ.up.set( 0, -1, 0 );
  16397. cameraNZ.lookAt( 0, 0, -1 );
  16398. } else {
  16399. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  16400. }
  16401. for ( const camera of cameras ) {
  16402. this.add( camera );
  16403. camera.updateMatrixWorld();
  16404. }
  16405. }
  16406. /**
  16407. * Calling this method will render the given scene with the given renderer
  16408. * into the cube render target of the camera.
  16409. *
  16410. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  16411. * @param {Scene} scene - The scene to render.
  16412. */
  16413. update( renderer, scene ) {
  16414. if ( this.parent === null ) this.updateMatrixWorld();
  16415. const { renderTarget, activeMipmapLevel } = this;
  16416. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  16417. this.coordinateSystem = renderer.coordinateSystem;
  16418. this.updateCoordinateSystem();
  16419. }
  16420. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  16421. const currentRenderTarget = renderer.getRenderTarget();
  16422. const currentActiveCubeFace = renderer.getActiveCubeFace();
  16423. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  16424. const currentXrEnabled = renderer.xr.enabled;
  16425. renderer.xr.enabled = false;
  16426. const generateMipmaps = renderTarget.texture.generateMipmaps;
  16427. renderTarget.texture.generateMipmaps = false;
  16428. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  16429. renderer.render( scene, cameraPX );
  16430. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  16431. renderer.render( scene, cameraNX );
  16432. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  16433. renderer.render( scene, cameraPY );
  16434. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  16435. renderer.render( scene, cameraNY );
  16436. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  16437. renderer.render( scene, cameraPZ );
  16438. // mipmaps are generated during the last call of render()
  16439. // at this point, all sides of the cube render target are defined
  16440. renderTarget.texture.generateMipmaps = generateMipmaps;
  16441. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  16442. renderer.render( scene, cameraNZ );
  16443. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  16444. renderer.xr.enabled = currentXrEnabled;
  16445. renderTarget.texture.needsPMREMUpdate = true;
  16446. }
  16447. }
  16448. /**
  16449. * Creates a cube texture made up of six images.
  16450. *
  16451. * ```js
  16452. * const loader = new THREE.CubeTextureLoader();
  16453. * loader.setPath( 'textures/cube/pisa/' );
  16454. *
  16455. * const textureCube = loader.load( [
  16456. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  16457. * ] );
  16458. *
  16459. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  16460. * ```
  16461. *
  16462. * @augments Texture
  16463. */
  16464. class CubeTexture extends Texture {
  16465. /**
  16466. * Constructs a new cube texture.
  16467. *
  16468. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  16469. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  16470. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  16471. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  16472. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  16473. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  16474. * @param {number} [format=RGBAFormat] - The texture format.
  16475. * @param {number} [type=UnsignedByteType] - The texture type.
  16476. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  16477. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  16478. */
  16479. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  16480. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  16481. /**
  16482. * This flag can be used for type testing.
  16483. *
  16484. * @type {boolean}
  16485. * @readonly
  16486. * @default true
  16487. */
  16488. this.isCubeTexture = true;
  16489. /**
  16490. * If set to `true`, the texture is flipped along the vertical axis when
  16491. * uploaded to the GPU.
  16492. *
  16493. * Overwritten and set to `false` by default.
  16494. *
  16495. * @type {boolean}
  16496. * @default false
  16497. */
  16498. this.flipY = false;
  16499. }
  16500. /**
  16501. * Alias for {@link CubeTexture#image}.
  16502. *
  16503. * @type {Array<Image>}
  16504. */
  16505. get images() {
  16506. return this.image;
  16507. }
  16508. set images( value ) {
  16509. this.image = value;
  16510. }
  16511. }
  16512. /**
  16513. * A cube render target used in context of {@link WebGLRenderer}.
  16514. *
  16515. * @augments WebGLRenderTarget
  16516. */
  16517. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  16518. /**
  16519. * Constructs a new cube render target.
  16520. *
  16521. * @param {number} [size=1] - The size of the render target.
  16522. * @param {RenderTarget~Options} [options] - The configuration object.
  16523. */
  16524. constructor( size = 1, options = {} ) {
  16525. super( size, size, options );
  16526. /**
  16527. * This flag can be used for type testing.
  16528. *
  16529. * @type {boolean}
  16530. * @readonly
  16531. * @default true
  16532. */
  16533. this.isWebGLCubeRenderTarget = true;
  16534. const image = { width: size, height: size, depth: 1 };
  16535. const images = [ image, image, image, image, image, image ];
  16536. /**
  16537. * Overwritten with a different texture type.
  16538. *
  16539. * @type {DataArrayTexture}
  16540. */
  16541. this.texture = new CubeTexture( images );
  16542. this._setTextureOptions( options );
  16543. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16544. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16545. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16546. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16547. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16548. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16549. this.texture.isRenderTargetTexture = true;
  16550. }
  16551. /**
  16552. * Converts the given equirectangular texture to a cube map.
  16553. *
  16554. * @param {WebGLRenderer} renderer - The renderer.
  16555. * @param {Texture} texture - The equirectangular texture.
  16556. * @return {WebGLCubeRenderTarget} A reference to this cube render target.
  16557. */
  16558. fromEquirectangularTexture( renderer, texture ) {
  16559. this.texture.type = texture.type;
  16560. this.texture.colorSpace = texture.colorSpace;
  16561. this.texture.generateMipmaps = texture.generateMipmaps;
  16562. this.texture.minFilter = texture.minFilter;
  16563. this.texture.magFilter = texture.magFilter;
  16564. const shader = {
  16565. uniforms: {
  16566. tEquirect: { value: null },
  16567. },
  16568. vertexShader: /* glsl */`
  16569. varying vec3 vWorldDirection;
  16570. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  16571. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  16572. }
  16573. void main() {
  16574. vWorldDirection = transformDirection( position, modelMatrix );
  16575. #include <begin_vertex>
  16576. #include <project_vertex>
  16577. }
  16578. `,
  16579. fragmentShader: /* glsl */`
  16580. uniform sampler2D tEquirect;
  16581. varying vec3 vWorldDirection;
  16582. #include <common>
  16583. void main() {
  16584. vec3 direction = normalize( vWorldDirection );
  16585. vec2 sampleUV = equirectUv( direction );
  16586. gl_FragColor = texture2D( tEquirect, sampleUV );
  16587. }
  16588. `
  16589. };
  16590. const geometry = new BoxGeometry( 5, 5, 5 );
  16591. const material = new ShaderMaterial( {
  16592. name: 'CubemapFromEquirect',
  16593. uniforms: cloneUniforms( shader.uniforms ),
  16594. vertexShader: shader.vertexShader,
  16595. fragmentShader: shader.fragmentShader,
  16596. side: BackSide,
  16597. blending: NoBlending
  16598. } );
  16599. material.uniforms.tEquirect.value = texture;
  16600. const mesh = new Mesh( geometry, material );
  16601. const currentMinFilter = texture.minFilter;
  16602. // Avoid blurred poles
  16603. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  16604. const camera = new CubeCamera( 1, 10, this );
  16605. camera.update( renderer, mesh );
  16606. texture.minFilter = currentMinFilter;
  16607. mesh.geometry.dispose();
  16608. mesh.material.dispose();
  16609. return this;
  16610. }
  16611. /**
  16612. * Clears this cube render target.
  16613. *
  16614. * @param {WebGLRenderer} renderer - The renderer.
  16615. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16616. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16617. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16618. */
  16619. clear( renderer, color = true, depth = true, stencil = true ) {
  16620. const currentRenderTarget = renderer.getRenderTarget();
  16621. for ( let i = 0; i < 6; i ++ ) {
  16622. renderer.setRenderTarget( this, i );
  16623. renderer.clear( color, depth, stencil );
  16624. }
  16625. renderer.setRenderTarget( currentRenderTarget );
  16626. }
  16627. }
  16628. /**
  16629. * This is almost identical to an {@link Object3D}. Its purpose is to
  16630. * make working with groups of objects syntactically clearer.
  16631. *
  16632. * ```js
  16633. * // Create a group and add the two cubes.
  16634. * // These cubes can now be rotated / scaled etc as a group.
  16635. * const group = new THREE.Group();
  16636. *
  16637. * group.add( meshA );
  16638. * group.add( meshB );
  16639. *
  16640. * scene.add( group );
  16641. * ```
  16642. *
  16643. * @augments Object3D
  16644. */
  16645. class Group extends Object3D {
  16646. constructor() {
  16647. super();
  16648. /**
  16649. * This flag can be used for type testing.
  16650. *
  16651. * @type {boolean}
  16652. * @readonly
  16653. * @default true
  16654. */
  16655. this.isGroup = true;
  16656. this.type = 'Group';
  16657. }
  16658. }
  16659. const _moveEvent = { type: 'move' };
  16660. /**
  16661. * Class for representing a XR controller with its
  16662. * different coordinate systems.
  16663. *
  16664. * @private
  16665. */
  16666. class WebXRController {
  16667. /**
  16668. * Constructs a new XR controller.
  16669. */
  16670. constructor() {
  16671. /**
  16672. * A group representing the target ray space
  16673. * of the XR controller.
  16674. *
  16675. * @private
  16676. * @type {?Group}
  16677. * @default null
  16678. */
  16679. this._targetRay = null;
  16680. /**
  16681. * A group representing the grip space
  16682. * of the XR controller.
  16683. *
  16684. * @private
  16685. * @type {?Group}
  16686. * @default null
  16687. */
  16688. this._grip = null;
  16689. /**
  16690. * A group representing the hand space
  16691. * of the XR controller.
  16692. *
  16693. * @private
  16694. * @type {?Group}
  16695. * @default null
  16696. */
  16697. this._hand = null;
  16698. }
  16699. /**
  16700. * Returns a group representing the hand space of the XR controller.
  16701. *
  16702. * @return {Group} A group representing the hand space of the XR controller.
  16703. */
  16704. getHandSpace() {
  16705. if ( this._hand === null ) {
  16706. this._hand = new Group();
  16707. this._hand.matrixAutoUpdate = false;
  16708. this._hand.visible = false;
  16709. this._hand.joints = {};
  16710. this._hand.inputState = { pinching: false };
  16711. }
  16712. return this._hand;
  16713. }
  16714. /**
  16715. * Returns a group representing the target ray space of the XR controller.
  16716. *
  16717. * @return {Group} A group representing the target ray space of the XR controller.
  16718. */
  16719. getTargetRaySpace() {
  16720. if ( this._targetRay === null ) {
  16721. this._targetRay = new Group();
  16722. this._targetRay.matrixAutoUpdate = false;
  16723. this._targetRay.visible = false;
  16724. this._targetRay.hasLinearVelocity = false;
  16725. this._targetRay.linearVelocity = new Vector3();
  16726. this._targetRay.hasAngularVelocity = false;
  16727. this._targetRay.angularVelocity = new Vector3();
  16728. }
  16729. return this._targetRay;
  16730. }
  16731. /**
  16732. * Returns a group representing the grip space of the XR controller.
  16733. *
  16734. * @return {Group} A group representing the grip space of the XR controller.
  16735. */
  16736. getGripSpace() {
  16737. if ( this._grip === null ) {
  16738. this._grip = new Group();
  16739. this._grip.matrixAutoUpdate = false;
  16740. this._grip.visible = false;
  16741. this._grip.hasLinearVelocity = false;
  16742. this._grip.linearVelocity = new Vector3();
  16743. this._grip.hasAngularVelocity = false;
  16744. this._grip.angularVelocity = new Vector3();
  16745. }
  16746. return this._grip;
  16747. }
  16748. /**
  16749. * Dispatches the given event to the groups representing
  16750. * the different coordinate spaces of the XR controller.
  16751. *
  16752. * @param {Object} event - The event to dispatch.
  16753. * @return {WebXRController} A reference to this instance.
  16754. */
  16755. dispatchEvent( event ) {
  16756. if ( this._targetRay !== null ) {
  16757. this._targetRay.dispatchEvent( event );
  16758. }
  16759. if ( this._grip !== null ) {
  16760. this._grip.dispatchEvent( event );
  16761. }
  16762. if ( this._hand !== null ) {
  16763. this._hand.dispatchEvent( event );
  16764. }
  16765. return this;
  16766. }
  16767. /**
  16768. * Connects the controller with the given XR input source.
  16769. *
  16770. * @param {XRInputSource} inputSource - The input source.
  16771. * @return {WebXRController} A reference to this instance.
  16772. */
  16773. connect( inputSource ) {
  16774. if ( inputSource && inputSource.hand ) {
  16775. const hand = this._hand;
  16776. if ( hand ) {
  16777. for ( const inputjoint of inputSource.hand.values() ) {
  16778. // Initialize hand with joints when connected
  16779. this._getHandJoint( hand, inputjoint );
  16780. }
  16781. }
  16782. }
  16783. this.dispatchEvent( { type: 'connected', data: inputSource } );
  16784. return this;
  16785. }
  16786. /**
  16787. * Disconnects the controller from the given XR input source.
  16788. *
  16789. * @param {XRInputSource} inputSource - The input source.
  16790. * @return {WebXRController} A reference to this instance.
  16791. */
  16792. disconnect( inputSource ) {
  16793. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  16794. if ( this._targetRay !== null ) {
  16795. this._targetRay.visible = false;
  16796. }
  16797. if ( this._grip !== null ) {
  16798. this._grip.visible = false;
  16799. }
  16800. if ( this._hand !== null ) {
  16801. this._hand.visible = false;
  16802. }
  16803. return this;
  16804. }
  16805. /**
  16806. * Updates the controller with the given input source, XR frame and reference space.
  16807. * This updates the transformations of the groups that represent the different
  16808. * coordinate systems of the controller.
  16809. *
  16810. * @param {XRInputSource} inputSource - The input source.
  16811. * @param {XRFrame} frame - The XR frame.
  16812. * @param {XRReferenceSpace} referenceSpace - The reference space.
  16813. * @return {WebXRController} A reference to this instance.
  16814. */
  16815. update( inputSource, frame, referenceSpace ) {
  16816. let inputPose = null;
  16817. let gripPose = null;
  16818. let handPose = null;
  16819. const targetRay = this._targetRay;
  16820. const grip = this._grip;
  16821. const hand = this._hand;
  16822. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  16823. if ( hand && inputSource.hand ) {
  16824. handPose = true;
  16825. for ( const inputjoint of inputSource.hand.values() ) {
  16826. // Update the joints groups with the XRJoint poses
  16827. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  16828. // The transform of this joint will be updated with the joint pose on each frame
  16829. const joint = this._getHandJoint( hand, inputjoint );
  16830. if ( jointPose !== null ) {
  16831. joint.matrix.fromArray( jointPose.transform.matrix );
  16832. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  16833. joint.matrixWorldNeedsUpdate = true;
  16834. joint.jointRadius = jointPose.radius;
  16835. }
  16836. joint.visible = jointPose !== null;
  16837. }
  16838. // Custom events
  16839. // Check pinchz
  16840. const indexTip = hand.joints[ 'index-finger-tip' ];
  16841. const thumbTip = hand.joints[ 'thumb-tip' ];
  16842. const distance = indexTip.position.distanceTo( thumbTip.position );
  16843. const distanceToPinch = 0.02;
  16844. const threshold = 0.005;
  16845. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  16846. hand.inputState.pinching = false;
  16847. this.dispatchEvent( {
  16848. type: 'pinchend',
  16849. handedness: inputSource.handedness,
  16850. target: this
  16851. } );
  16852. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  16853. hand.inputState.pinching = true;
  16854. this.dispatchEvent( {
  16855. type: 'pinchstart',
  16856. handedness: inputSource.handedness,
  16857. target: this
  16858. } );
  16859. }
  16860. } else {
  16861. if ( grip !== null && inputSource.gripSpace ) {
  16862. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  16863. if ( gripPose !== null ) {
  16864. grip.matrix.fromArray( gripPose.transform.matrix );
  16865. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  16866. grip.matrixWorldNeedsUpdate = true;
  16867. if ( gripPose.linearVelocity ) {
  16868. grip.hasLinearVelocity = true;
  16869. grip.linearVelocity.copy( gripPose.linearVelocity );
  16870. } else {
  16871. grip.hasLinearVelocity = false;
  16872. }
  16873. if ( gripPose.angularVelocity ) {
  16874. grip.hasAngularVelocity = true;
  16875. grip.angularVelocity.copy( gripPose.angularVelocity );
  16876. } else {
  16877. grip.hasAngularVelocity = false;
  16878. }
  16879. }
  16880. }
  16881. }
  16882. if ( targetRay !== null ) {
  16883. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  16884. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  16885. if ( inputPose === null && gripPose !== null ) {
  16886. inputPose = gripPose;
  16887. }
  16888. if ( inputPose !== null ) {
  16889. targetRay.matrix.fromArray( inputPose.transform.matrix );
  16890. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  16891. targetRay.matrixWorldNeedsUpdate = true;
  16892. if ( inputPose.linearVelocity ) {
  16893. targetRay.hasLinearVelocity = true;
  16894. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  16895. } else {
  16896. targetRay.hasLinearVelocity = false;
  16897. }
  16898. if ( inputPose.angularVelocity ) {
  16899. targetRay.hasAngularVelocity = true;
  16900. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  16901. } else {
  16902. targetRay.hasAngularVelocity = false;
  16903. }
  16904. this.dispatchEvent( _moveEvent );
  16905. }
  16906. }
  16907. }
  16908. if ( targetRay !== null ) {
  16909. targetRay.visible = ( inputPose !== null );
  16910. }
  16911. if ( grip !== null ) {
  16912. grip.visible = ( gripPose !== null );
  16913. }
  16914. if ( hand !== null ) {
  16915. hand.visible = ( handPose !== null );
  16916. }
  16917. return this;
  16918. }
  16919. /**
  16920. * Returns a group representing the hand joint for the given input joint.
  16921. *
  16922. * @private
  16923. * @param {Group} hand - The group representing the hand space.
  16924. * @param {XRJointSpace} inputjoint - The hand joint data.
  16925. * @return {Group} A group representing the hand joint for the given input joint.
  16926. */
  16927. _getHandJoint( hand, inputjoint ) {
  16928. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  16929. const joint = new Group();
  16930. joint.matrixAutoUpdate = false;
  16931. joint.visible = false;
  16932. hand.joints[ inputjoint.jointName ] = joint;
  16933. hand.add( joint );
  16934. }
  16935. return hand.joints[ inputjoint.jointName ];
  16936. }
  16937. }
  16938. /**
  16939. * This class can be used to define an exponential squared fog,
  16940. * which gives a clear view near the camera and a faster than exponentially
  16941. * densening fog farther from the camera.
  16942. *
  16943. * ```js
  16944. * const scene = new THREE.Scene();
  16945. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  16946. * ```
  16947. */
  16948. class FogExp2 {
  16949. /**
  16950. * Constructs a new fog.
  16951. *
  16952. * @param {number|Color} color - The fog's color.
  16953. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  16954. */
  16955. constructor( color, density = 0.00025 ) {
  16956. /**
  16957. * This flag can be used for type testing.
  16958. *
  16959. * @type {boolean}
  16960. * @readonly
  16961. * @default true
  16962. */
  16963. this.isFogExp2 = true;
  16964. /**
  16965. * The name of the fog.
  16966. *
  16967. * @type {string}
  16968. */
  16969. this.name = '';
  16970. /**
  16971. * The fog's color.
  16972. *
  16973. * @type {Color}
  16974. */
  16975. this.color = new Color( color );
  16976. /**
  16977. * Defines how fast the fog will grow dense.
  16978. *
  16979. * @type {number}
  16980. * @default 0.00025
  16981. */
  16982. this.density = density;
  16983. }
  16984. /**
  16985. * Returns a new fog with copied values from this instance.
  16986. *
  16987. * @return {FogExp2} A clone of this instance.
  16988. */
  16989. clone() {
  16990. return new FogExp2( this.color, this.density );
  16991. }
  16992. /**
  16993. * Serializes the fog into JSON.
  16994. *
  16995. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  16996. * @return {Object} A JSON object representing the serialized fog
  16997. */
  16998. toJSON( /* meta */ ) {
  16999. return {
  17000. type: 'FogExp2',
  17001. name: this.name,
  17002. color: this.color.getHex(),
  17003. density: this.density
  17004. };
  17005. }
  17006. }
  17007. /**
  17008. * This class can be used to define a linear fog that grows linearly denser
  17009. * with the distance.
  17010. *
  17011. * ```js
  17012. * const scene = new THREE.Scene();
  17013. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  17014. * ```
  17015. */
  17016. class Fog {
  17017. /**
  17018. * Constructs a new fog.
  17019. *
  17020. * @param {number|Color} color - The fog's color.
  17021. * @param {number} [near=1] - The minimum distance to start applying fog.
  17022. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  17023. */
  17024. constructor( color, near = 1, far = 1000 ) {
  17025. /**
  17026. * This flag can be used for type testing.
  17027. *
  17028. * @type {boolean}
  17029. * @readonly
  17030. * @default true
  17031. */
  17032. this.isFog = true;
  17033. /**
  17034. * The name of the fog.
  17035. *
  17036. * @type {string}
  17037. */
  17038. this.name = '';
  17039. /**
  17040. * The fog's color.
  17041. *
  17042. * @type {Color}
  17043. */
  17044. this.color = new Color( color );
  17045. /**
  17046. * The minimum distance to start applying fog. Objects that are less than
  17047. * `near` units from the active camera won't be affected by fog.
  17048. *
  17049. * @type {number}
  17050. * @default 1
  17051. */
  17052. this.near = near;
  17053. /**
  17054. * The maximum distance at which fog stops being calculated and applied.
  17055. * Objects that are more than `far` units away from the active camera won't
  17056. * be affected by fog.
  17057. *
  17058. * @type {number}
  17059. * @default 1000
  17060. */
  17061. this.far = far;
  17062. }
  17063. /**
  17064. * Returns a new fog with copied values from this instance.
  17065. *
  17066. * @return {Fog} A clone of this instance.
  17067. */
  17068. clone() {
  17069. return new Fog( this.color, this.near, this.far );
  17070. }
  17071. /**
  17072. * Serializes the fog into JSON.
  17073. *
  17074. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17075. * @return {Object} A JSON object representing the serialized fog
  17076. */
  17077. toJSON( /* meta */ ) {
  17078. return {
  17079. type: 'Fog',
  17080. name: this.name,
  17081. color: this.color.getHex(),
  17082. near: this.near,
  17083. far: this.far
  17084. };
  17085. }
  17086. }
  17087. /**
  17088. * Scenes allow you to set up what is to be rendered and where by three.js.
  17089. * This is where you place 3D objects like meshes, lines or lights.
  17090. *
  17091. * @augments Object3D
  17092. */
  17093. class Scene extends Object3D {
  17094. /**
  17095. * Constructs a new scene.
  17096. */
  17097. constructor() {
  17098. super();
  17099. /**
  17100. * This flag can be used for type testing.
  17101. *
  17102. * @type {boolean}
  17103. * @readonly
  17104. * @default true
  17105. */
  17106. this.isScene = true;
  17107. this.type = 'Scene';
  17108. /**
  17109. * Defines the background of the scene. Valid inputs are:
  17110. *
  17111. * - A color for defining a uniform colored background.
  17112. * - A texture for defining a (flat) textured background.
  17113. * - Cube textures or equirectangular textures for defining a skybox.
  17114. *
  17115. * @type {?(Color|Texture)}
  17116. * @default null
  17117. */
  17118. this.background = null;
  17119. /**
  17120. * Sets the environment map for all physical materials in the scene. However,
  17121. * it's not possible to overwrite an existing texture assigned to the `envMap`
  17122. * material property.
  17123. *
  17124. * @type {?Texture}
  17125. * @default null
  17126. */
  17127. this.environment = null;
  17128. /**
  17129. * A fog instance defining the type of fog that affects everything
  17130. * rendered in the scene.
  17131. *
  17132. * @type {?(Fog|FogExp2)}
  17133. * @default null
  17134. */
  17135. this.fog = null;
  17136. /**
  17137. * Sets the blurriness of the background. Only influences environment maps
  17138. * assigned to {@link Scene#background}. Valid input is a float between `0`
  17139. * and `1`.
  17140. *
  17141. * @type {number}
  17142. * @default 0
  17143. */
  17144. this.backgroundBlurriness = 0;
  17145. /**
  17146. * Attenuates the color of the background. Only applies to background textures.
  17147. *
  17148. * @type {number}
  17149. * @default 1
  17150. */
  17151. this.backgroundIntensity = 1;
  17152. /**
  17153. * The rotation of the background in radians. Only influences environment maps
  17154. * assigned to {@link Scene#background}.
  17155. *
  17156. * @type {Euler}
  17157. * @default (0,0,0)
  17158. */
  17159. this.backgroundRotation = new Euler();
  17160. /**
  17161. * Attenuates the color of the environment. Only influences environment maps
  17162. * assigned to {@link Scene#environment}.
  17163. *
  17164. * @type {number}
  17165. * @default 1
  17166. */
  17167. this.environmentIntensity = 1;
  17168. /**
  17169. * The rotation of the environment map in radians. Only influences physical materials
  17170. * in the scene when {@link Scene#environment} is used.
  17171. *
  17172. * @type {Euler}
  17173. * @default (0,0,0)
  17174. */
  17175. this.environmentRotation = new Euler();
  17176. /**
  17177. * Forces everything in the scene to be rendered with the defined material. It is possible
  17178. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  17179. *
  17180. * @type {?Material}
  17181. * @default null
  17182. */
  17183. this.overrideMaterial = null;
  17184. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17185. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17186. }
  17187. }
  17188. copy( source, recursive ) {
  17189. super.copy( source, recursive );
  17190. if ( source.background !== null ) this.background = source.background.clone();
  17191. if ( source.environment !== null ) this.environment = source.environment.clone();
  17192. if ( source.fog !== null ) this.fog = source.fog.clone();
  17193. this.backgroundBlurriness = source.backgroundBlurriness;
  17194. this.backgroundIntensity = source.backgroundIntensity;
  17195. this.backgroundRotation.copy( source.backgroundRotation );
  17196. this.environmentIntensity = source.environmentIntensity;
  17197. this.environmentRotation.copy( source.environmentRotation );
  17198. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17199. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17200. return this;
  17201. }
  17202. toJSON( meta ) {
  17203. const data = super.toJSON( meta );
  17204. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17205. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17206. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17207. data.object.backgroundRotation = this.backgroundRotation.toArray();
  17208. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  17209. data.object.environmentRotation = this.environmentRotation.toArray();
  17210. return data;
  17211. }
  17212. }
  17213. /**
  17214. * "Interleaved" means that multiple attributes, possibly of different types,
  17215. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  17216. *
  17217. * An introduction into interleaved arrays can be found here: [Interleaved array basics]{@link https://blog.tojicode.com/2011/05/interleaved-array-basics.html}
  17218. */
  17219. class InterleavedBuffer {
  17220. /**
  17221. * Constructs a new interleaved buffer.
  17222. *
  17223. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  17224. * @param {number} stride - The number of typed-array elements per vertex.
  17225. */
  17226. constructor( array, stride ) {
  17227. /**
  17228. * This flag can be used for type testing.
  17229. *
  17230. * @type {boolean}
  17231. * @readonly
  17232. * @default true
  17233. */
  17234. this.isInterleavedBuffer = true;
  17235. /**
  17236. * A typed array with a shared buffer storing attribute data.
  17237. *
  17238. * @type {TypedArray}
  17239. */
  17240. this.array = array;
  17241. /**
  17242. * The number of typed-array elements per vertex.
  17243. *
  17244. * @type {number}
  17245. */
  17246. this.stride = stride;
  17247. /**
  17248. * The total number of elements in the array
  17249. *
  17250. * @type {number}
  17251. * @readonly
  17252. */
  17253. this.count = array !== undefined ? array.length / stride : 0;
  17254. /**
  17255. * Defines the intended usage pattern of the data store for optimization purposes.
  17256. *
  17257. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  17258. * instantiate a new one and set the desired usage before the next render.
  17259. *
  17260. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  17261. * @default StaticDrawUsage
  17262. */
  17263. this.usage = StaticDrawUsage;
  17264. /**
  17265. * This can be used to only update some components of stored vectors (for example, just the
  17266. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  17267. *
  17268. * @type {Array<Object>}
  17269. */
  17270. this.updateRanges = [];
  17271. /**
  17272. * A version number, incremented every time the `needsUpdate` is set to `true`.
  17273. *
  17274. * @type {number}
  17275. */
  17276. this.version = 0;
  17277. /**
  17278. * The UUID of the interleaved buffer.
  17279. *
  17280. * @type {string}
  17281. * @readonly
  17282. */
  17283. this.uuid = generateUUID();
  17284. }
  17285. /**
  17286. * A callback function that is executed after the renderer has transferred the attribute array
  17287. * data to the GPU.
  17288. */
  17289. onUploadCallback() {}
  17290. /**
  17291. * Flag to indicate that this attribute has changed and should be re-sent to
  17292. * the GPU. Set this to `true` when you modify the value of the array.
  17293. *
  17294. * @type {number}
  17295. * @default false
  17296. * @param {boolean} value
  17297. */
  17298. set needsUpdate( value ) {
  17299. if ( value === true ) this.version ++;
  17300. }
  17301. /**
  17302. * Sets the usage of this interleaved buffer.
  17303. *
  17304. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  17305. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  17306. */
  17307. setUsage( value ) {
  17308. this.usage = value;
  17309. return this;
  17310. }
  17311. /**
  17312. * Adds a range of data in the data array to be updated on the GPU.
  17313. *
  17314. * @param {number} start - Position at which to start update.
  17315. * @param {number} count - The number of components to update.
  17316. */
  17317. addUpdateRange( start, count ) {
  17318. this.updateRanges.push( { start, count } );
  17319. }
  17320. /**
  17321. * Clears the update ranges.
  17322. */
  17323. clearUpdateRanges() {
  17324. this.updateRanges.length = 0;
  17325. }
  17326. /**
  17327. * Copies the values of the given interleaved buffer to this instance.
  17328. *
  17329. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  17330. * @return {InterleavedBuffer} A reference to this instance.
  17331. */
  17332. copy( source ) {
  17333. this.array = new source.array.constructor( source.array );
  17334. this.count = source.count;
  17335. this.stride = source.stride;
  17336. this.usage = source.usage;
  17337. return this;
  17338. }
  17339. /**
  17340. * Copies a vector from the given interleaved buffer to this one. The start
  17341. * and destination position in the attribute buffers are represented by the
  17342. * given indices.
  17343. *
  17344. * @param {number} index1 - The destination index into this interleaved buffer.
  17345. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  17346. * @param {number} index2 - The source index into the given interleaved buffer.
  17347. * @return {InterleavedBuffer} A reference to this instance.
  17348. */
  17349. copyAt( index1, interleavedBuffer, index2 ) {
  17350. index1 *= this.stride;
  17351. index2 *= interleavedBuffer.stride;
  17352. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17353. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  17354. }
  17355. return this;
  17356. }
  17357. /**
  17358. * Sets the given array data in the interleaved buffer.
  17359. *
  17360. * @param {(TypedArray|Array)} value - The array data to set.
  17361. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  17362. * @return {InterleavedBuffer} A reference to this instance.
  17363. */
  17364. set( value, offset = 0 ) {
  17365. this.array.set( value, offset );
  17366. return this;
  17367. }
  17368. /**
  17369. * Returns a new interleaved buffer with copied values from this instance.
  17370. *
  17371. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  17372. * @return {InterleavedBuffer} A clone of this instance.
  17373. */
  17374. clone( data ) {
  17375. if ( data.arrayBuffers === undefined ) {
  17376. data.arrayBuffers = {};
  17377. }
  17378. if ( this.array.buffer._uuid === undefined ) {
  17379. this.array.buffer._uuid = generateUUID();
  17380. }
  17381. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17382. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17383. }
  17384. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17385. const ib = new this.constructor( array, this.stride );
  17386. ib.setUsage( this.usage );
  17387. return ib;
  17388. }
  17389. /**
  17390. * Sets the given callback function that is executed after the Renderer has transferred
  17391. * the array data to the GPU. Can be used to perform clean-up operations after
  17392. * the upload when data are not needed anymore on the CPU side.
  17393. *
  17394. * @param {Function} callback - The `onUpload()` callback.
  17395. * @return {InterleavedBuffer} A reference to this instance.
  17396. */
  17397. onUpload( callback ) {
  17398. this.onUploadCallback = callback;
  17399. return this;
  17400. }
  17401. /**
  17402. * Serializes the interleaved buffer into JSON.
  17403. *
  17404. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17405. * @return {Object} A JSON object representing the serialized interleaved buffer.
  17406. */
  17407. toJSON( data ) {
  17408. if ( data.arrayBuffers === undefined ) {
  17409. data.arrayBuffers = {};
  17410. }
  17411. // generate UUID for array buffer if necessary
  17412. if ( this.array.buffer._uuid === undefined ) {
  17413. this.array.buffer._uuid = generateUUID();
  17414. }
  17415. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17416. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17417. }
  17418. //
  17419. return {
  17420. uuid: this.uuid,
  17421. buffer: this.array.buffer._uuid,
  17422. type: this.array.constructor.name,
  17423. stride: this.stride
  17424. };
  17425. }
  17426. }
  17427. const _vector$7 = /*@__PURE__*/ new Vector3();
  17428. /**
  17429. * An alternative version of a buffer attribute with interleaved data. Interleaved
  17430. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  17431. * different offsets into the buffer.
  17432. */
  17433. class InterleavedBufferAttribute {
  17434. /**
  17435. * Constructs a new interleaved buffer attribute.
  17436. *
  17437. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  17438. * @param {number} itemSize - The item size.
  17439. * @param {number} offset - The attribute offset into the buffer.
  17440. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  17441. */
  17442. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17443. /**
  17444. * This flag can be used for type testing.
  17445. *
  17446. * @type {boolean}
  17447. * @readonly
  17448. * @default true
  17449. */
  17450. this.isInterleavedBufferAttribute = true;
  17451. /**
  17452. * The name of the buffer attribute.
  17453. *
  17454. * @type {string}
  17455. */
  17456. this.name = '';
  17457. /**
  17458. * The buffer holding the interleaved data.
  17459. *
  17460. * @type {InterleavedBuffer}
  17461. */
  17462. this.data = interleavedBuffer;
  17463. /**
  17464. * The item size, see {@link BufferAttribute#itemSize}.
  17465. *
  17466. * @type {number}
  17467. */
  17468. this.itemSize = itemSize;
  17469. /**
  17470. * The attribute offset into the buffer.
  17471. *
  17472. * @type {number}
  17473. */
  17474. this.offset = offset;
  17475. /**
  17476. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  17477. *
  17478. * @type {InterleavedBuffer}
  17479. */
  17480. this.normalized = normalized;
  17481. }
  17482. /**
  17483. * The item count of this buffer attribute.
  17484. *
  17485. * @type {number}
  17486. * @readonly
  17487. */
  17488. get count() {
  17489. return this.data.count;
  17490. }
  17491. /**
  17492. * The array holding the interleaved buffer attribute data.
  17493. *
  17494. * @type {TypedArray}
  17495. */
  17496. get array() {
  17497. return this.data.array;
  17498. }
  17499. /**
  17500. * Flag to indicate that this attribute has changed and should be re-sent to
  17501. * the GPU. Set this to `true` when you modify the value of the array.
  17502. *
  17503. * @type {number}
  17504. * @default false
  17505. * @param {boolean} value
  17506. */
  17507. set needsUpdate( value ) {
  17508. this.data.needsUpdate = value;
  17509. }
  17510. /**
  17511. * Applies the given 4x4 matrix to the given attribute. Only works with
  17512. * item size `3`.
  17513. *
  17514. * @param {Matrix4} m - The matrix to apply.
  17515. * @return {InterleavedBufferAttribute} A reference to this instance.
  17516. */
  17517. applyMatrix4( m ) {
  17518. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17519. _vector$7.fromBufferAttribute( this, i );
  17520. _vector$7.applyMatrix4( m );
  17521. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17522. }
  17523. return this;
  17524. }
  17525. /**
  17526. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  17527. * item size `3`.
  17528. *
  17529. * @param {Matrix3} m - The normal matrix to apply.
  17530. * @return {InterleavedBufferAttribute} A reference to this instance.
  17531. */
  17532. applyNormalMatrix( m ) {
  17533. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17534. _vector$7.fromBufferAttribute( this, i );
  17535. _vector$7.applyNormalMatrix( m );
  17536. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17537. }
  17538. return this;
  17539. }
  17540. /**
  17541. * Applies the given 4x4 matrix to the given attribute. Only works with
  17542. * item size `3` and with direction vectors.
  17543. *
  17544. * @param {Matrix4} m - The matrix to apply.
  17545. * @return {InterleavedBufferAttribute} A reference to this instance.
  17546. */
  17547. transformDirection( m ) {
  17548. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17549. _vector$7.fromBufferAttribute( this, i );
  17550. _vector$7.transformDirection( m );
  17551. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17552. }
  17553. return this;
  17554. }
  17555. /**
  17556. * Returns the given component of the vector at the given index.
  17557. *
  17558. * @param {number} index - The index into the buffer attribute.
  17559. * @param {number} component - The component index.
  17560. * @return {number} The returned value.
  17561. */
  17562. getComponent( index, component ) {
  17563. let value = this.array[ index * this.data.stride + this.offset + component ];
  17564. if ( this.normalized ) value = denormalize( value, this.array );
  17565. return value;
  17566. }
  17567. /**
  17568. * Sets the given value to the given component of the vector at the given index.
  17569. *
  17570. * @param {number} index - The index into the buffer attribute.
  17571. * @param {number} component - The component index.
  17572. * @param {number} value - The value to set.
  17573. * @return {InterleavedBufferAttribute} A reference to this instance.
  17574. */
  17575. setComponent( index, component, value ) {
  17576. if ( this.normalized ) value = normalize( value, this.array );
  17577. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  17578. return this;
  17579. }
  17580. /**
  17581. * Sets the x component of the vector at the given index.
  17582. *
  17583. * @param {number} index - The index into the buffer attribute.
  17584. * @param {number} x - The value to set.
  17585. * @return {InterleavedBufferAttribute} A reference to this instance.
  17586. */
  17587. setX( index, x ) {
  17588. if ( this.normalized ) x = normalize( x, this.array );
  17589. this.data.array[ index * this.data.stride + this.offset ] = x;
  17590. return this;
  17591. }
  17592. /**
  17593. * Sets the y component of the vector at the given index.
  17594. *
  17595. * @param {number} index - The index into the buffer attribute.
  17596. * @param {number} y - The value to set.
  17597. * @return {InterleavedBufferAttribute} A reference to this instance.
  17598. */
  17599. setY( index, y ) {
  17600. if ( this.normalized ) y = normalize( y, this.array );
  17601. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17602. return this;
  17603. }
  17604. /**
  17605. * Sets the z component of the vector at the given index.
  17606. *
  17607. * @param {number} index - The index into the buffer attribute.
  17608. * @param {number} z - The value to set.
  17609. * @return {InterleavedBufferAttribute} A reference to this instance.
  17610. */
  17611. setZ( index, z ) {
  17612. if ( this.normalized ) z = normalize( z, this.array );
  17613. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17614. return this;
  17615. }
  17616. /**
  17617. * Sets the w component of the vector at the given index.
  17618. *
  17619. * @param {number} index - The index into the buffer attribute.
  17620. * @param {number} w - The value to set.
  17621. * @return {InterleavedBufferAttribute} A reference to this instance.
  17622. */
  17623. setW( index, w ) {
  17624. if ( this.normalized ) w = normalize( w, this.array );
  17625. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17626. return this;
  17627. }
  17628. /**
  17629. * Returns the x component of the vector at the given index.
  17630. *
  17631. * @param {number} index - The index into the buffer attribute.
  17632. * @return {number} The x component.
  17633. */
  17634. getX( index ) {
  17635. let x = this.data.array[ index * this.data.stride + this.offset ];
  17636. if ( this.normalized ) x = denormalize( x, this.array );
  17637. return x;
  17638. }
  17639. /**
  17640. * Returns the y component of the vector at the given index.
  17641. *
  17642. * @param {number} index - The index into the buffer attribute.
  17643. * @return {number} The y component.
  17644. */
  17645. getY( index ) {
  17646. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17647. if ( this.normalized ) y = denormalize( y, this.array );
  17648. return y;
  17649. }
  17650. /**
  17651. * Returns the z component of the vector at the given index.
  17652. *
  17653. * @param {number} index - The index into the buffer attribute.
  17654. * @return {number} The z component.
  17655. */
  17656. getZ( index ) {
  17657. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17658. if ( this.normalized ) z = denormalize( z, this.array );
  17659. return z;
  17660. }
  17661. /**
  17662. * Returns the w component of the vector at the given index.
  17663. *
  17664. * @param {number} index - The index into the buffer attribute.
  17665. * @return {number} The w component.
  17666. */
  17667. getW( index ) {
  17668. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17669. if ( this.normalized ) w = denormalize( w, this.array );
  17670. return w;
  17671. }
  17672. /**
  17673. * Sets the x and y component of the vector at the given index.
  17674. *
  17675. * @param {number} index - The index into the buffer attribute.
  17676. * @param {number} x - The value for the x component to set.
  17677. * @param {number} y - The value for the y component to set.
  17678. * @return {InterleavedBufferAttribute} A reference to this instance.
  17679. */
  17680. setXY( index, x, y ) {
  17681. index = index * this.data.stride + this.offset;
  17682. if ( this.normalized ) {
  17683. x = normalize( x, this.array );
  17684. y = normalize( y, this.array );
  17685. }
  17686. this.data.array[ index + 0 ] = x;
  17687. this.data.array[ index + 1 ] = y;
  17688. return this;
  17689. }
  17690. /**
  17691. * Sets the x, y and z component of the vector at the given index.
  17692. *
  17693. * @param {number} index - The index into the buffer attribute.
  17694. * @param {number} x - The value for the x component to set.
  17695. * @param {number} y - The value for the y component to set.
  17696. * @param {number} z - The value for the z component to set.
  17697. * @return {InterleavedBufferAttribute} A reference to this instance.
  17698. */
  17699. setXYZ( index, x, y, z ) {
  17700. index = index * this.data.stride + this.offset;
  17701. if ( this.normalized ) {
  17702. x = normalize( x, this.array );
  17703. y = normalize( y, this.array );
  17704. z = normalize( z, this.array );
  17705. }
  17706. this.data.array[ index + 0 ] = x;
  17707. this.data.array[ index + 1 ] = y;
  17708. this.data.array[ index + 2 ] = z;
  17709. return this;
  17710. }
  17711. /**
  17712. * Sets the x, y, z and w component of the vector at the given index.
  17713. *
  17714. * @param {number} index - The index into the buffer attribute.
  17715. * @param {number} x - The value for the x component to set.
  17716. * @param {number} y - The value for the y component to set.
  17717. * @param {number} z - The value for the z component to set.
  17718. * @param {number} w - The value for the w component to set.
  17719. * @return {InterleavedBufferAttribute} A reference to this instance.
  17720. */
  17721. setXYZW( index, x, y, z, w ) {
  17722. index = index * this.data.stride + this.offset;
  17723. if ( this.normalized ) {
  17724. x = normalize( x, this.array );
  17725. y = normalize( y, this.array );
  17726. z = normalize( z, this.array );
  17727. w = normalize( w, this.array );
  17728. }
  17729. this.data.array[ index + 0 ] = x;
  17730. this.data.array[ index + 1 ] = y;
  17731. this.data.array[ index + 2 ] = z;
  17732. this.data.array[ index + 3 ] = w;
  17733. return this;
  17734. }
  17735. /**
  17736. * Returns a new buffer attribute with copied values from this instance.
  17737. *
  17738. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17739. *
  17740. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  17741. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  17742. */
  17743. clone( data ) {
  17744. if ( data === undefined ) {
  17745. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17746. const array = [];
  17747. for ( let i = 0; i < this.count; i ++ ) {
  17748. const index = i * this.data.stride + this.offset;
  17749. for ( let j = 0; j < this.itemSize; j ++ ) {
  17750. array.push( this.data.array[ index + j ] );
  17751. }
  17752. }
  17753. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17754. } else {
  17755. if ( data.interleavedBuffers === undefined ) {
  17756. data.interleavedBuffers = {};
  17757. }
  17758. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17759. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17760. }
  17761. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17762. }
  17763. }
  17764. /**
  17765. * Serializes the buffer attribute into JSON.
  17766. *
  17767. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17768. *
  17769. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17770. * @return {Object} A JSON object representing the serialized buffer attribute.
  17771. */
  17772. toJSON( data ) {
  17773. if ( data === undefined ) {
  17774. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17775. const array = [];
  17776. for ( let i = 0; i < this.count; i ++ ) {
  17777. const index = i * this.data.stride + this.offset;
  17778. for ( let j = 0; j < this.itemSize; j ++ ) {
  17779. array.push( this.data.array[ index + j ] );
  17780. }
  17781. }
  17782. // de-interleave data and save it as an ordinary buffer attribute for now
  17783. return {
  17784. itemSize: this.itemSize,
  17785. type: this.array.constructor.name,
  17786. array: array,
  17787. normalized: this.normalized
  17788. };
  17789. } else {
  17790. // save as true interleaved attribute
  17791. if ( data.interleavedBuffers === undefined ) {
  17792. data.interleavedBuffers = {};
  17793. }
  17794. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17795. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17796. }
  17797. return {
  17798. isInterleavedBufferAttribute: true,
  17799. itemSize: this.itemSize,
  17800. data: this.data.uuid,
  17801. offset: this.offset,
  17802. normalized: this.normalized
  17803. };
  17804. }
  17805. }
  17806. }
  17807. /**
  17808. * A material for rendering instances of {@link Sprite}.
  17809. *
  17810. * ```js
  17811. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  17812. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  17813. *
  17814. * const sprite = new THREE.Sprite( material );
  17815. * sprite.scale.set(200, 200, 1)
  17816. * scene.add( sprite );
  17817. * ```
  17818. *
  17819. * @augments Material
  17820. */
  17821. class SpriteMaterial extends Material {
  17822. /**
  17823. * Constructs a new sprite material.
  17824. *
  17825. * @param {Object} [parameters] - An object with one or more properties
  17826. * defining the material's appearance. Any property of the material
  17827. * (including any property from inherited materials) can be passed
  17828. * in here. Color values can be passed any type of value accepted
  17829. * by {@link Color#set}.
  17830. */
  17831. constructor( parameters ) {
  17832. super();
  17833. /**
  17834. * This flag can be used for type testing.
  17835. *
  17836. * @type {boolean}
  17837. * @readonly
  17838. * @default true
  17839. */
  17840. this.isSpriteMaterial = true;
  17841. this.type = 'SpriteMaterial';
  17842. /**
  17843. * Color of the material.
  17844. *
  17845. * @type {Color}
  17846. * @default (1,1,1)
  17847. */
  17848. this.color = new Color( 0xffffff );
  17849. /**
  17850. * The color map. May optionally include an alpha channel, typically combined
  17851. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  17852. * color is modulated by the diffuse `color`.
  17853. *
  17854. * @type {?Texture}
  17855. * @default null
  17856. */
  17857. this.map = null;
  17858. /**
  17859. * The alpha map is a grayscale texture that controls the opacity across the
  17860. * surface (black: fully transparent; white: fully opaque).
  17861. *
  17862. * Only the color of the texture is used, ignoring the alpha channel if one
  17863. * exists. For RGB and RGBA textures, the renderer will use the green channel
  17864. * when sampling this texture due to the extra bit of precision provided for
  17865. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  17866. * luminance/alpha textures will also still work as expected.
  17867. *
  17868. * @type {?Texture}
  17869. * @default null
  17870. */
  17871. this.alphaMap = null;
  17872. /**
  17873. * The rotation of the sprite in radians.
  17874. *
  17875. * @type {number}
  17876. * @default 0
  17877. */
  17878. this.rotation = 0;
  17879. /**
  17880. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  17881. *
  17882. * @type {boolean}
  17883. * @default true
  17884. */
  17885. this.sizeAttenuation = true;
  17886. /**
  17887. * Overwritten since sprite materials are transparent
  17888. * by default.
  17889. *
  17890. * @type {boolean}
  17891. * @default true
  17892. */
  17893. this.transparent = true;
  17894. /**
  17895. * Whether the material is affected by fog or not.
  17896. *
  17897. * @type {boolean}
  17898. * @default true
  17899. */
  17900. this.fog = true;
  17901. this.setValues( parameters );
  17902. }
  17903. copy( source ) {
  17904. super.copy( source );
  17905. this.color.copy( source.color );
  17906. this.map = source.map;
  17907. this.alphaMap = source.alphaMap;
  17908. this.rotation = source.rotation;
  17909. this.sizeAttenuation = source.sizeAttenuation;
  17910. this.fog = source.fog;
  17911. return this;
  17912. }
  17913. }
  17914. let _geometry;
  17915. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17916. const _worldScale = /*@__PURE__*/ new Vector3();
  17917. const _mvPosition = /*@__PURE__*/ new Vector3();
  17918. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17919. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17920. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17921. const _vA = /*@__PURE__*/ new Vector3();
  17922. const _vB = /*@__PURE__*/ new Vector3();
  17923. const _vC = /*@__PURE__*/ new Vector3();
  17924. const _uvA = /*@__PURE__*/ new Vector2();
  17925. const _uvB = /*@__PURE__*/ new Vector2();
  17926. const _uvC = /*@__PURE__*/ new Vector2();
  17927. /**
  17928. * A sprite is a plane that always faces towards the camera, generally with a
  17929. * partially transparent texture applied.
  17930. *
  17931. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  17932. * have no effect.
  17933. *
  17934. * ```js
  17935. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  17936. * const material = new THREE.SpriteMaterial( { map: map } );
  17937. *
  17938. * const sprite = new THREE.Sprite( material );
  17939. * scene.add( sprite );
  17940. * ```
  17941. *
  17942. * @augments Object3D
  17943. */
  17944. class Sprite extends Object3D {
  17945. /**
  17946. * Constructs a new sprite.
  17947. *
  17948. * @param {SpriteMaterial} [material] - The sprite material.
  17949. */
  17950. constructor( material = new SpriteMaterial() ) {
  17951. super();
  17952. /**
  17953. * This flag can be used for type testing.
  17954. *
  17955. * @type {boolean}
  17956. * @readonly
  17957. * @default true
  17958. */
  17959. this.isSprite = true;
  17960. this.type = 'Sprite';
  17961. if ( _geometry === undefined ) {
  17962. _geometry = new BufferGeometry();
  17963. const float32Array = new Float32Array( [
  17964. -0.5, -0.5, 0, 0, 0,
  17965. 0.5, -0.5, 0, 1, 0,
  17966. 0.5, 0.5, 0, 1, 1,
  17967. -0.5, 0.5, 0, 0, 1
  17968. ] );
  17969. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  17970. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  17971. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  17972. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  17973. }
  17974. /**
  17975. * The sprite geometry.
  17976. *
  17977. * @type {BufferGeometry}
  17978. */
  17979. this.geometry = _geometry;
  17980. /**
  17981. * The sprite material.
  17982. *
  17983. * @type {SpriteMaterial}
  17984. */
  17985. this.material = material;
  17986. /**
  17987. * The sprite's anchor point, and the point around which the sprite rotates.
  17988. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  17989. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  17990. *
  17991. * @type {Vector2}
  17992. * @default (0.5,0.5)
  17993. */
  17994. this.center = new Vector2( 0.5, 0.5 );
  17995. /**
  17996. * The number of instances of this sprite.
  17997. * Can only be used with {@link WebGPURenderer}.
  17998. *
  17999. * @type {number}
  18000. * @default 1
  18001. */
  18002. this.count = 1;
  18003. }
  18004. /**
  18005. * Computes intersection points between a casted ray and this sprite.
  18006. *
  18007. * @param {Raycaster} raycaster - The raycaster.
  18008. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18009. */
  18010. raycast( raycaster, intersects ) {
  18011. if ( raycaster.camera === null ) {
  18012. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18013. }
  18014. _worldScale.setFromMatrixScale( this.matrixWorld );
  18015. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18016. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18017. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18018. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18019. _worldScale.multiplyScalar( - _mvPosition.z );
  18020. }
  18021. const rotation = this.material.rotation;
  18022. let sin, cos;
  18023. if ( rotation !== 0 ) {
  18024. cos = Math.cos( rotation );
  18025. sin = Math.sin( rotation );
  18026. }
  18027. const center = this.center;
  18028. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18029. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18030. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18031. _uvA.set( 0, 0 );
  18032. _uvB.set( 1, 0 );
  18033. _uvC.set( 1, 1 );
  18034. // check first triangle
  18035. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18036. if ( intersect === null ) {
  18037. // check second triangle
  18038. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18039. _uvB.set( 0, 1 );
  18040. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18041. if ( intersect === null ) {
  18042. return;
  18043. }
  18044. }
  18045. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18046. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18047. intersects.push( {
  18048. distance: distance,
  18049. point: _intersectPoint.clone(),
  18050. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18051. face: null,
  18052. object: this
  18053. } );
  18054. }
  18055. copy( source, recursive ) {
  18056. super.copy( source, recursive );
  18057. if ( source.center !== undefined ) this.center.copy( source.center );
  18058. this.material = source.material;
  18059. return this;
  18060. }
  18061. }
  18062. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18063. // compute position in camera space
  18064. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18065. // to check if rotation is not zero
  18066. if ( sin !== undefined ) {
  18067. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18068. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18069. } else {
  18070. _rotatedPosition.copy( _alignedPosition );
  18071. }
  18072. vertexPosition.copy( mvPosition );
  18073. vertexPosition.x += _rotatedPosition.x;
  18074. vertexPosition.y += _rotatedPosition.y;
  18075. // transform to world space
  18076. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18077. }
  18078. const _v1$2 = /*@__PURE__*/ new Vector3();
  18079. const _v2$1 = /*@__PURE__*/ new Vector3();
  18080. /**
  18081. * A component for providing a basic Level of Detail (LOD) mechanism.
  18082. *
  18083. * Every LOD level is associated with an object, and rendering can be switched
  18084. * between them at the distances specified. Typically you would create, say,
  18085. * three meshes, one for far away (low detail), one for mid range (medium
  18086. * detail) and one for close up (high detail).
  18087. *
  18088. * ```js
  18089. * const lod = new THREE.LOD();
  18090. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  18091. *
  18092. * //Create spheres with 3 levels of detail and create new LOD levels for them
  18093. * for( let i = 0; i < 3; i++ ) {
  18094. *
  18095. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  18096. * const mesh = new THREE.Mesh( geometry, material );
  18097. * lod.addLevel( mesh, i * 75 );
  18098. *
  18099. * }
  18100. *
  18101. * scene.add( lod );
  18102. * ```
  18103. *
  18104. * @augments Object3D
  18105. */
  18106. class LOD extends Object3D {
  18107. /**
  18108. * Constructs a new LOD.
  18109. */
  18110. constructor() {
  18111. super();
  18112. /**
  18113. * This flag can be used for type testing.
  18114. *
  18115. * @type {boolean}
  18116. * @readonly
  18117. * @default true
  18118. */
  18119. this.isLOD = true;
  18120. /**
  18121. * The current LOD index.
  18122. *
  18123. * @private
  18124. * @type {number}
  18125. * @default 0
  18126. */
  18127. this._currentLevel = 0;
  18128. this.type = 'LOD';
  18129. Object.defineProperties( this, {
  18130. /**
  18131. * This array holds the LOD levels.
  18132. *
  18133. * @name LOD#levels
  18134. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  18135. */
  18136. levels: {
  18137. enumerable: true,
  18138. value: []
  18139. }
  18140. } );
  18141. /**
  18142. * Whether the LOD object is updated automatically by the renderer per frame
  18143. * or not. If set to `false`, you have to call {@link LOD#update} in the
  18144. * render loop by yourself.
  18145. *
  18146. * @type {boolean}
  18147. * @default true
  18148. */
  18149. this.autoUpdate = true;
  18150. }
  18151. copy( source ) {
  18152. super.copy( source, false );
  18153. const levels = source.levels;
  18154. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18155. const level = levels[ i ];
  18156. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18157. }
  18158. this.autoUpdate = source.autoUpdate;
  18159. return this;
  18160. }
  18161. /**
  18162. * Adds a mesh that will display at a certain distance and greater. Typically
  18163. * the further away the distance, the lower the detail on the mesh.
  18164. *
  18165. * @param {Object3D} object - The 3D object to display at this level.
  18166. * @param {number} [distance=0] - The distance at which to display this level of detail.
  18167. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  18168. * @return {LOD} A reference to this instance.
  18169. */
  18170. addLevel( object, distance = 0, hysteresis = 0 ) {
  18171. distance = Math.abs( distance );
  18172. const levels = this.levels;
  18173. let l;
  18174. for ( l = 0; l < levels.length; l ++ ) {
  18175. if ( distance < levels[ l ].distance ) {
  18176. break;
  18177. }
  18178. }
  18179. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18180. this.add( object );
  18181. return this;
  18182. }
  18183. /**
  18184. * Removes an existing level, based on the distance from the camera.
  18185. * Returns `true` when the level has been removed. Otherwise `false`.
  18186. *
  18187. * @param {number} distance - Distance of the level to remove.
  18188. * @return {boolean} Whether the level has been removed or not.
  18189. */
  18190. removeLevel( distance ) {
  18191. const levels = this.levels;
  18192. for ( let i = 0; i < levels.length; i ++ ) {
  18193. if ( levels[ i ].distance === distance ) {
  18194. const removedElements = levels.splice( i, 1 );
  18195. this.remove( removedElements[ 0 ].object );
  18196. return true;
  18197. }
  18198. }
  18199. return false;
  18200. }
  18201. /**
  18202. * Returns the currently active LOD level index.
  18203. *
  18204. * @return {number} The current active LOD level index.
  18205. */
  18206. getCurrentLevel() {
  18207. return this._currentLevel;
  18208. }
  18209. /**
  18210. * Returns a reference to the first 3D object that is greater than
  18211. * the given distance.
  18212. *
  18213. * @param {number} distance - The LOD distance.
  18214. * @return {Object3D|null} The found 3D object. `null` if no 3D object has been found.
  18215. */
  18216. getObjectForDistance( distance ) {
  18217. const levels = this.levels;
  18218. if ( levels.length > 0 ) {
  18219. let i, l;
  18220. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18221. let levelDistance = levels[ i ].distance;
  18222. if ( levels[ i ].object.visible ) {
  18223. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18224. }
  18225. if ( distance < levelDistance ) {
  18226. break;
  18227. }
  18228. }
  18229. return levels[ i - 1 ].object;
  18230. }
  18231. return null;
  18232. }
  18233. /**
  18234. * Computes intersection points between a casted ray and this LOD.
  18235. *
  18236. * @param {Raycaster} raycaster - The raycaster.
  18237. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18238. */
  18239. raycast( raycaster, intersects ) {
  18240. const levels = this.levels;
  18241. if ( levels.length > 0 ) {
  18242. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18243. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18244. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18245. }
  18246. }
  18247. /**
  18248. * Updates the LOD by computing which LOD level should be visible according
  18249. * to the current distance of the given camera.
  18250. *
  18251. * @param {Camera} camera - The camera the scene is rendered with.
  18252. */
  18253. update( camera ) {
  18254. const levels = this.levels;
  18255. if ( levels.length > 1 ) {
  18256. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18257. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18258. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18259. levels[ 0 ].object.visible = true;
  18260. let i, l;
  18261. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18262. let levelDistance = levels[ i ].distance;
  18263. if ( levels[ i ].object.visible ) {
  18264. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18265. }
  18266. if ( distance >= levelDistance ) {
  18267. levels[ i - 1 ].object.visible = false;
  18268. levels[ i ].object.visible = true;
  18269. } else {
  18270. break;
  18271. }
  18272. }
  18273. this._currentLevel = i - 1;
  18274. for ( ; i < l; i ++ ) {
  18275. levels[ i ].object.visible = false;
  18276. }
  18277. }
  18278. }
  18279. toJSON( meta ) {
  18280. const data = super.toJSON( meta );
  18281. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18282. data.object.levels = [];
  18283. const levels = this.levels;
  18284. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18285. const level = levels[ i ];
  18286. data.object.levels.push( {
  18287. object: level.object.uuid,
  18288. distance: level.distance,
  18289. hysteresis: level.hysteresis
  18290. } );
  18291. }
  18292. return data;
  18293. }
  18294. }
  18295. const _basePosition = /*@__PURE__*/ new Vector3();
  18296. const _skinIndex = /*@__PURE__*/ new Vector4();
  18297. const _skinWeight = /*@__PURE__*/ new Vector4();
  18298. const _vector3 = /*@__PURE__*/ new Vector3();
  18299. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18300. const _vertex = /*@__PURE__*/ new Vector3();
  18301. const _sphere$5 = /*@__PURE__*/ new Sphere();
  18302. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18303. const _ray$2 = /*@__PURE__*/ new Ray();
  18304. /**
  18305. * A mesh that has a {@link Skeleton} that can then be used to animate the
  18306. * vertices of the geometry with skinning/skeleton animation.
  18307. *
  18308. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  18309. * as buffer attributes in its geometry. These attribute define which bones affect a single
  18310. * vertex to a certain extend.
  18311. *
  18312. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  18313. * or {@link FBXLoader } import respective models.
  18314. *
  18315. * @augments Mesh
  18316. */
  18317. class SkinnedMesh extends Mesh {
  18318. /**
  18319. * Constructs a new skinned mesh.
  18320. *
  18321. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18322. * @param {Material|Array<Material>} [material] - The mesh material.
  18323. */
  18324. constructor( geometry, material ) {
  18325. super( geometry, material );
  18326. /**
  18327. * This flag can be used for type testing.
  18328. *
  18329. * @type {boolean}
  18330. * @readonly
  18331. * @default true
  18332. */
  18333. this.isSkinnedMesh = true;
  18334. this.type = 'SkinnedMesh';
  18335. /**
  18336. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  18337. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  18338. * across multiple skinned meshes.
  18339. *
  18340. * @type {(AttachedBindMode|DetachedBindMode)}
  18341. * @default AttachedBindMode
  18342. */
  18343. this.bindMode = AttachedBindMode;
  18344. /**
  18345. * The base matrix that is used for the bound bone transforms.
  18346. *
  18347. * @type {Matrix4}
  18348. */
  18349. this.bindMatrix = new Matrix4();
  18350. /**
  18351. * The base matrix that is used for resetting the bound bone transforms.
  18352. *
  18353. * @type {Matrix4}
  18354. */
  18355. this.bindMatrixInverse = new Matrix4();
  18356. /**
  18357. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  18358. *
  18359. * @type {?Box3}
  18360. * @default null
  18361. */
  18362. this.boundingBox = null;
  18363. /**
  18364. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  18365. *
  18366. * @type {?Sphere}
  18367. * @default null
  18368. */
  18369. this.boundingSphere = null;
  18370. }
  18371. /**
  18372. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  18373. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18374. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  18375. * the current animation state.
  18376. */
  18377. computeBoundingBox() {
  18378. const geometry = this.geometry;
  18379. if ( this.boundingBox === null ) {
  18380. this.boundingBox = new Box3();
  18381. }
  18382. this.boundingBox.makeEmpty();
  18383. const positionAttribute = geometry.getAttribute( 'position' );
  18384. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18385. this.getVertexPosition( i, _vertex );
  18386. this.boundingBox.expandByPoint( _vertex );
  18387. }
  18388. }
  18389. /**
  18390. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  18391. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  18392. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  18393. * per frame in order to reflect the current animation state.
  18394. */
  18395. computeBoundingSphere() {
  18396. const geometry = this.geometry;
  18397. if ( this.boundingSphere === null ) {
  18398. this.boundingSphere = new Sphere();
  18399. }
  18400. this.boundingSphere.makeEmpty();
  18401. const positionAttribute = geometry.getAttribute( 'position' );
  18402. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18403. this.getVertexPosition( i, _vertex );
  18404. this.boundingSphere.expandByPoint( _vertex );
  18405. }
  18406. }
  18407. copy( source, recursive ) {
  18408. super.copy( source, recursive );
  18409. this.bindMode = source.bindMode;
  18410. this.bindMatrix.copy( source.bindMatrix );
  18411. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18412. this.skeleton = source.skeleton;
  18413. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18414. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18415. return this;
  18416. }
  18417. raycast( raycaster, intersects ) {
  18418. const material = this.material;
  18419. const matrixWorld = this.matrixWorld;
  18420. if ( material === undefined ) return;
  18421. // test with bounding sphere in world space
  18422. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18423. _sphere$5.copy( this.boundingSphere );
  18424. _sphere$5.applyMatrix4( matrixWorld );
  18425. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  18426. // convert ray to local space of skinned mesh
  18427. _inverseMatrix$2.copy( matrixWorld ).invert();
  18428. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18429. // test with bounding box in local space
  18430. if ( this.boundingBox !== null ) {
  18431. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18432. }
  18433. // test for intersections with geometry
  18434. this._computeIntersections( raycaster, intersects, _ray$2 );
  18435. }
  18436. getVertexPosition( index, target ) {
  18437. super.getVertexPosition( index, target );
  18438. this.applyBoneTransform( index, target );
  18439. return target;
  18440. }
  18441. /**
  18442. * Binds the given skeleton to the skinned mesh.
  18443. *
  18444. * @param {Skeleton} skeleton - The skeleton to bind.
  18445. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  18446. * the skinned mesh's world matrix will be used instead.
  18447. */
  18448. bind( skeleton, bindMatrix ) {
  18449. this.skeleton = skeleton;
  18450. if ( bindMatrix === undefined ) {
  18451. this.updateMatrixWorld( true );
  18452. this.skeleton.calculateInverses();
  18453. bindMatrix = this.matrixWorld;
  18454. }
  18455. this.bindMatrix.copy( bindMatrix );
  18456. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18457. }
  18458. /**
  18459. * This method sets the skinned mesh in the rest pose).
  18460. */
  18461. pose() {
  18462. this.skeleton.pose();
  18463. }
  18464. /**
  18465. * Normalizes the skin weights which are defined as a buffer attribute
  18466. * in the skinned mesh's geometry.
  18467. */
  18468. normalizeSkinWeights() {
  18469. const vector = new Vector4();
  18470. const skinWeight = this.geometry.attributes.skinWeight;
  18471. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18472. vector.fromBufferAttribute( skinWeight, i );
  18473. const scale = 1.0 / vector.manhattanLength();
  18474. if ( scale !== Infinity ) {
  18475. vector.multiplyScalar( scale );
  18476. } else {
  18477. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18478. }
  18479. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18480. }
  18481. }
  18482. updateMatrixWorld( force ) {
  18483. super.updateMatrixWorld( force );
  18484. if ( this.bindMode === AttachedBindMode ) {
  18485. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18486. } else if ( this.bindMode === DetachedBindMode ) {
  18487. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18488. } else {
  18489. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18490. }
  18491. }
  18492. /**
  18493. * Applies the bone transform associated with the given index to the given
  18494. * vertex position. Returns the updated vector.
  18495. *
  18496. * @param {number} index - The vertex index.
  18497. * @param {Vector3} target - The target object that is used to store the method's result.
  18498. * the skinned mesh's world matrix will be used instead.
  18499. * @return {Vector3} The updated vertex position.
  18500. */
  18501. applyBoneTransform( index, target ) {
  18502. const skeleton = this.skeleton;
  18503. const geometry = this.geometry;
  18504. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18505. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18506. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18507. target.set( 0, 0, 0 );
  18508. for ( let i = 0; i < 4; i ++ ) {
  18509. const weight = _skinWeight.getComponent( i );
  18510. if ( weight !== 0 ) {
  18511. const boneIndex = _skinIndex.getComponent( i );
  18512. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18513. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18514. }
  18515. }
  18516. return target.applyMatrix4( this.bindMatrixInverse );
  18517. }
  18518. }
  18519. /**
  18520. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  18521. * the {@link SkinnedMesh}.
  18522. *
  18523. * ```js
  18524. * const root = new THREE.Bone();
  18525. * const child = new THREE.Bone();
  18526. *
  18527. * root.add( child );
  18528. * child.position.y = 5;
  18529. * ```
  18530. *
  18531. * @augments Object3D
  18532. */
  18533. class Bone extends Object3D {
  18534. /**
  18535. * Constructs a new bone.
  18536. */
  18537. constructor() {
  18538. super();
  18539. /**
  18540. * This flag can be used for type testing.
  18541. *
  18542. * @type {boolean}
  18543. * @readonly
  18544. * @default true
  18545. */
  18546. this.isBone = true;
  18547. this.type = 'Bone';
  18548. }
  18549. }
  18550. /**
  18551. * Creates a texture directly from raw buffer data.
  18552. *
  18553. * The interpretation of the data depends on type and format: If the type is
  18554. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  18555. * texel data. If the format is `RGBAFormat`, data needs four values for
  18556. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  18557. *
  18558. * @augments Texture
  18559. */
  18560. class DataTexture extends Texture {
  18561. /**
  18562. * Constructs a new data texture.
  18563. *
  18564. * @param {?TypedArray} [data=null] - The buffer data.
  18565. * @param {number} [width=1] - The width of the texture.
  18566. * @param {number} [height=1] - The height of the texture.
  18567. * @param {number} [format=RGBAFormat] - The texture format.
  18568. * @param {number} [type=UnsignedByteType] - The texture type.
  18569. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  18570. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  18571. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  18572. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  18573. * @param {number} [minFilter=NearestFilter] - The min filter value.
  18574. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  18575. * @param {string} [colorSpace=NoColorSpace] - The color space.
  18576. */
  18577. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18578. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18579. /**
  18580. * This flag can be used for type testing.
  18581. *
  18582. * @type {boolean}
  18583. * @readonly
  18584. * @default true
  18585. */
  18586. this.isDataTexture = true;
  18587. /**
  18588. * The image definition of a data texture.
  18589. *
  18590. * @type {{data:TypedArray,width:number,height:number}}
  18591. */
  18592. this.image = { data: data, width: width, height: height };
  18593. /**
  18594. * Whether to generate mipmaps (if possible) for a texture.
  18595. *
  18596. * Overwritten and set to `false` by default.
  18597. *
  18598. * @type {boolean}
  18599. * @default false
  18600. */
  18601. this.generateMipmaps = false;
  18602. /**
  18603. * If set to `true`, the texture is flipped along the vertical axis when
  18604. * uploaded to the GPU.
  18605. *
  18606. * Overwritten and set to `false` by default.
  18607. *
  18608. * @type {boolean}
  18609. * @default false
  18610. */
  18611. this.flipY = false;
  18612. /**
  18613. * Specifies the alignment requirements for the start of each pixel row in memory.
  18614. *
  18615. * Overwritten and set to `1` by default.
  18616. *
  18617. * @type {boolean}
  18618. * @default 1
  18619. */
  18620. this.unpackAlignment = 1;
  18621. }
  18622. }
  18623. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18624. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18625. /**
  18626. * Class for representing the armatures in `three.js`. The skeleton
  18627. * is defined by a hierarchy of bones.
  18628. *
  18629. * ```js
  18630. * const bones = [];
  18631. *
  18632. * const shoulder = new THREE.Bone();
  18633. * const elbow = new THREE.Bone();
  18634. * const hand = new THREE.Bone();
  18635. *
  18636. * shoulder.add( elbow );
  18637. * elbow.add( hand );
  18638. *
  18639. * bones.push( shoulder , elbow, hand);
  18640. *
  18641. * shoulder.position.y = -5;
  18642. * elbow.position.y = 0;
  18643. * hand.position.y = 5;
  18644. *
  18645. * const armSkeleton = new THREE.Skeleton( bones );
  18646. * ```
  18647. */
  18648. class Skeleton {
  18649. /**
  18650. * Constructs a new skeleton.
  18651. *
  18652. * @param {Array<Bone>} [bones] - An array of bones.
  18653. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  18654. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  18655. */
  18656. constructor( bones = [], boneInverses = [] ) {
  18657. this.uuid = generateUUID();
  18658. /**
  18659. * An array of bones defining the skeleton.
  18660. *
  18661. * @type {Array<Bone>}
  18662. */
  18663. this.bones = bones.slice( 0 );
  18664. /**
  18665. * An array of bone inverse matrices.
  18666. *
  18667. * @type {Array<Matrix4>}
  18668. */
  18669. this.boneInverses = boneInverses;
  18670. /**
  18671. * An array buffer holding the bone data.
  18672. * Input data for {@link Skeleton#boneTexture}.
  18673. *
  18674. * @type {?Float32Array}
  18675. * @default null
  18676. */
  18677. this.boneMatrices = null;
  18678. /**
  18679. * A texture holding the bone data for use
  18680. * in the vertex shader.
  18681. *
  18682. * @type {?DataTexture}
  18683. * @default null
  18684. */
  18685. this.boneTexture = null;
  18686. this.init();
  18687. }
  18688. /**
  18689. * Initializes the skeleton. This method gets automatically called by the constructor
  18690. * but depending on how the skeleton is created it might be necessary to call this method
  18691. * manually.
  18692. */
  18693. init() {
  18694. const bones = this.bones;
  18695. const boneInverses = this.boneInverses;
  18696. this.boneMatrices = new Float32Array( bones.length * 16 );
  18697. // calculate inverse bone matrices if necessary
  18698. if ( boneInverses.length === 0 ) {
  18699. this.calculateInverses();
  18700. } else {
  18701. // handle special case
  18702. if ( bones.length !== boneInverses.length ) {
  18703. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18704. this.boneInverses = [];
  18705. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18706. this.boneInverses.push( new Matrix4() );
  18707. }
  18708. }
  18709. }
  18710. }
  18711. /**
  18712. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  18713. * and fills it with new matrices.
  18714. */
  18715. calculateInverses() {
  18716. this.boneInverses.length = 0;
  18717. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18718. const inverse = new Matrix4();
  18719. if ( this.bones[ i ] ) {
  18720. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18721. }
  18722. this.boneInverses.push( inverse );
  18723. }
  18724. }
  18725. /**
  18726. * Resets the skeleton to the base pose.
  18727. */
  18728. pose() {
  18729. // recover the bind-time world matrices
  18730. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18731. const bone = this.bones[ i ];
  18732. if ( bone ) {
  18733. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18734. }
  18735. }
  18736. // compute the local matrices, positions, rotations and scales
  18737. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18738. const bone = this.bones[ i ];
  18739. if ( bone ) {
  18740. if ( bone.parent && bone.parent.isBone ) {
  18741. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18742. bone.matrix.multiply( bone.matrixWorld );
  18743. } else {
  18744. bone.matrix.copy( bone.matrixWorld );
  18745. }
  18746. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18747. }
  18748. }
  18749. }
  18750. /**
  18751. * Resets the skeleton to the base pose.
  18752. */
  18753. update() {
  18754. const bones = this.bones;
  18755. const boneInverses = this.boneInverses;
  18756. const boneMatrices = this.boneMatrices;
  18757. const boneTexture = this.boneTexture;
  18758. // flatten bone matrices to array
  18759. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18760. // compute the offset between the current and the original transform
  18761. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18762. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18763. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18764. }
  18765. if ( boneTexture !== null ) {
  18766. boneTexture.needsUpdate = true;
  18767. }
  18768. }
  18769. /**
  18770. * Returns a new skeleton with copied values from this instance.
  18771. *
  18772. * @return {Skeleton} A clone of this instance.
  18773. */
  18774. clone() {
  18775. return new Skeleton( this.bones, this.boneInverses );
  18776. }
  18777. /**
  18778. * Computes a data texture for passing bone data to the vertex shader.
  18779. *
  18780. * @return {Skeleton} A reference of this instance.
  18781. */
  18782. computeBoneTexture() {
  18783. // layout (1 matrix = 4 pixels)
  18784. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18785. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18786. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18787. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18788. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18789. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18790. size = Math.ceil( size / 4 ) * 4;
  18791. size = Math.max( size, 4 );
  18792. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18793. boneMatrices.set( this.boneMatrices ); // copy current values
  18794. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18795. boneTexture.needsUpdate = true;
  18796. this.boneMatrices = boneMatrices;
  18797. this.boneTexture = boneTexture;
  18798. return this;
  18799. }
  18800. /**
  18801. * Searches through the skeleton's bone array and returns the first with a
  18802. * matching name.
  18803. *
  18804. * @param {string} name - The name of the bone.
  18805. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  18806. */
  18807. getBoneByName( name ) {
  18808. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18809. const bone = this.bones[ i ];
  18810. if ( bone.name === name ) {
  18811. return bone;
  18812. }
  18813. }
  18814. return undefined;
  18815. }
  18816. /**
  18817. * Frees the GPU-related resources allocated by this instance. Call this
  18818. * method whenever this instance is no longer used in your app.
  18819. */
  18820. dispose( ) {
  18821. if ( this.boneTexture !== null ) {
  18822. this.boneTexture.dispose();
  18823. this.boneTexture = null;
  18824. }
  18825. }
  18826. /**
  18827. * Setups the skeleton by the given JSON and bones.
  18828. *
  18829. * @param {Object} json - The skeleton as serialized JSON.
  18830. * @param {Object<string, Bone>} bones - An array of bones.
  18831. * @return {Skeleton} A reference of this instance.
  18832. */
  18833. fromJSON( json, bones ) {
  18834. this.uuid = json.uuid;
  18835. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18836. const uuid = json.bones[ i ];
  18837. let bone = bones[ uuid ];
  18838. if ( bone === undefined ) {
  18839. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18840. bone = new Bone();
  18841. }
  18842. this.bones.push( bone );
  18843. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18844. }
  18845. this.init();
  18846. return this;
  18847. }
  18848. /**
  18849. * Serializes the skeleton into JSON.
  18850. *
  18851. * @return {Object} A JSON object representing the serialized skeleton.
  18852. * @see {@link ObjectLoader#parse}
  18853. */
  18854. toJSON() {
  18855. const data = {
  18856. metadata: {
  18857. version: 4.7,
  18858. type: 'Skeleton',
  18859. generator: 'Skeleton.toJSON'
  18860. },
  18861. bones: [],
  18862. boneInverses: []
  18863. };
  18864. data.uuid = this.uuid;
  18865. const bones = this.bones;
  18866. const boneInverses = this.boneInverses;
  18867. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18868. const bone = bones[ i ];
  18869. data.bones.push( bone.uuid );
  18870. const boneInverse = boneInverses[ i ];
  18871. data.boneInverses.push( boneInverse.toArray() );
  18872. }
  18873. return data;
  18874. }
  18875. }
  18876. /**
  18877. * An instanced version of a buffer attribute.
  18878. *
  18879. * @augments BufferAttribute
  18880. */
  18881. class InstancedBufferAttribute extends BufferAttribute {
  18882. /**
  18883. * Constructs a new instanced buffer attribute.
  18884. *
  18885. * @param {TypedArray} array - The array holding the attribute data.
  18886. * @param {number} itemSize - The item size.
  18887. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  18888. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  18889. */
  18890. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18891. super( array, itemSize, normalized );
  18892. /**
  18893. * This flag can be used for type testing.
  18894. *
  18895. * @type {boolean}
  18896. * @readonly
  18897. * @default true
  18898. */
  18899. this.isInstancedBufferAttribute = true;
  18900. /**
  18901. * Defines how often a value of this buffer attribute should be repeated. A
  18902. * value of one means that each value of the instanced attribute is used for
  18903. * a single instance. A value of two means that each value is used for two
  18904. * consecutive instances (and so on).
  18905. *
  18906. * @type {number}
  18907. * @default 1
  18908. */
  18909. this.meshPerAttribute = meshPerAttribute;
  18910. }
  18911. copy( source ) {
  18912. super.copy( source );
  18913. this.meshPerAttribute = source.meshPerAttribute;
  18914. return this;
  18915. }
  18916. toJSON() {
  18917. const data = super.toJSON();
  18918. data.meshPerAttribute = this.meshPerAttribute;
  18919. data.isInstancedBufferAttribute = true;
  18920. return data;
  18921. }
  18922. }
  18923. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18924. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18925. const _instanceIntersects = [];
  18926. const _box3 = /*@__PURE__*/ new Box3();
  18927. const _identity = /*@__PURE__*/ new Matrix4();
  18928. const _mesh$1 = /*@__PURE__*/ new Mesh();
  18929. const _sphere$4 = /*@__PURE__*/ new Sphere();
  18930. /**
  18931. * A special version of a mesh with instanced rendering support. Use
  18932. * this class if you have to render a large number of objects with the same
  18933. * geometry and material(s) but with different world transformations. The usage
  18934. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  18935. * improve the overall rendering performance in your application.
  18936. *
  18937. * @augments Mesh
  18938. */
  18939. class InstancedMesh extends Mesh {
  18940. /**
  18941. * Constructs a new instanced mesh.
  18942. *
  18943. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18944. * @param {Material|Array<Material>} [material] - The mesh material.
  18945. * @param {number} count - The number of instances.
  18946. */
  18947. constructor( geometry, material, count ) {
  18948. super( geometry, material );
  18949. /**
  18950. * This flag can be used for type testing.
  18951. *
  18952. * @type {boolean}
  18953. * @readonly
  18954. * @default true
  18955. */
  18956. this.isInstancedMesh = true;
  18957. /**
  18958. * Represents the local transformation of all instances. You have to set its
  18959. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18960. * via {@link InstancedMesh#setMatrixAt}.
  18961. *
  18962. * @type {InstancedBufferAttribute}
  18963. */
  18964. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18965. /**
  18966. * Represents the color of all instances. You have to set its
  18967. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18968. * via {@link InstancedMesh#setColorAt}.
  18969. *
  18970. * @type {?InstancedBufferAttribute}
  18971. * @default null
  18972. */
  18973. this.instanceColor = null;
  18974. /**
  18975. * Represents the morph target weights of all instances. You have to set its
  18976. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  18977. * via {@link InstancedMesh#setMorphAt}.
  18978. *
  18979. * @type {?DataTexture}
  18980. * @default null
  18981. */
  18982. this.morphTexture = null;
  18983. /**
  18984. * The number of instances.
  18985. *
  18986. * @type {number}
  18987. */
  18988. this.count = count;
  18989. /**
  18990. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  18991. *
  18992. * @type {?Box3}
  18993. * @default null
  18994. */
  18995. this.boundingBox = null;
  18996. /**
  18997. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  18998. *
  18999. * @type {?Sphere}
  19000. * @default null
  19001. */
  19002. this.boundingSphere = null;
  19003. for ( let i = 0; i < count; i ++ ) {
  19004. this.setMatrixAt( i, _identity );
  19005. }
  19006. }
  19007. /**
  19008. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  19009. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  19010. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19011. */
  19012. computeBoundingBox() {
  19013. const geometry = this.geometry;
  19014. const count = this.count;
  19015. if ( this.boundingBox === null ) {
  19016. this.boundingBox = new Box3();
  19017. }
  19018. if ( geometry.boundingBox === null ) {
  19019. geometry.computeBoundingBox();
  19020. }
  19021. this.boundingBox.makeEmpty();
  19022. for ( let i = 0; i < count; i ++ ) {
  19023. this.getMatrixAt( i, _instanceLocalMatrix );
  19024. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19025. this.boundingBox.union( _box3 );
  19026. }
  19027. }
  19028. /**
  19029. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  19030. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  19031. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19032. */
  19033. computeBoundingSphere() {
  19034. const geometry = this.geometry;
  19035. const count = this.count;
  19036. if ( this.boundingSphere === null ) {
  19037. this.boundingSphere = new Sphere();
  19038. }
  19039. if ( geometry.boundingSphere === null ) {
  19040. geometry.computeBoundingSphere();
  19041. }
  19042. this.boundingSphere.makeEmpty();
  19043. for ( let i = 0; i < count; i ++ ) {
  19044. this.getMatrixAt( i, _instanceLocalMatrix );
  19045. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19046. this.boundingSphere.union( _sphere$4 );
  19047. }
  19048. }
  19049. copy( source, recursive ) {
  19050. super.copy( source, recursive );
  19051. this.instanceMatrix.copy( source.instanceMatrix );
  19052. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  19053. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19054. this.count = source.count;
  19055. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19056. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19057. return this;
  19058. }
  19059. /**
  19060. * Gets the color of the defined instance.
  19061. *
  19062. * @param {number} index - The instance index.
  19063. * @param {Color} color - The target object that is used to store the method's result.
  19064. */
  19065. getColorAt( index, color ) {
  19066. color.fromArray( this.instanceColor.array, index * 3 );
  19067. }
  19068. /**
  19069. * Gets the local transformation matrix of the defined instance.
  19070. *
  19071. * @param {number} index - The instance index.
  19072. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19073. */
  19074. getMatrixAt( index, matrix ) {
  19075. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19076. }
  19077. /**
  19078. * Gets the morph target weights of the defined instance.
  19079. *
  19080. * @param {number} index - The instance index.
  19081. * @param {Mesh} object - The target object that is used to store the method's result.
  19082. */
  19083. getMorphAt( index, object ) {
  19084. const objectInfluences = object.morphTargetInfluences;
  19085. const array = this.morphTexture.source.data.data;
  19086. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  19087. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  19088. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19089. objectInfluences[ i ] = array[ dataIndex + i ];
  19090. }
  19091. }
  19092. raycast( raycaster, intersects ) {
  19093. const matrixWorld = this.matrixWorld;
  19094. const raycastTimes = this.count;
  19095. _mesh$1.geometry = this.geometry;
  19096. _mesh$1.material = this.material;
  19097. if ( _mesh$1.material === undefined ) return;
  19098. // test with bounding sphere first
  19099. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19100. _sphere$4.copy( this.boundingSphere );
  19101. _sphere$4.applyMatrix4( matrixWorld );
  19102. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  19103. // now test each instance
  19104. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19105. // calculate the world matrix for each instance
  19106. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19107. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19108. // the mesh represents this single instance
  19109. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19110. _mesh$1.raycast( raycaster, _instanceIntersects );
  19111. // process the result of raycast
  19112. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19113. const intersect = _instanceIntersects[ i ];
  19114. intersect.instanceId = instanceId;
  19115. intersect.object = this;
  19116. intersects.push( intersect );
  19117. }
  19118. _instanceIntersects.length = 0;
  19119. }
  19120. }
  19121. /**
  19122. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  19123. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  19124. *
  19125. * @param {number} index - The instance index.
  19126. * @param {Color} color - The instance color.
  19127. */
  19128. setColorAt( index, color ) {
  19129. if ( this.instanceColor === null ) {
  19130. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  19131. }
  19132. color.toArray( this.instanceColor.array, index * 3 );
  19133. }
  19134. /**
  19135. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  19136. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  19137. *
  19138. * @param {number} index - The instance index.
  19139. * @param {Matrix4} matrix - The local transformation.
  19140. */
  19141. setMatrixAt( index, matrix ) {
  19142. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19143. }
  19144. /**
  19145. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  19146. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  19147. *
  19148. * @param {number} index - The instance index.
  19149. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  19150. * of a single instance.
  19151. */
  19152. setMorphAt( index, object ) {
  19153. const objectInfluences = object.morphTargetInfluences;
  19154. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  19155. if ( this.morphTexture === null ) {
  19156. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  19157. }
  19158. const array = this.morphTexture.source.data.data;
  19159. let morphInfluencesSum = 0;
  19160. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19161. morphInfluencesSum += objectInfluences[ i ];
  19162. }
  19163. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  19164. const dataIndex = len * index;
  19165. array[ dataIndex ] = morphBaseInfluence;
  19166. array.set( objectInfluences, dataIndex + 1 );
  19167. }
  19168. updateMorphTargets() {
  19169. }
  19170. /**
  19171. * Frees the GPU-related resources allocated by this instance. Call this
  19172. * method whenever this instance is no longer used in your app.
  19173. */
  19174. dispose() {
  19175. this.dispatchEvent( { type: 'dispose' } );
  19176. if ( this.morphTexture !== null ) {
  19177. this.morphTexture.dispose();
  19178. this.morphTexture = null;
  19179. }
  19180. }
  19181. }
  19182. const _vector1 = /*@__PURE__*/ new Vector3();
  19183. const _vector2 = /*@__PURE__*/ new Vector3();
  19184. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  19185. /**
  19186. * A two dimensional surface that extends infinitely in 3D space, represented
  19187. * in [Hessian normal form]{@link http://mathworld.wolfram.com/HessianNormalForm.html}
  19188. * by a unit length normal vector and a constant.
  19189. */
  19190. class Plane {
  19191. /**
  19192. * Constructs a new plane.
  19193. *
  19194. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  19195. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  19196. */
  19197. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  19198. /**
  19199. * This flag can be used for type testing.
  19200. *
  19201. * @type {boolean}
  19202. * @readonly
  19203. * @default true
  19204. */
  19205. this.isPlane = true;
  19206. /**
  19207. * A unit length vector defining the normal of the plane.
  19208. *
  19209. * @type {Vector3}
  19210. */
  19211. this.normal = normal;
  19212. /**
  19213. * The signed distance from the origin to the plane.
  19214. *
  19215. * @type {number}
  19216. * @default 0
  19217. */
  19218. this.constant = constant;
  19219. }
  19220. /**
  19221. * Sets the plane components by copying the given values.
  19222. *
  19223. * @param {Vector3} normal - The normal.
  19224. * @param {number} constant - The constant.
  19225. * @return {Plane} A reference to this plane.
  19226. */
  19227. set( normal, constant ) {
  19228. this.normal.copy( normal );
  19229. this.constant = constant;
  19230. return this;
  19231. }
  19232. /**
  19233. * Sets the plane components by defining `x`, `y`, `z` as the
  19234. * plane normal and `w` as the constant.
  19235. *
  19236. * @param {number} x - The value for the normal's x component.
  19237. * @param {number} y - The value for the normal's y component.
  19238. * @param {number} z - The value for the normal's z component.
  19239. * @param {number} w - The constant value.
  19240. * @return {Plane} A reference to this plane.
  19241. */
  19242. setComponents( x, y, z, w ) {
  19243. this.normal.set( x, y, z );
  19244. this.constant = w;
  19245. return this;
  19246. }
  19247. /**
  19248. * Sets the plane from the given normal and coplanar point (that is a point
  19249. * that lies onto the plane).
  19250. *
  19251. * @param {Vector3} normal - The normal.
  19252. * @param {Vector3} point - A coplanar point.
  19253. * @return {Plane} A reference to this plane.
  19254. */
  19255. setFromNormalAndCoplanarPoint( normal, point ) {
  19256. this.normal.copy( normal );
  19257. this.constant = - point.dot( this.normal );
  19258. return this;
  19259. }
  19260. /**
  19261. * Sets the plane from three coplanar points. The winding order is
  19262. * assumed to be counter-clockwise, and determines the direction of
  19263. * the plane normal.
  19264. *
  19265. * @param {Vector3} a - The first coplanar point.
  19266. * @param {Vector3} b - The second coplanar point.
  19267. * @param {Vector3} c - The third coplanar point.
  19268. * @return {Plane} A reference to this plane.
  19269. */
  19270. setFromCoplanarPoints( a, b, c ) {
  19271. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  19272. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  19273. this.setFromNormalAndCoplanarPoint( normal, a );
  19274. return this;
  19275. }
  19276. /**
  19277. * Copies the values of the given plane to this instance.
  19278. *
  19279. * @param {Plane} plane - The plane to copy.
  19280. * @return {Plane} A reference to this plane.
  19281. */
  19282. copy( plane ) {
  19283. this.normal.copy( plane.normal );
  19284. this.constant = plane.constant;
  19285. return this;
  19286. }
  19287. /**
  19288. * Normalizes the plane normal and adjusts the constant accordingly.
  19289. *
  19290. * @return {Plane} A reference to this plane.
  19291. */
  19292. normalize() {
  19293. // Note: will lead to a divide by zero if the plane is invalid.
  19294. const inverseNormalLength = 1.0 / this.normal.length();
  19295. this.normal.multiplyScalar( inverseNormalLength );
  19296. this.constant *= inverseNormalLength;
  19297. return this;
  19298. }
  19299. /**
  19300. * Negates both the plane normal and the constant.
  19301. *
  19302. * @return {Plane} A reference to this plane.
  19303. */
  19304. negate() {
  19305. this.constant *= -1;
  19306. this.normal.negate();
  19307. return this;
  19308. }
  19309. /**
  19310. * Returns the signed distance from the given point to this plane.
  19311. *
  19312. * @param {Vector3} point - The point to compute the distance for.
  19313. * @return {number} The signed distance.
  19314. */
  19315. distanceToPoint( point ) {
  19316. return this.normal.dot( point ) + this.constant;
  19317. }
  19318. /**
  19319. * Returns the signed distance from the given sphere to this plane.
  19320. *
  19321. * @param {Sphere} sphere - The sphere to compute the distance for.
  19322. * @return {number} The signed distance.
  19323. */
  19324. distanceToSphere( sphere ) {
  19325. return this.distanceToPoint( sphere.center ) - sphere.radius;
  19326. }
  19327. /**
  19328. * Projects a the given point onto the plane.
  19329. *
  19330. * @param {Vector3} point - The point to project.
  19331. * @param {Vector3} target - The target vector that is used to store the method's result.
  19332. * @return {Vector3} The projected point on the plane.
  19333. */
  19334. projectPoint( point, target ) {
  19335. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  19336. }
  19337. /**
  19338. * Returns the intersection point of the passed line and the plane. Returns
  19339. * `null` if the line does not intersect. Returns the line's starting point if
  19340. * the line is coplanar with the plane.
  19341. *
  19342. * @param {Line3} line - The line to compute the intersection for.
  19343. * @param {Vector3} target - The target vector that is used to store the method's result.
  19344. * @return {?Vector3} The intersection point.
  19345. */
  19346. intersectLine( line, target ) {
  19347. const direction = line.delta( _vector1 );
  19348. const denominator = this.normal.dot( direction );
  19349. if ( denominator === 0 ) {
  19350. // line is coplanar, return origin
  19351. if ( this.distanceToPoint( line.start ) === 0 ) {
  19352. return target.copy( line.start );
  19353. }
  19354. // Unsure if this is the correct method to handle this case.
  19355. return null;
  19356. }
  19357. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  19358. if ( t < 0 || t > 1 ) {
  19359. return null;
  19360. }
  19361. return target.copy( line.start ).addScaledVector( direction, t );
  19362. }
  19363. /**
  19364. * Returns `true` if the given line segment intersects with (passes through) the plane.
  19365. *
  19366. * @param {Line3} line - The line to test.
  19367. * @return {boolean} Whether the given line segment intersects with the plane or not.
  19368. */
  19369. intersectsLine( line ) {
  19370. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  19371. const startSign = this.distanceToPoint( line.start );
  19372. const endSign = this.distanceToPoint( line.end );
  19373. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  19374. }
  19375. /**
  19376. * Returns `true` if the given bounding box intersects with the plane.
  19377. *
  19378. * @param {Box3} box - The bounding box to test.
  19379. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  19380. */
  19381. intersectsBox( box ) {
  19382. return box.intersectsPlane( this );
  19383. }
  19384. /**
  19385. * Returns `true` if the given bounding sphere intersects with the plane.
  19386. *
  19387. * @param {Sphere} sphere - The bounding sphere to test.
  19388. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  19389. */
  19390. intersectsSphere( sphere ) {
  19391. return sphere.intersectsPlane( this );
  19392. }
  19393. /**
  19394. * Returns a coplanar vector to the plane, by calculating the
  19395. * projection of the normal at the origin onto the plane.
  19396. *
  19397. * @param {Vector3} target - The target vector that is used to store the method's result.
  19398. * @return {Vector3} The coplanar point.
  19399. */
  19400. coplanarPoint( target ) {
  19401. return target.copy( this.normal ).multiplyScalar( - this.constant );
  19402. }
  19403. /**
  19404. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  19405. *
  19406. * The optional normal matrix can be pre-computed like so:
  19407. * ```js
  19408. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  19409. * ```
  19410. *
  19411. * @param {Matrix4} matrix - The transformation matrix.
  19412. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  19413. * @return {Plane} A reference to this plane.
  19414. */
  19415. applyMatrix4( matrix, optionalNormalMatrix ) {
  19416. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  19417. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  19418. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  19419. this.constant = - referencePoint.dot( normal );
  19420. return this;
  19421. }
  19422. /**
  19423. * Translates the plane by the distance defined by the given offset vector.
  19424. * Note that this only affects the plane constant and will not affect the normal vector.
  19425. *
  19426. * @param {Vector3} offset - The offset vector.
  19427. * @return {Plane} A reference to this plane.
  19428. */
  19429. translate( offset ) {
  19430. this.constant -= offset.dot( this.normal );
  19431. return this;
  19432. }
  19433. /**
  19434. * Returns `true` if this plane is equal with the given one.
  19435. *
  19436. * @param {Plane} plane - The plane to test for equality.
  19437. * @return {boolean} Whether this plane is equal with the given one.
  19438. */
  19439. equals( plane ) {
  19440. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  19441. }
  19442. /**
  19443. * Returns a new plane with copied values from this instance.
  19444. *
  19445. * @return {Plane} A clone of this instance.
  19446. */
  19447. clone() {
  19448. return new this.constructor().copy( this );
  19449. }
  19450. }
  19451. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19452. const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 );
  19453. const _vector$6 = /*@__PURE__*/ new Vector3();
  19454. /**
  19455. * Frustums are used to determine what is inside the camera's field of view.
  19456. * They help speed up the rendering process - objects which lie outside a camera's
  19457. * frustum can safely be excluded from rendering.
  19458. *
  19459. * This class is mainly intended for use internally by a renderer.
  19460. */
  19461. class Frustum {
  19462. /**
  19463. * Constructs a new frustum.
  19464. *
  19465. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19466. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19467. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19468. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19469. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19470. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19471. */
  19472. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  19473. /**
  19474. * This array holds the planes that enclose the frustum.
  19475. *
  19476. * @type {Array<Plane>}
  19477. */
  19478. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  19479. }
  19480. /**
  19481. * Sets the frustum planes by copying the given planes.
  19482. *
  19483. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19484. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19485. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19486. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19487. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19488. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19489. * @return {Frustum} A reference to this frustum.
  19490. */
  19491. set( p0, p1, p2, p3, p4, p5 ) {
  19492. const planes = this.planes;
  19493. planes[ 0 ].copy( p0 );
  19494. planes[ 1 ].copy( p1 );
  19495. planes[ 2 ].copy( p2 );
  19496. planes[ 3 ].copy( p3 );
  19497. planes[ 4 ].copy( p4 );
  19498. planes[ 5 ].copy( p5 );
  19499. return this;
  19500. }
  19501. /**
  19502. * Copies the values of the given frustum to this instance.
  19503. *
  19504. * @param {Frustum} frustum - The frustum to copy.
  19505. * @return {Frustum} A reference to this frustum.
  19506. */
  19507. copy( frustum ) {
  19508. const planes = this.planes;
  19509. for ( let i = 0; i < 6; i ++ ) {
  19510. planes[ i ].copy( frustum.planes[ i ] );
  19511. }
  19512. return this;
  19513. }
  19514. /**
  19515. * Sets the frustum planes from the given projection matrix.
  19516. *
  19517. * @param {Matrix4} m - The projection matrix.
  19518. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  19519. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  19520. * @return {Frustum} A reference to this frustum.
  19521. */
  19522. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  19523. const planes = this.planes;
  19524. const me = m.elements;
  19525. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  19526. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  19527. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  19528. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  19529. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  19530. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  19531. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  19532. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  19533. if ( reversedDepth ) {
  19534. planes[ 4 ].setComponents( me2, me6, me10, me14 ).normalize(); // far
  19535. planes[ 5 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // near
  19536. } else {
  19537. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // far
  19538. if ( coordinateSystem === WebGLCoordinateSystem ) {
  19539. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); // near
  19540. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  19541. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); // near
  19542. } else {
  19543. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  19544. }
  19545. }
  19546. return this;
  19547. }
  19548. /**
  19549. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  19550. *
  19551. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  19552. *
  19553. * @param {Object3D} object - The 3D object to test.
  19554. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  19555. */
  19556. intersectsObject( object ) {
  19557. if ( object.boundingSphere !== undefined ) {
  19558. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  19559. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  19560. } else {
  19561. const geometry = object.geometry;
  19562. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19563. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  19564. }
  19565. return this.intersectsSphere( _sphere$3 );
  19566. }
  19567. /**
  19568. * Returns `true` if the given sprite is intersecting this frustum.
  19569. *
  19570. * @param {Sprite} sprite - The sprite to test.
  19571. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  19572. */
  19573. intersectsSprite( sprite ) {
  19574. _sphere$3.center.set( 0, 0, 0 );
  19575. const offset = _defaultSpriteCenter.distanceTo( sprite.center );
  19576. _sphere$3.radius = 0.7071067811865476 + offset;
  19577. _sphere$3.applyMatrix4( sprite.matrixWorld );
  19578. return this.intersectsSphere( _sphere$3 );
  19579. }
  19580. /**
  19581. * Returns `true` if the given bounding sphere is intersecting this frustum.
  19582. *
  19583. * @param {Sphere} sphere - The bounding sphere to test.
  19584. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  19585. */
  19586. intersectsSphere( sphere ) {
  19587. const planes = this.planes;
  19588. const center = sphere.center;
  19589. const negRadius = - sphere.radius;
  19590. for ( let i = 0; i < 6; i ++ ) {
  19591. const distance = planes[ i ].distanceToPoint( center );
  19592. if ( distance < negRadius ) {
  19593. return false;
  19594. }
  19595. }
  19596. return true;
  19597. }
  19598. /**
  19599. * Returns `true` if the given bounding box is intersecting this frustum.
  19600. *
  19601. * @param {Box3} box - The bounding box to test.
  19602. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  19603. */
  19604. intersectsBox( box ) {
  19605. const planes = this.planes;
  19606. for ( let i = 0; i < 6; i ++ ) {
  19607. const plane = planes[ i ];
  19608. // corner at max distance
  19609. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  19610. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  19611. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  19612. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  19613. return false;
  19614. }
  19615. }
  19616. return true;
  19617. }
  19618. /**
  19619. * Returns `true` if the given point lies within the frustum.
  19620. *
  19621. * @param {Vector3} point - The point to test.
  19622. * @return {boolean} Whether the point lies within this frustum or not.
  19623. */
  19624. containsPoint( point ) {
  19625. const planes = this.planes;
  19626. for ( let i = 0; i < 6; i ++ ) {
  19627. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  19628. return false;
  19629. }
  19630. }
  19631. return true;
  19632. }
  19633. /**
  19634. * Returns a new frustum with copied values from this instance.
  19635. *
  19636. * @return {Frustum} A clone of this instance.
  19637. */
  19638. clone() {
  19639. return new this.constructor().copy( this );
  19640. }
  19641. }
  19642. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  19643. const _frustum$1 = /*@__PURE__*/ new Frustum();
  19644. /**
  19645. * FrustumArray is used to determine if an object is visible in at least one camera
  19646. * from an array of cameras. This is particularly useful for multi-view renderers.
  19647. */
  19648. class FrustumArray {
  19649. /**
  19650. * Constructs a new frustum array.
  19651. *
  19652. */
  19653. constructor() {
  19654. /**
  19655. * The coordinate system to use.
  19656. *
  19657. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  19658. * @default WebGLCoordinateSystem
  19659. */
  19660. this.coordinateSystem = WebGLCoordinateSystem;
  19661. }
  19662. /**
  19663. * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
  19664. * from the camera array.
  19665. *
  19666. * @param {Object3D} object - The 3D object to test.
  19667. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19668. * @return {boolean} Whether the 3D object is visible in any camera.
  19669. */
  19670. intersectsObject( object, cameraArray ) {
  19671. if ( ! cameraArray.isArrayCamera || cameraArray.cameras.length === 0 ) {
  19672. return false;
  19673. }
  19674. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19675. const camera = cameraArray.cameras[ i ];
  19676. _projScreenMatrix$2.multiplyMatrices(
  19677. camera.projectionMatrix,
  19678. camera.matrixWorldInverse
  19679. );
  19680. _frustum$1.setFromProjectionMatrix(
  19681. _projScreenMatrix$2,
  19682. camera.coordinateSystem,
  19683. camera.reversedDepth
  19684. );
  19685. if ( _frustum$1.intersectsObject( object ) ) {
  19686. return true; // Object is visible in at least one camera
  19687. }
  19688. }
  19689. return false; // Not visible in any camera
  19690. }
  19691. /**
  19692. * Returns `true` if the given sprite is intersecting any frustum
  19693. * from the camera array.
  19694. *
  19695. * @param {Sprite} sprite - The sprite to test.
  19696. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19697. * @return {boolean} Whether the sprite is visible in any camera.
  19698. */
  19699. intersectsSprite( sprite, cameraArray ) {
  19700. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19701. return false;
  19702. }
  19703. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19704. const camera = cameraArray.cameras[ i ];
  19705. _projScreenMatrix$2.multiplyMatrices(
  19706. camera.projectionMatrix,
  19707. camera.matrixWorldInverse
  19708. );
  19709. _frustum$1.setFromProjectionMatrix(
  19710. _projScreenMatrix$2,
  19711. camera.coordinateSystem,
  19712. camera.reversedDepth
  19713. );
  19714. if ( _frustum$1.intersectsSprite( sprite ) ) {
  19715. return true; // Sprite is visible in at least one camera
  19716. }
  19717. }
  19718. return false; // Not visible in any camera
  19719. }
  19720. /**
  19721. * Returns `true` if the given bounding sphere is intersecting any frustum
  19722. * from the camera array.
  19723. *
  19724. * @param {Sphere} sphere - The bounding sphere to test.
  19725. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19726. * @return {boolean} Whether the sphere is visible in any camera.
  19727. */
  19728. intersectsSphere( sphere, cameraArray ) {
  19729. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19730. return false;
  19731. }
  19732. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19733. const camera = cameraArray.cameras[ i ];
  19734. _projScreenMatrix$2.multiplyMatrices(
  19735. camera.projectionMatrix,
  19736. camera.matrixWorldInverse
  19737. );
  19738. _frustum$1.setFromProjectionMatrix(
  19739. _projScreenMatrix$2,
  19740. camera.coordinateSystem,
  19741. camera.reversedDepth
  19742. );
  19743. if ( _frustum$1.intersectsSphere( sphere ) ) {
  19744. return true; // Sphere is visible in at least one camera
  19745. }
  19746. }
  19747. return false; // Not visible in any camera
  19748. }
  19749. /**
  19750. * Returns `true` if the given bounding box is intersecting any frustum
  19751. * from the camera array.
  19752. *
  19753. * @param {Box3} box - The bounding box to test.
  19754. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19755. * @return {boolean} Whether the box is visible in any camera.
  19756. */
  19757. intersectsBox( box, cameraArray ) {
  19758. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19759. return false;
  19760. }
  19761. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19762. const camera = cameraArray.cameras[ i ];
  19763. _projScreenMatrix$2.multiplyMatrices(
  19764. camera.projectionMatrix,
  19765. camera.matrixWorldInverse
  19766. );
  19767. _frustum$1.setFromProjectionMatrix(
  19768. _projScreenMatrix$2,
  19769. camera.coordinateSystem,
  19770. camera.reversedDepth
  19771. );
  19772. if ( _frustum$1.intersectsBox( box ) ) {
  19773. return true; // Box is visible in at least one camera
  19774. }
  19775. }
  19776. return false; // Not visible in any camera
  19777. }
  19778. /**
  19779. * Returns `true` if the given point lies within any frustum
  19780. * from the camera array.
  19781. *
  19782. * @param {Vector3} point - The point to test.
  19783. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19784. * @return {boolean} Whether the point is visible in any camera.
  19785. */
  19786. containsPoint( point, cameraArray ) {
  19787. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19788. return false;
  19789. }
  19790. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19791. const camera = cameraArray.cameras[ i ];
  19792. _projScreenMatrix$2.multiplyMatrices(
  19793. camera.projectionMatrix,
  19794. camera.matrixWorldInverse
  19795. );
  19796. _frustum$1.setFromProjectionMatrix(
  19797. _projScreenMatrix$2,
  19798. camera.coordinateSystem,
  19799. camera.reversedDepth
  19800. );
  19801. if ( _frustum$1.containsPoint( point ) ) {
  19802. return true; // Point is visible in at least one camera
  19803. }
  19804. }
  19805. return false; // Not visible in any camera
  19806. }
  19807. /**
  19808. * Returns a new frustum array with copied values from this instance.
  19809. *
  19810. * @return {FrustumArray} A clone of this instance.
  19811. */
  19812. clone() {
  19813. return new FrustumArray();
  19814. }
  19815. }
  19816. function ascIdSort( a, b ) {
  19817. return a - b;
  19818. }
  19819. function sortOpaque( a, b ) {
  19820. return a.z - b.z;
  19821. }
  19822. function sortTransparent( a, b ) {
  19823. return b.z - a.z;
  19824. }
  19825. class MultiDrawRenderList {
  19826. constructor() {
  19827. this.index = 0;
  19828. this.pool = [];
  19829. this.list = [];
  19830. }
  19831. push( start, count, z, index ) {
  19832. const pool = this.pool;
  19833. const list = this.list;
  19834. if ( this.index >= pool.length ) {
  19835. pool.push( {
  19836. start: -1,
  19837. count: -1,
  19838. z: -1,
  19839. index: -1,
  19840. } );
  19841. }
  19842. const item = pool[ this.index ];
  19843. list.push( item );
  19844. this.index ++;
  19845. item.start = start;
  19846. item.count = count;
  19847. item.z = z;
  19848. item.index = index;
  19849. }
  19850. reset() {
  19851. this.list.length = 0;
  19852. this.index = 0;
  19853. }
  19854. }
  19855. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  19856. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  19857. const _frustum = /*@__PURE__*/ new Frustum();
  19858. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  19859. const _box$1 = /*@__PURE__*/ new Box3();
  19860. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19861. const _vector$5 = /*@__PURE__*/ new Vector3();
  19862. const _forward$1 = /*@__PURE__*/ new Vector3();
  19863. const _temp = /*@__PURE__*/ new Vector3();
  19864. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19865. const _mesh = /*@__PURE__*/ new Mesh();
  19866. const _batchIntersects = [];
  19867. // copies data from attribute "src" into "target" starting at "targetOffset"
  19868. function copyAttributeData( src, target, targetOffset = 0 ) {
  19869. const itemSize = target.itemSize;
  19870. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19871. // use the component getters and setters if the array data cannot
  19872. // be copied directly
  19873. const vertexCount = src.count;
  19874. for ( let i = 0; i < vertexCount; i ++ ) {
  19875. for ( let c = 0; c < itemSize; c ++ ) {
  19876. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19877. }
  19878. }
  19879. } else {
  19880. // faster copy approach using typed array set function
  19881. target.array.set( src.array, targetOffset * itemSize );
  19882. }
  19883. target.needsUpdate = true;
  19884. }
  19885. // safely copies array contents to a potentially smaller array
  19886. function copyArrayContents( src, target ) {
  19887. if ( src.constructor !== target.constructor ) {
  19888. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  19889. const len = Math.min( src.length, target.length );
  19890. for ( let i = 0; i < len; i ++ ) {
  19891. target[ i ] = src[ i ];
  19892. }
  19893. } else {
  19894. // if the arrays use the same data layout we can use a fast block copy
  19895. const len = Math.min( src.length, target.length );
  19896. target.set( new src.constructor( src.buffer, 0, len ) );
  19897. }
  19898. }
  19899. /**
  19900. * A special version of a mesh with multi draw batch rendering support. Use
  19901. * this class if you have to render a large number of objects with the same
  19902. * material but with different geometries or world transformations. The usage of
  19903. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  19904. * rendering performance in your application.
  19905. *
  19906. * ```js
  19907. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  19908. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  19909. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  19910. *
  19911. * // initialize and add geometries into the batched mesh
  19912. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  19913. * const boxGeometryId = batchedMesh.addGeometry( box );
  19914. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  19915. *
  19916. * // create instances of those geometries
  19917. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  19918. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  19919. *
  19920. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  19921. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  19922. *
  19923. * // position the geometries
  19924. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  19925. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  19926. *
  19927. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  19928. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  19929. *
  19930. * scene.add( batchedMesh );
  19931. * ```
  19932. *
  19933. * @augments Mesh
  19934. */
  19935. class BatchedMesh extends Mesh {
  19936. /**
  19937. * Constructs a new batched mesh.
  19938. *
  19939. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  19940. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  19941. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  19942. * @param {Material|Array<Material>} [material] - The mesh material.
  19943. */
  19944. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19945. super( new BufferGeometry(), material );
  19946. /**
  19947. * This flag can be used for type testing.
  19948. *
  19949. * @type {boolean}
  19950. * @readonly
  19951. * @default true
  19952. */
  19953. this.isBatchedMesh = true;
  19954. /**
  19955. * When set ot `true`, the individual objects of a batch are frustum culled.
  19956. *
  19957. * @type {boolean}
  19958. * @default true
  19959. */
  19960. this.perObjectFrustumCulled = true;
  19961. /**
  19962. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  19963. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  19964. * rendered front to back.
  19965. *
  19966. * @type {boolean}
  19967. * @default true
  19968. */
  19969. this.sortObjects = true;
  19970. /**
  19971. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  19972. *
  19973. * @type {?Box3}
  19974. * @default null
  19975. */
  19976. this.boundingBox = null;
  19977. /**
  19978. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  19979. *
  19980. * @type {?Sphere}
  19981. * @default null
  19982. */
  19983. this.boundingSphere = null;
  19984. /**
  19985. * Takes a sort a function that is run before render. The function takes a list of instances to
  19986. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  19987. * sort with.
  19988. *
  19989. * @type {?Function}
  19990. * @default null
  19991. */
  19992. this.customSort = null;
  19993. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  19994. this._instanceInfo = [];
  19995. this._geometryInfo = [];
  19996. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  19997. this._availableInstanceIds = [];
  19998. this._availableGeometryIds = [];
  19999. // used to track where the next point is that geometry should be inserted
  20000. this._nextIndexStart = 0;
  20001. this._nextVertexStart = 0;
  20002. this._geometryCount = 0;
  20003. // flags
  20004. this._visibilityChanged = true;
  20005. this._geometryInitialized = false;
  20006. // cached user options
  20007. this._maxInstanceCount = maxInstanceCount;
  20008. this._maxVertexCount = maxVertexCount;
  20009. this._maxIndexCount = maxIndexCount;
  20010. // buffers for multi draw
  20011. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  20012. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  20013. this._multiDrawCount = 0;
  20014. this._multiDrawInstances = null;
  20015. // Local matrix per geometry by using data texture
  20016. this._matricesTexture = null;
  20017. this._indirectTexture = null;
  20018. this._colorsTexture = null;
  20019. this._initMatricesTexture();
  20020. this._initIndirectTexture();
  20021. }
  20022. /**
  20023. * The maximum number of individual instances that can be stored in the batch.
  20024. *
  20025. * @type {number}
  20026. * @readonly
  20027. */
  20028. get maxInstanceCount() {
  20029. return this._maxInstanceCount;
  20030. }
  20031. /**
  20032. * The instance count.
  20033. *
  20034. * @type {number}
  20035. * @readonly
  20036. */
  20037. get instanceCount() {
  20038. return this._instanceInfo.length - this._availableInstanceIds.length;
  20039. }
  20040. /**
  20041. * The number of unused vertices.
  20042. *
  20043. * @type {number}
  20044. * @readonly
  20045. */
  20046. get unusedVertexCount() {
  20047. return this._maxVertexCount - this._nextVertexStart;
  20048. }
  20049. /**
  20050. * The number of unused indices.
  20051. *
  20052. * @type {number}
  20053. * @readonly
  20054. */
  20055. get unusedIndexCount() {
  20056. return this._maxIndexCount - this._nextIndexStart;
  20057. }
  20058. _initMatricesTexture() {
  20059. // layout (1 matrix = 4 pixels)
  20060. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  20061. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  20062. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  20063. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  20064. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  20065. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  20066. size = Math.ceil( size / 4 ) * 4;
  20067. size = Math.max( size, 4 );
  20068. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  20069. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  20070. this._matricesTexture = matricesTexture;
  20071. }
  20072. _initIndirectTexture() {
  20073. let size = Math.sqrt( this._maxInstanceCount );
  20074. size = Math.ceil( size );
  20075. const indirectArray = new Uint32Array( size * size );
  20076. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  20077. this._indirectTexture = indirectTexture;
  20078. }
  20079. _initColorsTexture() {
  20080. let size = Math.sqrt( this._maxInstanceCount );
  20081. size = Math.ceil( size );
  20082. // 4 floats per RGBA pixel initialized to white
  20083. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  20084. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  20085. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  20086. this._colorsTexture = colorsTexture;
  20087. }
  20088. _initializeGeometry( reference ) {
  20089. const geometry = this.geometry;
  20090. const maxVertexCount = this._maxVertexCount;
  20091. const maxIndexCount = this._maxIndexCount;
  20092. if ( this._geometryInitialized === false ) {
  20093. for ( const attributeName in reference.attributes ) {
  20094. const srcAttribute = reference.getAttribute( attributeName );
  20095. const { array, itemSize, normalized } = srcAttribute;
  20096. const dstArray = new array.constructor( maxVertexCount * itemSize );
  20097. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  20098. geometry.setAttribute( attributeName, dstAttribute );
  20099. }
  20100. if ( reference.getIndex() !== null ) {
  20101. // Reserve last u16 index for primitive restart.
  20102. const indexArray = maxVertexCount > 65535
  20103. ? new Uint32Array( maxIndexCount )
  20104. : new Uint16Array( maxIndexCount );
  20105. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  20106. }
  20107. this._geometryInitialized = true;
  20108. }
  20109. }
  20110. // Make sure the geometry is compatible with the existing combined geometry attributes
  20111. _validateGeometry( geometry ) {
  20112. // check to ensure the geometries are using consistent attributes and indices
  20113. const batchGeometry = this.geometry;
  20114. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  20115. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  20116. }
  20117. for ( const attributeName in batchGeometry.attributes ) {
  20118. if ( ! geometry.hasAttribute( attributeName ) ) {
  20119. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  20120. }
  20121. const srcAttribute = geometry.getAttribute( attributeName );
  20122. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20123. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  20124. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  20125. }
  20126. }
  20127. }
  20128. /**
  20129. * Validates the instance defined by the given ID.
  20130. *
  20131. * @param {number} instanceId - The instance to validate.
  20132. */
  20133. validateInstanceId( instanceId ) {
  20134. const instanceInfo = this._instanceInfo;
  20135. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  20136. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  20137. }
  20138. }
  20139. /**
  20140. * Validates the geometry defined by the given ID.
  20141. *
  20142. * @param {number} geometryId - The geometry to validate.
  20143. */
  20144. validateGeometryId( geometryId ) {
  20145. const geometryInfoList = this._geometryInfo;
  20146. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20147. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  20148. }
  20149. }
  20150. /**
  20151. * Takes a sort a function that is run before render. The function takes a list of instances to
  20152. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  20153. *
  20154. * @param {Function} func - The custom sort function.
  20155. * @return {BatchedMesh} A reference to this batched mesh.
  20156. */
  20157. setCustomSort( func ) {
  20158. this.customSort = func;
  20159. return this;
  20160. }
  20161. /**
  20162. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  20163. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  20164. * otherwise they are `null`.
  20165. */
  20166. computeBoundingBox() {
  20167. if ( this.boundingBox === null ) {
  20168. this.boundingBox = new Box3();
  20169. }
  20170. const boundingBox = this.boundingBox;
  20171. const instanceInfo = this._instanceInfo;
  20172. boundingBox.makeEmpty();
  20173. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20174. if ( instanceInfo[ i ].active === false ) continue;
  20175. const geometryId = instanceInfo[ i ].geometryIndex;
  20176. this.getMatrixAt( i, _matrix$1 );
  20177. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  20178. boundingBox.union( _box$1 );
  20179. }
  20180. }
  20181. /**
  20182. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  20183. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  20184. * otherwise they are `null`.
  20185. */
  20186. computeBoundingSphere() {
  20187. if ( this.boundingSphere === null ) {
  20188. this.boundingSphere = new Sphere();
  20189. }
  20190. const boundingSphere = this.boundingSphere;
  20191. const instanceInfo = this._instanceInfo;
  20192. boundingSphere.makeEmpty();
  20193. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20194. if ( instanceInfo[ i ].active === false ) continue;
  20195. const geometryId = instanceInfo[ i ].geometryIndex;
  20196. this.getMatrixAt( i, _matrix$1 );
  20197. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20198. boundingSphere.union( _sphere$2 );
  20199. }
  20200. }
  20201. /**
  20202. * Adds a new instance to the batch using the geometry of the given ID and returns
  20203. * a new id referring to the new instance to be used by other functions.
  20204. *
  20205. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  20206. * @return {number} The instance ID.
  20207. */
  20208. addInstance( geometryId ) {
  20209. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  20210. // ensure we're not over geometry
  20211. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  20212. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  20213. }
  20214. const instanceInfo = {
  20215. visible: true,
  20216. active: true,
  20217. geometryIndex: geometryId,
  20218. };
  20219. let drawId = null;
  20220. // Prioritize using previously freed instance ids
  20221. if ( this._availableInstanceIds.length > 0 ) {
  20222. this._availableInstanceIds.sort( ascIdSort );
  20223. drawId = this._availableInstanceIds.shift();
  20224. this._instanceInfo[ drawId ] = instanceInfo;
  20225. } else {
  20226. drawId = this._instanceInfo.length;
  20227. this._instanceInfo.push( instanceInfo );
  20228. }
  20229. const matricesTexture = this._matricesTexture;
  20230. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  20231. matricesTexture.needsUpdate = true;
  20232. const colorsTexture = this._colorsTexture;
  20233. if ( colorsTexture ) {
  20234. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  20235. colorsTexture.needsUpdate = true;
  20236. }
  20237. this._visibilityChanged = true;
  20238. return drawId;
  20239. }
  20240. /**
  20241. * Adds the given geometry to the batch and returns the associated
  20242. * geometry id referring to it to be used in other functions.
  20243. *
  20244. * @param {BufferGeometry} geometry - The geometry to add.
  20245. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  20246. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  20247. * to set a new geometry at this index at a later time that is larger than the original geometry.
  20248. * Defaults to the length of the given geometry vertex buffer.
  20249. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  20250. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  20251. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  20252. * the length of the given geometry index buffer.
  20253. * @return {number} The geometry ID.
  20254. */
  20255. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  20256. this._initializeGeometry( geometry );
  20257. this._validateGeometry( geometry );
  20258. const geometryInfo = {
  20259. // geometry information
  20260. vertexStart: -1,
  20261. vertexCount: -1,
  20262. reservedVertexCount: -1,
  20263. indexStart: -1,
  20264. indexCount: -1,
  20265. reservedIndexCount: -1,
  20266. // draw range information
  20267. start: -1,
  20268. count: -1,
  20269. // state
  20270. boundingBox: null,
  20271. boundingSphere: null,
  20272. active: true,
  20273. };
  20274. const geometryInfoList = this._geometryInfo;
  20275. geometryInfo.vertexStart = this._nextVertexStart;
  20276. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  20277. const index = geometry.getIndex();
  20278. const hasIndex = index !== null;
  20279. if ( hasIndex ) {
  20280. geometryInfo.indexStart = this._nextIndexStart;
  20281. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  20282. }
  20283. if (
  20284. geometryInfo.indexStart !== -1 &&
  20285. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  20286. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  20287. ) {
  20288. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  20289. }
  20290. // update id
  20291. let geometryId;
  20292. if ( this._availableGeometryIds.length > 0 ) {
  20293. this._availableGeometryIds.sort( ascIdSort );
  20294. geometryId = this._availableGeometryIds.shift();
  20295. geometryInfoList[ geometryId ] = geometryInfo;
  20296. } else {
  20297. geometryId = this._geometryCount;
  20298. this._geometryCount ++;
  20299. geometryInfoList.push( geometryInfo );
  20300. }
  20301. // update the geometry
  20302. this.setGeometryAt( geometryId, geometry );
  20303. // increment the next geometry position
  20304. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  20305. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20306. return geometryId;
  20307. }
  20308. /**
  20309. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  20310. * is not enough space reserved for geometry. Calling this will change all instances that are
  20311. * rendering that geometry.
  20312. *
  20313. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  20314. * @param {BufferGeometry} geometry - The new geometry.
  20315. * @return {number} The geometry ID.
  20316. */
  20317. setGeometryAt( geometryId, geometry ) {
  20318. if ( geometryId >= this._geometryCount ) {
  20319. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  20320. }
  20321. this._validateGeometry( geometry );
  20322. const batchGeometry = this.geometry;
  20323. const hasIndex = batchGeometry.getIndex() !== null;
  20324. const dstIndex = batchGeometry.getIndex();
  20325. const srcIndex = geometry.getIndex();
  20326. const geometryInfo = this._geometryInfo[ geometryId ];
  20327. if (
  20328. hasIndex &&
  20329. srcIndex.count > geometryInfo.reservedIndexCount ||
  20330. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  20331. ) {
  20332. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  20333. }
  20334. // copy geometry buffer data over
  20335. const vertexStart = geometryInfo.vertexStart;
  20336. const reservedVertexCount = geometryInfo.reservedVertexCount;
  20337. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  20338. for ( const attributeName in batchGeometry.attributes ) {
  20339. // copy attribute data
  20340. const srcAttribute = geometry.getAttribute( attributeName );
  20341. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20342. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  20343. // fill the rest in with zeroes
  20344. const itemSize = srcAttribute.itemSize;
  20345. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  20346. const index = vertexStart + i;
  20347. for ( let c = 0; c < itemSize; c ++ ) {
  20348. dstAttribute.setComponent( index, c, 0 );
  20349. }
  20350. }
  20351. dstAttribute.needsUpdate = true;
  20352. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  20353. }
  20354. // copy index
  20355. if ( hasIndex ) {
  20356. const indexStart = geometryInfo.indexStart;
  20357. const reservedIndexCount = geometryInfo.reservedIndexCount;
  20358. geometryInfo.indexCount = geometry.getIndex().count;
  20359. // copy index data over
  20360. for ( let i = 0; i < srcIndex.count; i ++ ) {
  20361. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  20362. }
  20363. // fill the rest in with zeroes
  20364. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  20365. dstIndex.setX( indexStart + i, vertexStart );
  20366. }
  20367. dstIndex.needsUpdate = true;
  20368. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  20369. }
  20370. // update the draw range
  20371. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20372. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  20373. // store the bounding boxes
  20374. geometryInfo.boundingBox = null;
  20375. if ( geometry.boundingBox !== null ) {
  20376. geometryInfo.boundingBox = geometry.boundingBox.clone();
  20377. }
  20378. geometryInfo.boundingSphere = null;
  20379. if ( geometry.boundingSphere !== null ) {
  20380. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  20381. }
  20382. this._visibilityChanged = true;
  20383. return geometryId;
  20384. }
  20385. /**
  20386. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  20387. * this geometry will also be removed as a side effect.
  20388. *
  20389. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  20390. * @return {BatchedMesh} A reference to this batched mesh.
  20391. */
  20392. deleteGeometry( geometryId ) {
  20393. const geometryInfoList = this._geometryInfo;
  20394. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20395. return this;
  20396. }
  20397. // delete any instances associated with this geometry
  20398. const instanceInfo = this._instanceInfo;
  20399. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20400. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  20401. this.deleteInstance( i );
  20402. }
  20403. }
  20404. geometryInfoList[ geometryId ].active = false;
  20405. this._availableGeometryIds.push( geometryId );
  20406. this._visibilityChanged = true;
  20407. return this;
  20408. }
  20409. /**
  20410. * Deletes an existing instance from the batch using the given ID.
  20411. *
  20412. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20413. * @return {BatchedMesh} A reference to this batched mesh.
  20414. */
  20415. deleteInstance( instanceId ) {
  20416. this.validateInstanceId( instanceId );
  20417. this._instanceInfo[ instanceId ].active = false;
  20418. this._availableInstanceIds.push( instanceId );
  20419. this._visibilityChanged = true;
  20420. return this;
  20421. }
  20422. /**
  20423. * Repacks the sub geometries in [name] to remove any unused space remaining from
  20424. * previously deleted geometry, freeing up space to add new geometry.
  20425. *
  20426. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20427. * @return {BatchedMesh} A reference to this batched mesh.
  20428. */
  20429. optimize() {
  20430. // track the next indices to copy data to
  20431. let nextVertexStart = 0;
  20432. let nextIndexStart = 0;
  20433. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  20434. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  20435. const geometryInfoList = this._geometryInfo;
  20436. const indices = geometryInfoList
  20437. .map( ( e, i ) => i )
  20438. .sort( ( a, b ) => {
  20439. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  20440. } );
  20441. const geometry = this.geometry;
  20442. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  20443. // if a geometry range is inactive then don't copy anything
  20444. const index = indices[ i ];
  20445. const geometryInfo = geometryInfoList[ index ];
  20446. if ( geometryInfo.active === false ) {
  20447. continue;
  20448. }
  20449. // if a geometry contains an index buffer then shift it, as well
  20450. if ( geometry.index !== null ) {
  20451. if ( geometryInfo.indexStart !== nextIndexStart ) {
  20452. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  20453. const index = geometry.index;
  20454. const array = index.array;
  20455. // shift the index pointers based on how the vertex data will shift
  20456. // adjusting the index must happen first so the original vertex start value is available
  20457. const elementDelta = nextVertexStart - vertexStart;
  20458. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  20459. array[ j ] = array[ j ] + elementDelta;
  20460. }
  20461. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  20462. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  20463. geometryInfo.indexStart = nextIndexStart;
  20464. }
  20465. nextIndexStart += geometryInfo.reservedIndexCount;
  20466. }
  20467. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  20468. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  20469. const { vertexStart, reservedVertexCount } = geometryInfo;
  20470. const attributes = geometry.attributes;
  20471. for ( const key in attributes ) {
  20472. const attribute = attributes[ key ];
  20473. const { array, itemSize } = attribute;
  20474. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  20475. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  20476. }
  20477. geometryInfo.vertexStart = nextVertexStart;
  20478. }
  20479. nextVertexStart += geometryInfo.reservedVertexCount;
  20480. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20481. // step the next geometry points to the shifted position
  20482. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  20483. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20484. }
  20485. return this;
  20486. }
  20487. /**
  20488. * Returns the bounding box for the given geometry.
  20489. *
  20490. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  20491. * @param {Box3} target - The target object that is used to store the method's result.
  20492. * @return {Box3|null} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  20493. */
  20494. getBoundingBoxAt( geometryId, target ) {
  20495. if ( geometryId >= this._geometryCount ) {
  20496. return null;
  20497. }
  20498. // compute bounding box
  20499. const geometry = this.geometry;
  20500. const geometryInfo = this._geometryInfo[ geometryId ];
  20501. if ( geometryInfo.boundingBox === null ) {
  20502. const box = new Box3();
  20503. const index = geometry.index;
  20504. const position = geometry.attributes.position;
  20505. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20506. let iv = i;
  20507. if ( index ) {
  20508. iv = index.getX( iv );
  20509. }
  20510. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  20511. }
  20512. geometryInfo.boundingBox = box;
  20513. }
  20514. target.copy( geometryInfo.boundingBox );
  20515. return target;
  20516. }
  20517. /**
  20518. * Returns the bounding sphere for the given geometry.
  20519. *
  20520. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  20521. * @param {Sphere} target - The target object that is used to store the method's result.
  20522. * @return {Sphere|null} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  20523. */
  20524. getBoundingSphereAt( geometryId, target ) {
  20525. if ( geometryId >= this._geometryCount ) {
  20526. return null;
  20527. }
  20528. // compute bounding sphere
  20529. const geometry = this.geometry;
  20530. const geometryInfo = this._geometryInfo[ geometryId ];
  20531. if ( geometryInfo.boundingSphere === null ) {
  20532. const sphere = new Sphere();
  20533. this.getBoundingBoxAt( geometryId, _box$1 );
  20534. _box$1.getCenter( sphere.center );
  20535. const index = geometry.index;
  20536. const position = geometry.attributes.position;
  20537. let maxRadiusSq = 0;
  20538. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20539. let iv = i;
  20540. if ( index ) {
  20541. iv = index.getX( iv );
  20542. }
  20543. _vector$5.fromBufferAttribute( position, iv );
  20544. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20545. }
  20546. sphere.radius = Math.sqrt( maxRadiusSq );
  20547. geometryInfo.boundingSphere = sphere;
  20548. }
  20549. target.copy( geometryInfo.boundingSphere );
  20550. return target;
  20551. }
  20552. /**
  20553. * Sets the given local transformation matrix to the defined instance.
  20554. * Negatively scaled matrices are not supported.
  20555. *
  20556. * @param {number} instanceId - The ID of an instance to set the matrix of.
  20557. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  20558. * @return {BatchedMesh} A reference to this batched mesh.
  20559. */
  20560. setMatrixAt( instanceId, matrix ) {
  20561. this.validateInstanceId( instanceId );
  20562. const matricesTexture = this._matricesTexture;
  20563. const matricesArray = this._matricesTexture.image.data;
  20564. matrix.toArray( matricesArray, instanceId * 16 );
  20565. matricesTexture.needsUpdate = true;
  20566. return this;
  20567. }
  20568. /**
  20569. * Returns the local transformation matrix of the defined instance.
  20570. *
  20571. * @param {number} instanceId - The ID of an instance to get the matrix of.
  20572. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  20573. * @return {Matrix4} The instance's local transformation matrix.
  20574. */
  20575. getMatrixAt( instanceId, matrix ) {
  20576. this.validateInstanceId( instanceId );
  20577. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  20578. }
  20579. /**
  20580. * Sets the given color to the defined instance.
  20581. *
  20582. * @param {number} instanceId - The ID of an instance to set the color of.
  20583. * @param {Color} color - The color to set the instance to.
  20584. * @return {BatchedMesh} A reference to this batched mesh.
  20585. */
  20586. setColorAt( instanceId, color ) {
  20587. this.validateInstanceId( instanceId );
  20588. if ( this._colorsTexture === null ) {
  20589. this._initColorsTexture();
  20590. }
  20591. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  20592. this._colorsTexture.needsUpdate = true;
  20593. return this;
  20594. }
  20595. /**
  20596. * Returns the color of the defined instance.
  20597. *
  20598. * @param {number} instanceId - The ID of an instance to get the color of.
  20599. * @param {Color} color - The target object that is used to store the method's result.
  20600. * @return {Color} The instance's color.
  20601. */
  20602. getColorAt( instanceId, color ) {
  20603. this.validateInstanceId( instanceId );
  20604. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  20605. }
  20606. /**
  20607. * Sets the visibility of the instance.
  20608. *
  20609. * @param {number} instanceId - The id of the instance to set the visibility of.
  20610. * @param {boolean} visible - Whether the instance is visible or not.
  20611. * @return {BatchedMesh} A reference to this batched mesh.
  20612. */
  20613. setVisibleAt( instanceId, visible ) {
  20614. this.validateInstanceId( instanceId );
  20615. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  20616. return this;
  20617. }
  20618. this._instanceInfo[ instanceId ].visible = visible;
  20619. this._visibilityChanged = true;
  20620. return this;
  20621. }
  20622. /**
  20623. * Returns the visibility state of the defined instance.
  20624. *
  20625. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  20626. * @return {boolean} Whether the instance is visible or not.
  20627. */
  20628. getVisibleAt( instanceId ) {
  20629. this.validateInstanceId( instanceId );
  20630. return this._instanceInfo[ instanceId ].visible;
  20631. }
  20632. /**
  20633. * Sets the geometry ID of the instance at the given index.
  20634. *
  20635. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  20636. * @param {number} geometryId - The geometry ID to be use by the instance.
  20637. * @return {BatchedMesh} A reference to this batched mesh.
  20638. */
  20639. setGeometryIdAt( instanceId, geometryId ) {
  20640. this.validateInstanceId( instanceId );
  20641. this.validateGeometryId( geometryId );
  20642. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  20643. return this;
  20644. }
  20645. /**
  20646. * Returns the geometry ID of the defined instance.
  20647. *
  20648. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  20649. * @return {number} The instance's geometry ID.
  20650. */
  20651. getGeometryIdAt( instanceId ) {
  20652. this.validateInstanceId( instanceId );
  20653. return this._instanceInfo[ instanceId ].geometryIndex;
  20654. }
  20655. /**
  20656. * Get the range representing the subset of triangles related to the attached geometry,
  20657. * indicating the starting offset and count, or `null` if invalid.
  20658. *
  20659. * @param {number} geometryId - The id of the geometry to get the range of.
  20660. * @param {Object} [target] - The target object that is used to store the method's result.
  20661. * @return {{
  20662. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  20663. * indexStart:number,indexCount:number,reservedIndexCount:number,
  20664. * start:number,count:number
  20665. * }} The result object with range data.
  20666. */
  20667. getGeometryRangeAt( geometryId, target = {} ) {
  20668. this.validateGeometryId( geometryId );
  20669. const geometryInfo = this._geometryInfo[ geometryId ];
  20670. target.vertexStart = geometryInfo.vertexStart;
  20671. target.vertexCount = geometryInfo.vertexCount;
  20672. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  20673. target.indexStart = geometryInfo.indexStart;
  20674. target.indexCount = geometryInfo.indexCount;
  20675. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  20676. target.start = geometryInfo.start;
  20677. target.count = geometryInfo.count;
  20678. return target;
  20679. }
  20680. /**
  20681. * Resizes the necessary buffers to support the provided number of instances.
  20682. * If the provided arguments shrink the number of instances but there are not enough
  20683. * unused Ids at the end of the list then an error is thrown.
  20684. *
  20685. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  20686. */
  20687. setInstanceCount( maxInstanceCount ) {
  20688. // shrink the available instances as much as possible
  20689. const availableInstanceIds = this._availableInstanceIds;
  20690. const instanceInfo = this._instanceInfo;
  20691. availableInstanceIds.sort( ascIdSort );
  20692. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) {
  20693. instanceInfo.pop();
  20694. availableInstanceIds.pop();
  20695. }
  20696. // throw an error if it can't be shrunk to the desired size
  20697. if ( maxInstanceCount < instanceInfo.length ) {
  20698. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  20699. }
  20700. // copy the multi draw counts
  20701. const multiDrawCounts = new Int32Array( maxInstanceCount );
  20702. const multiDrawStarts = new Int32Array( maxInstanceCount );
  20703. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  20704. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  20705. this._multiDrawCounts = multiDrawCounts;
  20706. this._multiDrawStarts = multiDrawStarts;
  20707. this._maxInstanceCount = maxInstanceCount;
  20708. // update texture data for instance sampling
  20709. const indirectTexture = this._indirectTexture;
  20710. const matricesTexture = this._matricesTexture;
  20711. const colorsTexture = this._colorsTexture;
  20712. indirectTexture.dispose();
  20713. this._initIndirectTexture();
  20714. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  20715. matricesTexture.dispose();
  20716. this._initMatricesTexture();
  20717. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  20718. if ( colorsTexture ) {
  20719. colorsTexture.dispose();
  20720. this._initColorsTexture();
  20721. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  20722. }
  20723. }
  20724. /**
  20725. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  20726. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  20727. * end of the geometry attributes then an error is thrown.
  20728. *
  20729. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  20730. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  20731. */
  20732. setGeometrySize( maxVertexCount, maxIndexCount ) {
  20733. // Check if we can shrink to the requested vertex attribute size
  20734. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  20735. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  20736. if ( requiredVertexLength > maxVertexCount ) {
  20737. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20738. }
  20739. // Check if we can shrink to the requested index attribute size
  20740. if ( this.geometry.index ) {
  20741. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  20742. if ( requiredIndexLength > maxIndexCount ) {
  20743. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20744. }
  20745. }
  20746. //
  20747. // dispose of the previous geometry
  20748. const oldGeometry = this.geometry;
  20749. oldGeometry.dispose();
  20750. // recreate the geometry needed based on the previous variant
  20751. this._maxVertexCount = maxVertexCount;
  20752. this._maxIndexCount = maxIndexCount;
  20753. if ( this._geometryInitialized ) {
  20754. this._geometryInitialized = false;
  20755. this.geometry = new BufferGeometry();
  20756. this._initializeGeometry( oldGeometry );
  20757. }
  20758. // copy data from the previous geometry
  20759. const geometry = this.geometry;
  20760. if ( oldGeometry.index ) {
  20761. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  20762. }
  20763. for ( const key in oldGeometry.attributes ) {
  20764. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  20765. }
  20766. }
  20767. raycast( raycaster, intersects ) {
  20768. const instanceInfo = this._instanceInfo;
  20769. const geometryInfoList = this._geometryInfo;
  20770. const matrixWorld = this.matrixWorld;
  20771. const batchGeometry = this.geometry;
  20772. // iterate over each geometry
  20773. _mesh.material = this.material;
  20774. _mesh.geometry.index = batchGeometry.index;
  20775. _mesh.geometry.attributes = batchGeometry.attributes;
  20776. if ( _mesh.geometry.boundingBox === null ) {
  20777. _mesh.geometry.boundingBox = new Box3();
  20778. }
  20779. if ( _mesh.geometry.boundingSphere === null ) {
  20780. _mesh.geometry.boundingSphere = new Sphere();
  20781. }
  20782. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20783. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  20784. continue;
  20785. }
  20786. const geometryId = instanceInfo[ i ].geometryIndex;
  20787. const geometryInfo = geometryInfoList[ geometryId ];
  20788. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  20789. // get the intersects
  20790. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  20791. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  20792. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  20793. _mesh.raycast( raycaster, _batchIntersects );
  20794. // add batch id to the intersects
  20795. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  20796. const intersect = _batchIntersects[ j ];
  20797. intersect.object = this;
  20798. intersect.batchId = i;
  20799. intersects.push( intersect );
  20800. }
  20801. _batchIntersects.length = 0;
  20802. }
  20803. _mesh.material = null;
  20804. _mesh.geometry.index = null;
  20805. _mesh.geometry.attributes = {};
  20806. _mesh.geometry.setDrawRange( 0, Infinity );
  20807. }
  20808. copy( source ) {
  20809. super.copy( source );
  20810. this.geometry = source.geometry.clone();
  20811. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  20812. this.sortObjects = source.sortObjects;
  20813. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  20814. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  20815. this._geometryInfo = source._geometryInfo.map( info => ( {
  20816. ...info,
  20817. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  20818. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  20819. } ) );
  20820. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  20821. this._availableInstanceIds = source._availableInstanceIds.slice();
  20822. this._availableGeometryIds = source._availableGeometryIds.slice();
  20823. this._nextIndexStart = source._nextIndexStart;
  20824. this._nextVertexStart = source._nextVertexStart;
  20825. this._geometryCount = source._geometryCount;
  20826. this._maxInstanceCount = source._maxInstanceCount;
  20827. this._maxVertexCount = source._maxVertexCount;
  20828. this._maxIndexCount = source._maxIndexCount;
  20829. this._geometryInitialized = source._geometryInitialized;
  20830. this._multiDrawCounts = source._multiDrawCounts.slice();
  20831. this._multiDrawStarts = source._multiDrawStarts.slice();
  20832. this._indirectTexture = source._indirectTexture.clone();
  20833. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  20834. this._matricesTexture = source._matricesTexture.clone();
  20835. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  20836. if ( this._colorsTexture !== null ) {
  20837. this._colorsTexture = source._colorsTexture.clone();
  20838. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  20839. }
  20840. return this;
  20841. }
  20842. /**
  20843. * Frees the GPU-related resources allocated by this instance. Call this
  20844. * method whenever this instance is no longer used in your app.
  20845. */
  20846. dispose() {
  20847. // Assuming the geometry is not shared with other meshes
  20848. this.geometry.dispose();
  20849. this._matricesTexture.dispose();
  20850. this._matricesTexture = null;
  20851. this._indirectTexture.dispose();
  20852. this._indirectTexture = null;
  20853. if ( this._colorsTexture !== null ) {
  20854. this._colorsTexture.dispose();
  20855. this._colorsTexture = null;
  20856. }
  20857. }
  20858. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  20859. // if visibility has not changed and frustum culling and object sorting is not required
  20860. // then skip iterating over all items
  20861. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  20862. return;
  20863. }
  20864. // the indexed version of the multi draw function requires specifying the start
  20865. // offset in bytes.
  20866. const index = geometry.getIndex();
  20867. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  20868. const instanceInfo = this._instanceInfo;
  20869. const multiDrawStarts = this._multiDrawStarts;
  20870. const multiDrawCounts = this._multiDrawCounts;
  20871. const geometryInfoList = this._geometryInfo;
  20872. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  20873. const indirectTexture = this._indirectTexture;
  20874. const indirectArray = indirectTexture.image.data;
  20875. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  20876. // prepare the frustum in the local frame
  20877. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  20878. _matrix$1
  20879. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  20880. .multiply( this.matrixWorld );
  20881. _frustum.setFromProjectionMatrix(
  20882. _matrix$1,
  20883. camera.coordinateSystem,
  20884. camera.reversedDepth
  20885. );
  20886. }
  20887. let multiDrawCount = 0;
  20888. if ( this.sortObjects ) {
  20889. // get the camera position in the local frame
  20890. _matrix$1.copy( this.matrixWorld ).invert();
  20891. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  20892. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  20893. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20894. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20895. const geometryId = instanceInfo[ i ].geometryIndex;
  20896. // get the bounds in world space
  20897. this.getMatrixAt( i, _matrix$1 );
  20898. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20899. // determine whether the batched geometry is within the frustum
  20900. let culled = false;
  20901. if ( perObjectFrustumCulled ) {
  20902. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20903. }
  20904. if ( ! culled ) {
  20905. // get the distance from camera used for sorting
  20906. const geometryInfo = geometryInfoList[ geometryId ];
  20907. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  20908. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  20909. }
  20910. }
  20911. }
  20912. // Sort the draw ranges and prep for rendering
  20913. const list = _renderList.list;
  20914. const customSort = this.customSort;
  20915. if ( customSort === null ) {
  20916. list.sort( material.transparent ? sortTransparent : sortOpaque );
  20917. } else {
  20918. customSort.call( this, list, camera );
  20919. }
  20920. for ( let i = 0, l = list.length; i < l; i ++ ) {
  20921. const item = list[ i ];
  20922. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  20923. multiDrawCounts[ multiDrawCount ] = item.count;
  20924. indirectArray[ multiDrawCount ] = item.index;
  20925. multiDrawCount ++;
  20926. }
  20927. _renderList.reset();
  20928. } else {
  20929. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20930. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20931. const geometryId = instanceInfo[ i ].geometryIndex;
  20932. // determine whether the batched geometry is within the frustum
  20933. let culled = false;
  20934. if ( perObjectFrustumCulled ) {
  20935. // get the bounds in world space
  20936. this.getMatrixAt( i, _matrix$1 );
  20937. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20938. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20939. }
  20940. if ( ! culled ) {
  20941. const geometryInfo = geometryInfoList[ geometryId ];
  20942. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  20943. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  20944. indirectArray[ multiDrawCount ] = i;
  20945. multiDrawCount ++;
  20946. }
  20947. }
  20948. }
  20949. }
  20950. indirectTexture.needsUpdate = true;
  20951. this._multiDrawCount = multiDrawCount;
  20952. this._visibilityChanged = false;
  20953. }
  20954. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  20955. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  20956. }
  20957. }
  20958. /**
  20959. * A material for rendering line primitives.
  20960. *
  20961. * Materials define the appearance of renderable 3D objects.
  20962. *
  20963. * ```js
  20964. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  20965. * ```
  20966. *
  20967. * @augments Material
  20968. */
  20969. class LineBasicMaterial extends Material {
  20970. /**
  20971. * Constructs a new line basic material.
  20972. *
  20973. * @param {Object} [parameters] - An object with one or more properties
  20974. * defining the material's appearance. Any property of the material
  20975. * (including any property from inherited materials) can be passed
  20976. * in here. Color values can be passed any type of value accepted
  20977. * by {@link Color#set}.
  20978. */
  20979. constructor( parameters ) {
  20980. super();
  20981. /**
  20982. * This flag can be used for type testing.
  20983. *
  20984. * @type {boolean}
  20985. * @readonly
  20986. * @default true
  20987. */
  20988. this.isLineBasicMaterial = true;
  20989. this.type = 'LineBasicMaterial';
  20990. /**
  20991. * Color of the material.
  20992. *
  20993. * @type {Color}
  20994. * @default (1,1,1)
  20995. */
  20996. this.color = new Color( 0xffffff );
  20997. /**
  20998. * Sets the color of the lines using data from a texture. The texture map
  20999. * color is modulated by the diffuse `color`.
  21000. *
  21001. * @type {?Texture}
  21002. * @default null
  21003. */
  21004. this.map = null;
  21005. /**
  21006. * Controls line thickness or lines.
  21007. *
  21008. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  21009. * ignore this setting and always render line primitives with a
  21010. * width of one pixel.
  21011. *
  21012. * @type {number}
  21013. * @default 1
  21014. */
  21015. this.linewidth = 1;
  21016. /**
  21017. * Defines appearance of line ends.
  21018. *
  21019. * Can only be used with {@link SVGRenderer}.
  21020. *
  21021. * @type {('butt'|'round'|'square')}
  21022. * @default 'round'
  21023. */
  21024. this.linecap = 'round';
  21025. /**
  21026. * Defines appearance of line joints.
  21027. *
  21028. * Can only be used with {@link SVGRenderer}.
  21029. *
  21030. * @type {('round'|'bevel'|'miter')}
  21031. * @default 'round'
  21032. */
  21033. this.linejoin = 'round';
  21034. /**
  21035. * Whether the material is affected by fog or not.
  21036. *
  21037. * @type {boolean}
  21038. * @default true
  21039. */
  21040. this.fog = true;
  21041. this.setValues( parameters );
  21042. }
  21043. copy( source ) {
  21044. super.copy( source );
  21045. this.color.copy( source.color );
  21046. this.map = source.map;
  21047. this.linewidth = source.linewidth;
  21048. this.linecap = source.linecap;
  21049. this.linejoin = source.linejoin;
  21050. this.fog = source.fog;
  21051. return this;
  21052. }
  21053. }
  21054. const _vStart = /*@__PURE__*/ new Vector3();
  21055. const _vEnd = /*@__PURE__*/ new Vector3();
  21056. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  21057. const _ray$1 = /*@__PURE__*/ new Ray();
  21058. const _sphere$1 = /*@__PURE__*/ new Sphere();
  21059. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  21060. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  21061. /**
  21062. * A continuous line. The line are rendered by connecting consecutive
  21063. * vertices with straight lines.
  21064. *
  21065. * ```js
  21066. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  21067. *
  21068. * const points = [];
  21069. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  21070. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  21071. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  21072. *
  21073. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  21074. *
  21075. * const line = new THREE.Line( geometry, material );
  21076. * scene.add( line );
  21077. * ```
  21078. *
  21079. * @augments Object3D
  21080. */
  21081. class Line extends Object3D {
  21082. /**
  21083. * Constructs a new line.
  21084. *
  21085. * @param {BufferGeometry} [geometry] - The line geometry.
  21086. * @param {Material|Array<Material>} [material] - The line material.
  21087. */
  21088. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  21089. super();
  21090. /**
  21091. * This flag can be used for type testing.
  21092. *
  21093. * @type {boolean}
  21094. * @readonly
  21095. * @default true
  21096. */
  21097. this.isLine = true;
  21098. this.type = 'Line';
  21099. /**
  21100. * The line geometry.
  21101. *
  21102. * @type {BufferGeometry}
  21103. */
  21104. this.geometry = geometry;
  21105. /**
  21106. * The line material.
  21107. *
  21108. * @type {Material|Array<Material>}
  21109. * @default LineBasicMaterial
  21110. */
  21111. this.material = material;
  21112. /**
  21113. * A dictionary representing the morph targets in the geometry. The key is the
  21114. * morph targets name, the value its attribute index. This member is `undefined`
  21115. * by default and only set when morph targets are detected in the geometry.
  21116. *
  21117. * @type {Object<String,number>|undefined}
  21118. * @default undefined
  21119. */
  21120. this.morphTargetDictionary = undefined;
  21121. /**
  21122. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21123. * is applied. This member is `undefined` by default and only set when morph targets are
  21124. * detected in the geometry.
  21125. *
  21126. * @type {Array<number>|undefined}
  21127. * @default undefined
  21128. */
  21129. this.morphTargetInfluences = undefined;
  21130. this.updateMorphTargets();
  21131. }
  21132. copy( source, recursive ) {
  21133. super.copy( source, recursive );
  21134. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21135. this.geometry = source.geometry;
  21136. return this;
  21137. }
  21138. /**
  21139. * Computes an array of distance values which are necessary for rendering dashed lines.
  21140. * For each vertex in the geometry, the method calculates the cumulative length from the
  21141. * current point to the very beginning of the line.
  21142. *
  21143. * @return {Line} A reference to this line.
  21144. */
  21145. computeLineDistances() {
  21146. const geometry = this.geometry;
  21147. // we assume non-indexed geometry
  21148. if ( geometry.index === null ) {
  21149. const positionAttribute = geometry.attributes.position;
  21150. const lineDistances = [ 0 ];
  21151. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  21152. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  21153. _vEnd.fromBufferAttribute( positionAttribute, i );
  21154. lineDistances[ i ] = lineDistances[ i - 1 ];
  21155. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  21156. }
  21157. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21158. } else {
  21159. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21160. }
  21161. return this;
  21162. }
  21163. /**
  21164. * Computes intersection points between a casted ray and this line.
  21165. *
  21166. * @param {Raycaster} raycaster - The raycaster.
  21167. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21168. */
  21169. raycast( raycaster, intersects ) {
  21170. const geometry = this.geometry;
  21171. const matrixWorld = this.matrixWorld;
  21172. const threshold = raycaster.params.Line.threshold;
  21173. const drawRange = geometry.drawRange;
  21174. // Checking boundingSphere distance to ray
  21175. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21176. _sphere$1.copy( geometry.boundingSphere );
  21177. _sphere$1.applyMatrix4( matrixWorld );
  21178. _sphere$1.radius += threshold;
  21179. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  21180. //
  21181. _inverseMatrix$1.copy( matrixWorld ).invert();
  21182. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  21183. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21184. const localThresholdSq = localThreshold * localThreshold;
  21185. const step = this.isLineSegments ? 2 : 1;
  21186. const index = geometry.index;
  21187. const attributes = geometry.attributes;
  21188. const positionAttribute = attributes.position;
  21189. if ( index !== null ) {
  21190. const start = Math.max( 0, drawRange.start );
  21191. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21192. for ( let i = start, l = end - 1; i < l; i += step ) {
  21193. const a = index.getX( i );
  21194. const b = index.getX( i + 1 );
  21195. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  21196. if ( intersect ) {
  21197. intersects.push( intersect );
  21198. }
  21199. }
  21200. if ( this.isLineLoop ) {
  21201. const a = index.getX( end - 1 );
  21202. const b = index.getX( start );
  21203. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  21204. if ( intersect ) {
  21205. intersects.push( intersect );
  21206. }
  21207. }
  21208. } else {
  21209. const start = Math.max( 0, drawRange.start );
  21210. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21211. for ( let i = start, l = end - 1; i < l; i += step ) {
  21212. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  21213. if ( intersect ) {
  21214. intersects.push( intersect );
  21215. }
  21216. }
  21217. if ( this.isLineLoop ) {
  21218. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  21219. if ( intersect ) {
  21220. intersects.push( intersect );
  21221. }
  21222. }
  21223. }
  21224. }
  21225. /**
  21226. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  21227. * to make sure existing morph targets can influence this 3D object.
  21228. */
  21229. updateMorphTargets() {
  21230. const geometry = this.geometry;
  21231. const morphAttributes = geometry.morphAttributes;
  21232. const keys = Object.keys( morphAttributes );
  21233. if ( keys.length > 0 ) {
  21234. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21235. if ( morphAttribute !== undefined ) {
  21236. this.morphTargetInfluences = [];
  21237. this.morphTargetDictionary = {};
  21238. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21239. const name = morphAttribute[ m ].name || String( m );
  21240. this.morphTargetInfluences.push( 0 );
  21241. this.morphTargetDictionary[ name ] = m;
  21242. }
  21243. }
  21244. }
  21245. }
  21246. }
  21247. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  21248. const positionAttribute = object.geometry.attributes.position;
  21249. _vStart.fromBufferAttribute( positionAttribute, a );
  21250. _vEnd.fromBufferAttribute( positionAttribute, b );
  21251. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  21252. if ( distSq > thresholdSq ) return;
  21253. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  21254. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  21255. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21256. return {
  21257. distance: distance,
  21258. // What do we want? intersection point on the ray or on the segment??
  21259. // point: raycaster.ray.at( distance ),
  21260. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  21261. index: i,
  21262. face: null,
  21263. faceIndex: null,
  21264. barycoord: null,
  21265. object: object
  21266. };
  21267. }
  21268. const _start = /*@__PURE__*/ new Vector3();
  21269. const _end = /*@__PURE__*/ new Vector3();
  21270. /**
  21271. * A series of lines drawn between pairs of vertices.
  21272. *
  21273. * @augments Line
  21274. */
  21275. class LineSegments extends Line {
  21276. /**
  21277. * Constructs a new line segments.
  21278. *
  21279. * @param {BufferGeometry} [geometry] - The line geometry.
  21280. * @param {Material|Array<Material>} [material] - The line material.
  21281. */
  21282. constructor( geometry, material ) {
  21283. super( geometry, material );
  21284. /**
  21285. * This flag can be used for type testing.
  21286. *
  21287. * @type {boolean}
  21288. * @readonly
  21289. * @default true
  21290. */
  21291. this.isLineSegments = true;
  21292. this.type = 'LineSegments';
  21293. }
  21294. computeLineDistances() {
  21295. const geometry = this.geometry;
  21296. // we assume non-indexed geometry
  21297. if ( geometry.index === null ) {
  21298. const positionAttribute = geometry.attributes.position;
  21299. const lineDistances = [];
  21300. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  21301. _start.fromBufferAttribute( positionAttribute, i );
  21302. _end.fromBufferAttribute( positionAttribute, i + 1 );
  21303. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  21304. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  21305. }
  21306. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21307. } else {
  21308. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21309. }
  21310. return this;
  21311. }
  21312. }
  21313. /**
  21314. * A continuous line. This is nearly the same as {@link Line} the only difference
  21315. * is that the last vertex is connected with the first vertex in order to close
  21316. * the line to form a loop.
  21317. *
  21318. * @augments Line
  21319. */
  21320. class LineLoop extends Line {
  21321. /**
  21322. * Constructs a new line loop.
  21323. *
  21324. * @param {BufferGeometry} [geometry] - The line geometry.
  21325. * @param {Material|Array<Material>} [material] - The line material.
  21326. */
  21327. constructor( geometry, material ) {
  21328. super( geometry, material );
  21329. /**
  21330. * This flag can be used for type testing.
  21331. *
  21332. * @type {boolean}
  21333. * @readonly
  21334. * @default true
  21335. */
  21336. this.isLineLoop = true;
  21337. this.type = 'LineLoop';
  21338. }
  21339. }
  21340. /**
  21341. * A material for rendering point primitives.
  21342. *
  21343. * Materials define the appearance of renderable 3D objects.
  21344. *
  21345. * ```js
  21346. * const vertices = [];
  21347. *
  21348. * for ( let i = 0; i < 10000; i ++ ) {
  21349. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  21350. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  21351. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  21352. *
  21353. * vertices.push( x, y, z );
  21354. * }
  21355. *
  21356. * const geometry = new THREE.BufferGeometry();
  21357. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  21358. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  21359. * const points = new THREE.Points( geometry, material );
  21360. * scene.add( points );
  21361. * ```
  21362. *
  21363. * @augments Material
  21364. */
  21365. class PointsMaterial extends Material {
  21366. /**
  21367. * Constructs a new points material.
  21368. *
  21369. * @param {Object} [parameters] - An object with one or more properties
  21370. * defining the material's appearance. Any property of the material
  21371. * (including any property from inherited materials) can be passed
  21372. * in here. Color values can be passed any type of value accepted
  21373. * by {@link Color#set}.
  21374. */
  21375. constructor( parameters ) {
  21376. super();
  21377. /**
  21378. * This flag can be used for type testing.
  21379. *
  21380. * @type {boolean}
  21381. * @readonly
  21382. * @default true
  21383. */
  21384. this.isPointsMaterial = true;
  21385. this.type = 'PointsMaterial';
  21386. /**
  21387. * Color of the material.
  21388. *
  21389. * @type {Color}
  21390. * @default (1,1,1)
  21391. */
  21392. this.color = new Color( 0xffffff );
  21393. /**
  21394. * The color map. May optionally include an alpha channel, typically combined
  21395. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  21396. * color is modulated by the diffuse `color`.
  21397. *
  21398. * @type {?Texture}
  21399. * @default null
  21400. */
  21401. this.map = null;
  21402. /**
  21403. * The alpha map is a grayscale texture that controls the opacity across the
  21404. * surface (black: fully transparent; white: fully opaque).
  21405. *
  21406. * Only the color of the texture is used, ignoring the alpha channel if one
  21407. * exists. For RGB and RGBA textures, the renderer will use the green channel
  21408. * when sampling this texture due to the extra bit of precision provided for
  21409. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  21410. * luminance/alpha textures will also still work as expected.
  21411. *
  21412. * @type {?Texture}
  21413. * @default null
  21414. */
  21415. this.alphaMap = null;
  21416. /**
  21417. * Defines the size of the points in pixels.
  21418. *
  21419. * 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}.
  21420. *
  21421. * @type {number}
  21422. * @default 1
  21423. */
  21424. this.size = 1;
  21425. /**
  21426. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  21427. *
  21428. * @type {boolean}
  21429. * @default true
  21430. */
  21431. this.sizeAttenuation = true;
  21432. /**
  21433. * Whether the material is affected by fog or not.
  21434. *
  21435. * @type {boolean}
  21436. * @default true
  21437. */
  21438. this.fog = true;
  21439. this.setValues( parameters );
  21440. }
  21441. copy( source ) {
  21442. super.copy( source );
  21443. this.color.copy( source.color );
  21444. this.map = source.map;
  21445. this.alphaMap = source.alphaMap;
  21446. this.size = source.size;
  21447. this.sizeAttenuation = source.sizeAttenuation;
  21448. this.fog = source.fog;
  21449. return this;
  21450. }
  21451. }
  21452. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  21453. const _ray = /*@__PURE__*/ new Ray();
  21454. const _sphere = /*@__PURE__*/ new Sphere();
  21455. const _position$2 = /*@__PURE__*/ new Vector3();
  21456. /**
  21457. * A class for displaying points or point clouds.
  21458. *
  21459. * @augments Object3D
  21460. */
  21461. class Points extends Object3D {
  21462. /**
  21463. * Constructs a new point cloud.
  21464. *
  21465. * @param {BufferGeometry} [geometry] - The points geometry.
  21466. * @param {Material|Array<Material>} [material] - The points material.
  21467. */
  21468. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  21469. super();
  21470. /**
  21471. * This flag can be used for type testing.
  21472. *
  21473. * @type {boolean}
  21474. * @readonly
  21475. * @default true
  21476. */
  21477. this.isPoints = true;
  21478. this.type = 'Points';
  21479. /**
  21480. * The points geometry.
  21481. *
  21482. * @type {BufferGeometry}
  21483. */
  21484. this.geometry = geometry;
  21485. /**
  21486. * The line material.
  21487. *
  21488. * @type {Material|Array<Material>}
  21489. * @default PointsMaterial
  21490. */
  21491. this.material = material;
  21492. /**
  21493. * A dictionary representing the morph targets in the geometry. The key is the
  21494. * morph targets name, the value its attribute index. This member is `undefined`
  21495. * by default and only set when morph targets are detected in the geometry.
  21496. *
  21497. * @type {Object<String,number>|undefined}
  21498. * @default undefined
  21499. */
  21500. this.morphTargetDictionary = undefined;
  21501. /**
  21502. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21503. * is applied. This member is `undefined` by default and only set when morph targets are
  21504. * detected in the geometry.
  21505. *
  21506. * @type {Array<number>|undefined}
  21507. * @default undefined
  21508. */
  21509. this.morphTargetInfluences = undefined;
  21510. this.updateMorphTargets();
  21511. }
  21512. copy( source, recursive ) {
  21513. super.copy( source, recursive );
  21514. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21515. this.geometry = source.geometry;
  21516. return this;
  21517. }
  21518. /**
  21519. * Computes intersection points between a casted ray and this point cloud.
  21520. *
  21521. * @param {Raycaster} raycaster - The raycaster.
  21522. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21523. */
  21524. raycast( raycaster, intersects ) {
  21525. const geometry = this.geometry;
  21526. const matrixWorld = this.matrixWorld;
  21527. const threshold = raycaster.params.Points.threshold;
  21528. const drawRange = geometry.drawRange;
  21529. // Checking boundingSphere distance to ray
  21530. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21531. _sphere.copy( geometry.boundingSphere );
  21532. _sphere.applyMatrix4( matrixWorld );
  21533. _sphere.radius += threshold;
  21534. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  21535. //
  21536. _inverseMatrix.copy( matrixWorld ).invert();
  21537. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  21538. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21539. const localThresholdSq = localThreshold * localThreshold;
  21540. const index = geometry.index;
  21541. const attributes = geometry.attributes;
  21542. const positionAttribute = attributes.position;
  21543. if ( index !== null ) {
  21544. const start = Math.max( 0, drawRange.start );
  21545. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21546. for ( let i = start, il = end; i < il; i ++ ) {
  21547. const a = index.getX( i );
  21548. _position$2.fromBufferAttribute( positionAttribute, a );
  21549. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21550. }
  21551. } else {
  21552. const start = Math.max( 0, drawRange.start );
  21553. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21554. for ( let i = start, l = end; i < l; i ++ ) {
  21555. _position$2.fromBufferAttribute( positionAttribute, i );
  21556. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21557. }
  21558. }
  21559. }
  21560. /**
  21561. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  21562. * to make sure existing morph targets can influence this 3D object.
  21563. */
  21564. updateMorphTargets() {
  21565. const geometry = this.geometry;
  21566. const morphAttributes = geometry.morphAttributes;
  21567. const keys = Object.keys( morphAttributes );
  21568. if ( keys.length > 0 ) {
  21569. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21570. if ( morphAttribute !== undefined ) {
  21571. this.morphTargetInfluences = [];
  21572. this.morphTargetDictionary = {};
  21573. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21574. const name = morphAttribute[ m ].name || String( m );
  21575. this.morphTargetInfluences.push( 0 );
  21576. this.morphTargetDictionary[ name ] = m;
  21577. }
  21578. }
  21579. }
  21580. }
  21581. }
  21582. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  21583. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  21584. if ( rayPointDistanceSq < localThresholdSq ) {
  21585. const intersectPoint = new Vector3();
  21586. _ray.closestPointToPoint( point, intersectPoint );
  21587. intersectPoint.applyMatrix4( matrixWorld );
  21588. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  21589. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21590. intersects.push( {
  21591. distance: distance,
  21592. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  21593. point: intersectPoint,
  21594. index: index,
  21595. face: null,
  21596. faceIndex: null,
  21597. barycoord: null,
  21598. object: object
  21599. } );
  21600. }
  21601. }
  21602. /**
  21603. * A texture for use with a video.
  21604. *
  21605. * ```js
  21606. * // assuming you have created a HTML video element with id="video"
  21607. * const video = document.getElementById( 'video' );
  21608. * const texture = new THREE.VideoTexture( video );
  21609. * ```
  21610. *
  21611. * Note: When using video textures with {@link WebGPURenderer}, {@link Texture#colorSpace} must be
  21612. * set to THREE.SRGBColorSpace.
  21613. *
  21614. * Note: After the initial use of a texture, its dimensions, format, and type
  21615. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  21616. *
  21617. * @augments Texture
  21618. */
  21619. class VideoTexture extends Texture {
  21620. /**
  21621. * Constructs a new video texture.
  21622. *
  21623. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  21624. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21625. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21626. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21627. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21628. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21629. * @param {number} [format=RGBAFormat] - The texture format.
  21630. * @param {number} [type=UnsignedByteType] - The texture type.
  21631. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21632. */
  21633. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  21634. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21635. /**
  21636. * This flag can be used for type testing.
  21637. *
  21638. * @type {boolean}
  21639. * @readonly
  21640. * @default true
  21641. */
  21642. this.isVideoTexture = true;
  21643. /**
  21644. * Whether to generate mipmaps (if possible) for a texture.
  21645. *
  21646. * Overwritten and set to `false` by default.
  21647. *
  21648. * @type {boolean}
  21649. * @default false
  21650. */
  21651. this.generateMipmaps = false;
  21652. /**
  21653. * The video frame request callback identifier, which is a positive integer.
  21654. *
  21655. * Value of 0 represents no scheduled rVFC.
  21656. *
  21657. * @private
  21658. * @type {number}
  21659. */
  21660. this._requestVideoFrameCallbackId = 0;
  21661. const scope = this;
  21662. function updateVideo() {
  21663. scope.needsUpdate = true;
  21664. scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21665. }
  21666. if ( 'requestVideoFrameCallback' in video ) {
  21667. this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21668. }
  21669. }
  21670. clone() {
  21671. return new this.constructor( this.image ).copy( this );
  21672. }
  21673. /**
  21674. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  21675. * to `true` every time a new frame is available.
  21676. *
  21677. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  21678. */
  21679. update() {
  21680. const video = this.image;
  21681. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  21682. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  21683. this.needsUpdate = true;
  21684. }
  21685. }
  21686. /**
  21687. * @override
  21688. */
  21689. dispose() {
  21690. if ( this._requestVideoFrameCallbackId !== 0 ) {
  21691. this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId );
  21692. }
  21693. super.dispose();
  21694. }
  21695. }
  21696. /**
  21697. * This class can be used as an alternative way to define video data. Instead of using
  21698. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  21699. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  21700. * video frames are decoded with the WebCodecs API.
  21701. *
  21702. * ```js
  21703. * const texture = new THREE.VideoFrameTexture();
  21704. * texture.setFrame( frame );
  21705. * ```
  21706. *
  21707. * @augments VideoTexture
  21708. */
  21709. class VideoFrameTexture extends VideoTexture {
  21710. /**
  21711. * Constructs a new video frame texture.
  21712. *
  21713. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21714. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21715. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21716. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21717. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21718. * @param {number} [format=RGBAFormat] - The texture format.
  21719. * @param {number} [type=UnsignedByteType] - The texture type.
  21720. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21721. */
  21722. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21723. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21724. /**
  21725. * This flag can be used for type testing.
  21726. *
  21727. * @type {boolean}
  21728. * @readonly
  21729. * @default true
  21730. */
  21731. this.isVideoFrameTexture = true;
  21732. }
  21733. /**
  21734. * This method overwritten with an empty implementation since
  21735. * this type of texture is updated via `setFrame()`.
  21736. */
  21737. update() {}
  21738. clone() {
  21739. return new this.constructor().copy( this ); // restoring Texture.clone()
  21740. }
  21741. /**
  21742. * Sets the current frame of the video. This will automatically update the texture
  21743. * so the data can be used for rendering.
  21744. *
  21745. * @param {VideoFrame} frame - The video frame.
  21746. */
  21747. setFrame( frame ) {
  21748. this.image = frame;
  21749. this.needsUpdate = true;
  21750. }
  21751. }
  21752. /**
  21753. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  21754. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  21755. * as a texture for further usage.
  21756. *
  21757. * ```js
  21758. * const pixelRatio = window.devicePixelRatio;
  21759. * const textureSize = 128 * pixelRatio;
  21760. *
  21761. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  21762. *
  21763. * // calculate start position for copying part of the frame data
  21764. * const vector = new Vector2();
  21765. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  21766. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  21767. *
  21768. * renderer.render( scene, camera );
  21769. *
  21770. * // copy part of the rendered frame into the framebuffer texture
  21771. * renderer.copyFramebufferToTexture( frameTexture, vector );
  21772. * ```
  21773. *
  21774. * @augments Texture
  21775. */
  21776. class FramebufferTexture extends Texture {
  21777. /**
  21778. * Constructs a new framebuffer texture.
  21779. *
  21780. * @param {number} [width] - The width of the texture.
  21781. * @param {number} [height] - The height of the texture.
  21782. */
  21783. constructor( width, height ) {
  21784. super( { width, height } );
  21785. /**
  21786. * This flag can be used for type testing.
  21787. *
  21788. * @type {boolean}
  21789. * @readonly
  21790. * @default true
  21791. */
  21792. this.isFramebufferTexture = true;
  21793. /**
  21794. * How the texture is sampled when a texel covers more than one pixel.
  21795. *
  21796. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21797. *
  21798. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21799. * @default NearestFilter
  21800. */
  21801. this.magFilter = NearestFilter;
  21802. /**
  21803. * How the texture is sampled when a texel covers less than one pixel.
  21804. *
  21805. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21806. *
  21807. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21808. * @default NearestFilter
  21809. */
  21810. this.minFilter = NearestFilter;
  21811. /**
  21812. * Whether to generate mipmaps (if possible) for a texture.
  21813. *
  21814. * Overwritten and set to `false` by default.
  21815. *
  21816. * @type {boolean}
  21817. * @default false
  21818. */
  21819. this.generateMipmaps = false;
  21820. this.needsUpdate = true;
  21821. }
  21822. }
  21823. /**
  21824. * Creates a texture based on data in compressed form.
  21825. *
  21826. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21827. *
  21828. * @augments Texture
  21829. */
  21830. class CompressedTexture extends Texture {
  21831. /**
  21832. * Constructs a new compressed texture.
  21833. *
  21834. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21835. * the data and dimensions.
  21836. * @param {number} width - The width of the texture.
  21837. * @param {number} height - The height of the texture.
  21838. * @param {number} [format=RGBAFormat] - The texture format.
  21839. * @param {number} [type=UnsignedByteType] - The texture type.
  21840. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21841. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21842. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21843. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21844. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21845. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21846. * @param {string} [colorSpace=NoColorSpace] - The color space.
  21847. */
  21848. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  21849. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21850. /**
  21851. * This flag can be used for type testing.
  21852. *
  21853. * @type {boolean}
  21854. * @readonly
  21855. * @default true
  21856. */
  21857. this.isCompressedTexture = true;
  21858. /**
  21859. * The image property of a compressed texture just defines its dimensions.
  21860. *
  21861. * @type {{width:number,height:number}}
  21862. */
  21863. this.image = { width: width, height: height };
  21864. /**
  21865. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  21866. *
  21867. * @type {Array<Object>}
  21868. */
  21869. this.mipmaps = mipmaps;
  21870. /**
  21871. * If set to `true`, the texture is flipped along the vertical axis when
  21872. * uploaded to the GPU.
  21873. *
  21874. * Overwritten and set to `false` by default since it is not possible to
  21875. * flip compressed textures.
  21876. *
  21877. * @type {boolean}
  21878. * @default false
  21879. * @readonly
  21880. */
  21881. this.flipY = false;
  21882. /**
  21883. * Whether to generate mipmaps (if possible) for a texture.
  21884. *
  21885. * Overwritten and set to `false` by default since it is not
  21886. * possible to generate mipmaps for compressed data. Mipmaps
  21887. * must be embedded in the compressed texture file.
  21888. *
  21889. * @type {boolean}
  21890. * @default false
  21891. * @readonly
  21892. */
  21893. this.generateMipmaps = false;
  21894. }
  21895. }
  21896. /**
  21897. * Creates a texture 2D array based on data in compressed form.
  21898. *
  21899. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21900. *
  21901. * @augments CompressedTexture
  21902. */
  21903. class CompressedArrayTexture extends CompressedTexture {
  21904. /**
  21905. * Constructs a new compressed array texture.
  21906. *
  21907. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21908. * the data and dimensions.
  21909. * @param {number} width - The width of the texture.
  21910. * @param {number} height - The height of the texture.
  21911. * @param {number} depth - The depth of the texture.
  21912. * @param {number} [format=RGBAFormat] - The min filter value.
  21913. * @param {number} [type=UnsignedByteType] - The min filter value.
  21914. */
  21915. constructor( mipmaps, width, height, depth, format, type ) {
  21916. super( mipmaps, width, height, format, type );
  21917. /**
  21918. * This flag can be used for type testing.
  21919. *
  21920. * @type {boolean}
  21921. * @readonly
  21922. * @default true
  21923. */
  21924. this.isCompressedArrayTexture = true;
  21925. /**
  21926. * The image property of a compressed texture just defines its dimensions.
  21927. *
  21928. * @name CompressedArrayTexture#image
  21929. * @type {{width:number,height:number,depth:number}}
  21930. */
  21931. this.image.depth = depth;
  21932. /**
  21933. * This defines how the texture is wrapped in the depth and corresponds to
  21934. * *W* in UVW mapping.
  21935. *
  21936. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  21937. * @default ClampToEdgeWrapping
  21938. */
  21939. this.wrapR = ClampToEdgeWrapping;
  21940. /**
  21941. * A set of all layers which need to be updated in the texture.
  21942. *
  21943. * @type {Set<number>}
  21944. */
  21945. this.layerUpdates = new Set();
  21946. }
  21947. /**
  21948. * Describes that a specific layer of the texture needs to be updated.
  21949. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  21950. * entire compressed texture array is sent to the GPU. Marking specific
  21951. * layers will only transmit subsets of all mipmaps associated with a
  21952. * specific depth in the array which is often much more performant.
  21953. *
  21954. * @param {number} layerIndex - The layer index that should be updated.
  21955. */
  21956. addLayerUpdate( layerIndex ) {
  21957. this.layerUpdates.add( layerIndex );
  21958. }
  21959. /**
  21960. * Resets the layer updates registry.
  21961. */
  21962. clearLayerUpdates() {
  21963. this.layerUpdates.clear();
  21964. }
  21965. }
  21966. /**
  21967. * Creates a cube texture based on data in compressed form.
  21968. *
  21969. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21970. *
  21971. * @augments CompressedTexture
  21972. */
  21973. class CompressedCubeTexture extends CompressedTexture {
  21974. /**
  21975. * Constructs a new compressed texture.
  21976. *
  21977. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  21978. * @param {number} [format=RGBAFormat] - The texture format.
  21979. * @param {number} [type=UnsignedByteType] - The texture type.
  21980. */
  21981. constructor( images, format, type ) {
  21982. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  21983. /**
  21984. * This flag can be used for type testing.
  21985. *
  21986. * @type {boolean}
  21987. * @readonly
  21988. * @default true
  21989. */
  21990. this.isCompressedCubeTexture = true;
  21991. /**
  21992. * This flag can be used for type testing.
  21993. *
  21994. * @type {boolean}
  21995. * @readonly
  21996. * @default true
  21997. */
  21998. this.isCubeTexture = true;
  21999. this.image = images;
  22000. }
  22001. }
  22002. /**
  22003. * Creates a texture from a canvas element.
  22004. *
  22005. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  22006. * to `true` immediately since a canvas can directly be used for rendering.
  22007. *
  22008. * @augments Texture
  22009. */
  22010. class CanvasTexture extends Texture {
  22011. /**
  22012. * Constructs a new texture.
  22013. *
  22014. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  22015. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22016. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22017. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22018. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22019. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  22020. * @param {number} [format=RGBAFormat] - The texture format.
  22021. * @param {number} [type=UnsignedByteType] - The texture type.
  22022. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22023. */
  22024. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22025. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22026. /**
  22027. * This flag can be used for type testing.
  22028. *
  22029. * @type {boolean}
  22030. * @readonly
  22031. * @default true
  22032. */
  22033. this.isCanvasTexture = true;
  22034. this.needsUpdate = true;
  22035. }
  22036. }
  22037. /**
  22038. * This class can be used to automatically save the depth information of a
  22039. * rendering into a texture.
  22040. *
  22041. * @augments Texture
  22042. */
  22043. class DepthTexture extends Texture {
  22044. /**
  22045. * Constructs a new depth texture.
  22046. *
  22047. * @param {number} width - The width of the texture.
  22048. * @param {number} height - The height of the texture.
  22049. * @param {number} [type=UnsignedIntType] - The texture type.
  22050. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22051. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22052. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22053. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22054. * @param {number} [minFilter=LinearFilter] - The min filter value.
  22055. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22056. * @param {number} [format=DepthFormat] - The texture format.
  22057. * @param {number} [depth=1] - The depth of the texture.
  22058. */
  22059. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  22060. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  22061. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  22062. }
  22063. const image = { width: width, height: height, depth: depth };
  22064. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22065. /**
  22066. * This flag can be used for type testing.
  22067. *
  22068. * @type {boolean}
  22069. * @readonly
  22070. * @default true
  22071. */
  22072. this.isDepthTexture = true;
  22073. /**
  22074. * If set to `true`, the texture is flipped along the vertical axis when
  22075. * uploaded to the GPU.
  22076. *
  22077. * Overwritten and set to `false` by default.
  22078. *
  22079. * @type {boolean}
  22080. * @default false
  22081. */
  22082. this.flipY = false;
  22083. /**
  22084. * Whether to generate mipmaps (if possible) for a texture.
  22085. *
  22086. * Overwritten and set to `false` by default.
  22087. *
  22088. * @type {boolean}
  22089. * @default false
  22090. */
  22091. this.generateMipmaps = false;
  22092. /**
  22093. * Code corresponding to the depth compare function.
  22094. *
  22095. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  22096. * @default null
  22097. */
  22098. this.compareFunction = null;
  22099. }
  22100. copy( source ) {
  22101. super.copy( source );
  22102. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  22103. this.compareFunction = source.compareFunction;
  22104. return this;
  22105. }
  22106. toJSON( meta ) {
  22107. const data = super.toJSON( meta );
  22108. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  22109. return data;
  22110. }
  22111. }
  22112. /**
  22113. * A geometry class for representing a capsule.
  22114. *
  22115. * ```js
  22116. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  22117. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  22118. * const capsule = new THREE.Mesh( geometry, material );
  22119. * scene.add( capsule );
  22120. * ```
  22121. *
  22122. * @augments BufferGeometry
  22123. */
  22124. class CapsuleGeometry extends BufferGeometry {
  22125. /**
  22126. * Constructs a new capsule geometry.
  22127. *
  22128. * @param {number} [radius=1] - Radius of the capsule.
  22129. * @param {number} [height=1] - Height of the middle section.
  22130. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  22131. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  22132. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  22133. */
  22134. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  22135. super();
  22136. this.type = 'CapsuleGeometry';
  22137. /**
  22138. * Holds the constructor parameters that have been
  22139. * used to generate the geometry. Any modification
  22140. * after instantiation does not change the geometry.
  22141. *
  22142. * @type {Object}
  22143. */
  22144. this.parameters = {
  22145. radius: radius,
  22146. height: height,
  22147. capSegments: capSegments,
  22148. radialSegments: radialSegments,
  22149. heightSegments: heightSegments,
  22150. };
  22151. height = Math.max( 0, height );
  22152. capSegments = Math.max( 1, Math.floor( capSegments ) );
  22153. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  22154. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  22155. // buffers
  22156. const indices = [];
  22157. const vertices = [];
  22158. const normals = [];
  22159. const uvs = [];
  22160. // helper variables
  22161. const halfHeight = height / 2;
  22162. const capArcLength = ( Math.PI / 2 ) * radius;
  22163. const cylinderPartLength = height;
  22164. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  22165. const numVerticalSegments = capSegments * 2 + heightSegments;
  22166. const verticesPerRow = radialSegments + 1;
  22167. const normal = new Vector3();
  22168. const vertex = new Vector3();
  22169. // generate vertices, normals, and uvs
  22170. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  22171. let currentArcLength = 0;
  22172. let profileY = 0;
  22173. let profileRadius = 0;
  22174. let normalYComponent = 0;
  22175. if ( iy <= capSegments ) {
  22176. // bottom cap
  22177. const segmentProgress = iy / capSegments;
  22178. const angle = ( segmentProgress * Math.PI ) / 2;
  22179. profileY = - halfHeight - radius * Math.cos( angle );
  22180. profileRadius = radius * Math.sin( angle );
  22181. normalYComponent = - radius * Math.cos( angle );
  22182. currentArcLength = segmentProgress * capArcLength;
  22183. } else if ( iy <= capSegments + heightSegments ) {
  22184. // middle section
  22185. const segmentProgress = ( iy - capSegments ) / heightSegments;
  22186. profileY = - halfHeight + segmentProgress * height;
  22187. profileRadius = radius;
  22188. normalYComponent = 0;
  22189. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  22190. } else {
  22191. // top cap
  22192. const segmentProgress =
  22193. ( iy - capSegments - heightSegments ) / capSegments;
  22194. const angle = ( segmentProgress * Math.PI ) / 2;
  22195. profileY = halfHeight + radius * Math.sin( angle );
  22196. profileRadius = radius * Math.cos( angle );
  22197. normalYComponent = radius * Math.sin( angle );
  22198. currentArcLength =
  22199. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  22200. }
  22201. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  22202. // special case for the poles
  22203. let uOffset = 0;
  22204. if ( iy === 0 ) {
  22205. uOffset = 0.5 / radialSegments;
  22206. } else if ( iy === numVerticalSegments ) {
  22207. uOffset = -0.5 / radialSegments;
  22208. }
  22209. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  22210. const u = ix / radialSegments;
  22211. const theta = u * Math.PI * 2;
  22212. const sinTheta = Math.sin( theta );
  22213. const cosTheta = Math.cos( theta );
  22214. // vertex
  22215. vertex.x = - profileRadius * cosTheta;
  22216. vertex.y = profileY;
  22217. vertex.z = profileRadius * sinTheta;
  22218. vertices.push( vertex.x, vertex.y, vertex.z );
  22219. // normal
  22220. normal.set(
  22221. - profileRadius * cosTheta,
  22222. normalYComponent,
  22223. profileRadius * sinTheta
  22224. );
  22225. normal.normalize();
  22226. normals.push( normal.x, normal.y, normal.z );
  22227. // uv
  22228. uvs.push( u + uOffset, v );
  22229. }
  22230. if ( iy > 0 ) {
  22231. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  22232. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  22233. const i1 = prevIndexRow + ix;
  22234. const i2 = prevIndexRow + ix + 1;
  22235. const i3 = iy * verticesPerRow + ix;
  22236. const i4 = iy * verticesPerRow + ix + 1;
  22237. indices.push( i1, i2, i3 );
  22238. indices.push( i2, i4, i3 );
  22239. }
  22240. }
  22241. }
  22242. // build geometry
  22243. this.setIndex( indices );
  22244. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22245. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22246. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22247. }
  22248. copy( source ) {
  22249. super.copy( source );
  22250. this.parameters = Object.assign( {}, source.parameters );
  22251. return this;
  22252. }
  22253. /**
  22254. * Factory method for creating an instance of this class from the given
  22255. * JSON object.
  22256. *
  22257. * @param {Object} data - A JSON object representing the serialized geometry.
  22258. * @return {CapsuleGeometry} A new instance.
  22259. */
  22260. static fromJSON( data ) {
  22261. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  22262. }
  22263. }
  22264. /**
  22265. * A simple shape of Euclidean geometry. It is constructed from a
  22266. * number of triangular segments that are oriented around a central point and
  22267. * extend as far out as a given radius. It is built counter-clockwise from a
  22268. * start angle and a given central angle. It can also be used to create
  22269. * regular polygons, where the number of segments determines the number of
  22270. * sides.
  22271. *
  22272. * ```js
  22273. * const geometry = new THREE.CircleGeometry( 5, 32 );
  22274. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22275. * const circle = new THREE.Mesh( geometry, material );
  22276. * scene.add( circle )
  22277. * ```
  22278. *
  22279. * @augments BufferGeometry
  22280. */
  22281. class CircleGeometry extends BufferGeometry {
  22282. /**
  22283. * Constructs a new circle geometry.
  22284. *
  22285. * @param {number} [radius=1] - Radius of the circle.
  22286. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  22287. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  22288. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  22289. * of the circular sector in radians. The default value results in a complete circle.
  22290. */
  22291. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22292. super();
  22293. this.type = 'CircleGeometry';
  22294. /**
  22295. * Holds the constructor parameters that have been
  22296. * used to generate the geometry. Any modification
  22297. * after instantiation does not change the geometry.
  22298. *
  22299. * @type {Object}
  22300. */
  22301. this.parameters = {
  22302. radius: radius,
  22303. segments: segments,
  22304. thetaStart: thetaStart,
  22305. thetaLength: thetaLength
  22306. };
  22307. segments = Math.max( 3, segments );
  22308. // buffers
  22309. const indices = [];
  22310. const vertices = [];
  22311. const normals = [];
  22312. const uvs = [];
  22313. // helper variables
  22314. const vertex = new Vector3();
  22315. const uv = new Vector2();
  22316. // center point
  22317. vertices.push( 0, 0, 0 );
  22318. normals.push( 0, 0, 1 );
  22319. uvs.push( 0.5, 0.5 );
  22320. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22321. const segment = thetaStart + s / segments * thetaLength;
  22322. // vertex
  22323. vertex.x = radius * Math.cos( segment );
  22324. vertex.y = radius * Math.sin( segment );
  22325. vertices.push( vertex.x, vertex.y, vertex.z );
  22326. // normal
  22327. normals.push( 0, 0, 1 );
  22328. // uvs
  22329. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22330. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22331. uvs.push( uv.x, uv.y );
  22332. }
  22333. // indices
  22334. for ( let i = 1; i <= segments; i ++ ) {
  22335. indices.push( i, i + 1, 0 );
  22336. }
  22337. // build geometry
  22338. this.setIndex( indices );
  22339. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22340. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22341. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22342. }
  22343. copy( source ) {
  22344. super.copy( source );
  22345. this.parameters = Object.assign( {}, source.parameters );
  22346. return this;
  22347. }
  22348. /**
  22349. * Factory method for creating an instance of this class from the given
  22350. * JSON object.
  22351. *
  22352. * @param {Object} data - A JSON object representing the serialized geometry.
  22353. * @return {CircleGeometry} A new instance.
  22354. */
  22355. static fromJSON( data ) {
  22356. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  22357. }
  22358. }
  22359. /**
  22360. * A geometry class for representing a cylinder.
  22361. *
  22362. * ```js
  22363. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  22364. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22365. * const cylinder = new THREE.Mesh( geometry, material );
  22366. * scene.add( cylinder );
  22367. * ```
  22368. *
  22369. * @augments BufferGeometry
  22370. */
  22371. class CylinderGeometry extends BufferGeometry {
  22372. /**
  22373. * Constructs a new cylinder geometry.
  22374. *
  22375. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  22376. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  22377. * @param {number} [height=1] - Height of the cylinder.
  22378. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  22379. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  22380. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  22381. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22382. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22383. * The default value results in a complete cylinder.
  22384. */
  22385. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22386. super();
  22387. this.type = 'CylinderGeometry';
  22388. /**
  22389. * Holds the constructor parameters that have been
  22390. * used to generate the geometry. Any modification
  22391. * after instantiation does not change the geometry.
  22392. *
  22393. * @type {Object}
  22394. */
  22395. this.parameters = {
  22396. radiusTop: radiusTop,
  22397. radiusBottom: radiusBottom,
  22398. height: height,
  22399. radialSegments: radialSegments,
  22400. heightSegments: heightSegments,
  22401. openEnded: openEnded,
  22402. thetaStart: thetaStart,
  22403. thetaLength: thetaLength
  22404. };
  22405. const scope = this;
  22406. radialSegments = Math.floor( radialSegments );
  22407. heightSegments = Math.floor( heightSegments );
  22408. // buffers
  22409. const indices = [];
  22410. const vertices = [];
  22411. const normals = [];
  22412. const uvs = [];
  22413. // helper variables
  22414. let index = 0;
  22415. const indexArray = [];
  22416. const halfHeight = height / 2;
  22417. let groupStart = 0;
  22418. // generate geometry
  22419. generateTorso();
  22420. if ( openEnded === false ) {
  22421. if ( radiusTop > 0 ) generateCap( true );
  22422. if ( radiusBottom > 0 ) generateCap( false );
  22423. }
  22424. // build geometry
  22425. this.setIndex( indices );
  22426. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22427. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22428. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22429. function generateTorso() {
  22430. const normal = new Vector3();
  22431. const vertex = new Vector3();
  22432. let groupCount = 0;
  22433. // this will be used to calculate the normal
  22434. const slope = ( radiusBottom - radiusTop ) / height;
  22435. // generate vertices, normals and uvs
  22436. for ( let y = 0; y <= heightSegments; y ++ ) {
  22437. const indexRow = [];
  22438. const v = y / heightSegments;
  22439. // calculate the radius of the current row
  22440. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22441. for ( let x = 0; x <= radialSegments; x ++ ) {
  22442. const u = x / radialSegments;
  22443. const theta = u * thetaLength + thetaStart;
  22444. const sinTheta = Math.sin( theta );
  22445. const cosTheta = Math.cos( theta );
  22446. // vertex
  22447. vertex.x = radius * sinTheta;
  22448. vertex.y = - v * height + halfHeight;
  22449. vertex.z = radius * cosTheta;
  22450. vertices.push( vertex.x, vertex.y, vertex.z );
  22451. // normal
  22452. normal.set( sinTheta, slope, cosTheta ).normalize();
  22453. normals.push( normal.x, normal.y, normal.z );
  22454. // uv
  22455. uvs.push( u, 1 - v );
  22456. // save index of vertex in respective row
  22457. indexRow.push( index ++ );
  22458. }
  22459. // now save vertices of the row in our index array
  22460. indexArray.push( indexRow );
  22461. }
  22462. // generate indices
  22463. for ( let x = 0; x < radialSegments; x ++ ) {
  22464. for ( let y = 0; y < heightSegments; y ++ ) {
  22465. // we use the index array to access the correct indices
  22466. const a = indexArray[ y ][ x ];
  22467. const b = indexArray[ y + 1 ][ x ];
  22468. const c = indexArray[ y + 1 ][ x + 1 ];
  22469. const d = indexArray[ y ][ x + 1 ];
  22470. // faces
  22471. if ( radiusTop > 0 || y !== 0 ) {
  22472. indices.push( a, b, d );
  22473. groupCount += 3;
  22474. }
  22475. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  22476. indices.push( b, c, d );
  22477. groupCount += 3;
  22478. }
  22479. }
  22480. }
  22481. // add a group to the geometry. this will ensure multi material support
  22482. scope.addGroup( groupStart, groupCount, 0 );
  22483. // calculate new start value for groups
  22484. groupStart += groupCount;
  22485. }
  22486. function generateCap( top ) {
  22487. // save the index of the first center vertex
  22488. const centerIndexStart = index;
  22489. const uv = new Vector2();
  22490. const vertex = new Vector3();
  22491. let groupCount = 0;
  22492. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22493. const sign = ( top === true ) ? 1 : -1;
  22494. // first we generate the center vertex data of the cap.
  22495. // because the geometry needs one set of uvs per face,
  22496. // we must generate a center vertex per face/segment
  22497. for ( let x = 1; x <= radialSegments; x ++ ) {
  22498. // vertex
  22499. vertices.push( 0, halfHeight * sign, 0 );
  22500. // normal
  22501. normals.push( 0, sign, 0 );
  22502. // uv
  22503. uvs.push( 0.5, 0.5 );
  22504. // increase index
  22505. index ++;
  22506. }
  22507. // save the index of the last center vertex
  22508. const centerIndexEnd = index;
  22509. // now we generate the surrounding vertices, normals and uvs
  22510. for ( let x = 0; x <= radialSegments; x ++ ) {
  22511. const u = x / radialSegments;
  22512. const theta = u * thetaLength + thetaStart;
  22513. const cosTheta = Math.cos( theta );
  22514. const sinTheta = Math.sin( theta );
  22515. // vertex
  22516. vertex.x = radius * sinTheta;
  22517. vertex.y = halfHeight * sign;
  22518. vertex.z = radius * cosTheta;
  22519. vertices.push( vertex.x, vertex.y, vertex.z );
  22520. // normal
  22521. normals.push( 0, sign, 0 );
  22522. // uv
  22523. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22524. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22525. uvs.push( uv.x, uv.y );
  22526. // increase index
  22527. index ++;
  22528. }
  22529. // generate indices
  22530. for ( let x = 0; x < radialSegments; x ++ ) {
  22531. const c = centerIndexStart + x;
  22532. const i = centerIndexEnd + x;
  22533. if ( top === true ) {
  22534. // face top
  22535. indices.push( i, i + 1, c );
  22536. } else {
  22537. // face bottom
  22538. indices.push( i + 1, i, c );
  22539. }
  22540. groupCount += 3;
  22541. }
  22542. // add a group to the geometry. this will ensure multi material support
  22543. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22544. // calculate new start value for groups
  22545. groupStart += groupCount;
  22546. }
  22547. }
  22548. copy( source ) {
  22549. super.copy( source );
  22550. this.parameters = Object.assign( {}, source.parameters );
  22551. return this;
  22552. }
  22553. /**
  22554. * Factory method for creating an instance of this class from the given
  22555. * JSON object.
  22556. *
  22557. * @param {Object} data - A JSON object representing the serialized geometry.
  22558. * @return {CylinderGeometry} A new instance.
  22559. */
  22560. static fromJSON( data ) {
  22561. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22562. }
  22563. }
  22564. /**
  22565. * A geometry class for representing a cone.
  22566. *
  22567. * ```js
  22568. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  22569. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22570. * const cone = new THREE.Mesh(geometry, material );
  22571. * scene.add( cone );
  22572. * ```
  22573. *
  22574. * @augments CylinderGeometry
  22575. */
  22576. class ConeGeometry extends CylinderGeometry {
  22577. /**
  22578. * Constructs a new cone geometry.
  22579. *
  22580. * @param {number} [radius=1] - Radius of the cone base.
  22581. * @param {number} [height=1] - Height of the cone.
  22582. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  22583. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  22584. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  22585. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22586. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22587. * The default value results in a complete cone.
  22588. */
  22589. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22590. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22591. this.type = 'ConeGeometry';
  22592. /**
  22593. * Holds the constructor parameters that have been
  22594. * used to generate the geometry. Any modification
  22595. * after instantiation does not change the geometry.
  22596. *
  22597. * @type {Object}
  22598. */
  22599. this.parameters = {
  22600. radius: radius,
  22601. height: height,
  22602. radialSegments: radialSegments,
  22603. heightSegments: heightSegments,
  22604. openEnded: openEnded,
  22605. thetaStart: thetaStart,
  22606. thetaLength: thetaLength
  22607. };
  22608. }
  22609. /**
  22610. * Factory method for creating an instance of this class from the given
  22611. * JSON object.
  22612. *
  22613. * @param {Object} data - A JSON object representing the serialized geometry.
  22614. * @return {ConeGeometry} A new instance.
  22615. */
  22616. static fromJSON( data ) {
  22617. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22618. }
  22619. }
  22620. /**
  22621. * A polyhedron is a solid in three dimensions with flat faces. This class
  22622. * will take an array of vertices, project them onto a sphere, and then
  22623. * divide them up to the desired level of detail.
  22624. *
  22625. * @augments BufferGeometry
  22626. */
  22627. class PolyhedronGeometry extends BufferGeometry {
  22628. /**
  22629. * Constructs a new polyhedron geometry.
  22630. *
  22631. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  22632. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  22633. * @param {number} [radius=1] - The radius of the shape.
  22634. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  22635. */
  22636. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22637. super();
  22638. this.type = 'PolyhedronGeometry';
  22639. /**
  22640. * Holds the constructor parameters that have been
  22641. * used to generate the geometry. Any modification
  22642. * after instantiation does not change the geometry.
  22643. *
  22644. * @type {Object}
  22645. */
  22646. this.parameters = {
  22647. vertices: vertices,
  22648. indices: indices,
  22649. radius: radius,
  22650. detail: detail
  22651. };
  22652. // default buffer data
  22653. const vertexBuffer = [];
  22654. const uvBuffer = [];
  22655. // the subdivision creates the vertex buffer data
  22656. subdivide( detail );
  22657. // all vertices should lie on a conceptual sphere with a given radius
  22658. applyRadius( radius );
  22659. // finally, create the uv data
  22660. generateUVs();
  22661. // build non-indexed geometry
  22662. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22663. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22664. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22665. if ( detail === 0 ) {
  22666. this.computeVertexNormals(); // flat normals
  22667. } else {
  22668. this.normalizeNormals(); // smooth normals
  22669. }
  22670. // helper functions
  22671. function subdivide( detail ) {
  22672. const a = new Vector3();
  22673. const b = new Vector3();
  22674. const c = new Vector3();
  22675. // iterate over all faces and apply a subdivision with the given detail value
  22676. for ( let i = 0; i < indices.length; i += 3 ) {
  22677. // get the vertices of the face
  22678. getVertexByIndex( indices[ i + 0 ], a );
  22679. getVertexByIndex( indices[ i + 1 ], b );
  22680. getVertexByIndex( indices[ i + 2 ], c );
  22681. // perform subdivision
  22682. subdivideFace( a, b, c, detail );
  22683. }
  22684. }
  22685. function subdivideFace( a, b, c, detail ) {
  22686. const cols = detail + 1;
  22687. // we use this multidimensional array as a data structure for creating the subdivision
  22688. const v = [];
  22689. // construct all of the vertices for this subdivision
  22690. for ( let i = 0; i <= cols; i ++ ) {
  22691. v[ i ] = [];
  22692. const aj = a.clone().lerp( c, i / cols );
  22693. const bj = b.clone().lerp( c, i / cols );
  22694. const rows = cols - i;
  22695. for ( let j = 0; j <= rows; j ++ ) {
  22696. if ( j === 0 && i === cols ) {
  22697. v[ i ][ j ] = aj;
  22698. } else {
  22699. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22700. }
  22701. }
  22702. }
  22703. // construct all of the faces
  22704. for ( let i = 0; i < cols; i ++ ) {
  22705. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22706. const k = Math.floor( j / 2 );
  22707. if ( j % 2 === 0 ) {
  22708. pushVertex( v[ i ][ k + 1 ] );
  22709. pushVertex( v[ i + 1 ][ k ] );
  22710. pushVertex( v[ i ][ k ] );
  22711. } else {
  22712. pushVertex( v[ i ][ k + 1 ] );
  22713. pushVertex( v[ i + 1 ][ k + 1 ] );
  22714. pushVertex( v[ i + 1 ][ k ] );
  22715. }
  22716. }
  22717. }
  22718. }
  22719. function applyRadius( radius ) {
  22720. const vertex = new Vector3();
  22721. // iterate over the entire buffer and apply the radius to each vertex
  22722. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22723. vertex.x = vertexBuffer[ i + 0 ];
  22724. vertex.y = vertexBuffer[ i + 1 ];
  22725. vertex.z = vertexBuffer[ i + 2 ];
  22726. vertex.normalize().multiplyScalar( radius );
  22727. vertexBuffer[ i + 0 ] = vertex.x;
  22728. vertexBuffer[ i + 1 ] = vertex.y;
  22729. vertexBuffer[ i + 2 ] = vertex.z;
  22730. }
  22731. }
  22732. function generateUVs() {
  22733. const vertex = new Vector3();
  22734. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22735. vertex.x = vertexBuffer[ i + 0 ];
  22736. vertex.y = vertexBuffer[ i + 1 ];
  22737. vertex.z = vertexBuffer[ i + 2 ];
  22738. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22739. const v = inclination( vertex ) / Math.PI + 0.5;
  22740. uvBuffer.push( u, 1 - v );
  22741. }
  22742. correctUVs();
  22743. correctSeam();
  22744. }
  22745. function correctSeam() {
  22746. // handle case when face straddles the seam, see #3269
  22747. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22748. // uv data of a single face
  22749. const x0 = uvBuffer[ i + 0 ];
  22750. const x1 = uvBuffer[ i + 2 ];
  22751. const x2 = uvBuffer[ i + 4 ];
  22752. const max = Math.max( x0, x1, x2 );
  22753. const min = Math.min( x0, x1, x2 );
  22754. // 0.9 is somewhat arbitrary
  22755. if ( max > 0.9 && min < 0.1 ) {
  22756. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  22757. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  22758. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  22759. }
  22760. }
  22761. }
  22762. function pushVertex( vertex ) {
  22763. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22764. }
  22765. function getVertexByIndex( index, vertex ) {
  22766. const stride = index * 3;
  22767. vertex.x = vertices[ stride + 0 ];
  22768. vertex.y = vertices[ stride + 1 ];
  22769. vertex.z = vertices[ stride + 2 ];
  22770. }
  22771. function correctUVs() {
  22772. const a = new Vector3();
  22773. const b = new Vector3();
  22774. const c = new Vector3();
  22775. const centroid = new Vector3();
  22776. const uvA = new Vector2();
  22777. const uvB = new Vector2();
  22778. const uvC = new Vector2();
  22779. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  22780. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  22781. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  22782. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  22783. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  22784. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  22785. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  22786. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  22787. const azi = azimuth( centroid );
  22788. correctUV( uvA, j + 0, a, azi );
  22789. correctUV( uvB, j + 2, b, azi );
  22790. correctUV( uvC, j + 4, c, azi );
  22791. }
  22792. }
  22793. function correctUV( uv, stride, vector, azimuth ) {
  22794. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  22795. uvBuffer[ stride ] = uv.x - 1;
  22796. }
  22797. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  22798. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  22799. }
  22800. }
  22801. // Angle around the Y axis, counter-clockwise when looking from above.
  22802. function azimuth( vector ) {
  22803. return Math.atan2( vector.z, - vector.x );
  22804. }
  22805. // Angle above the XZ plane.
  22806. function inclination( vector ) {
  22807. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22808. }
  22809. }
  22810. copy( source ) {
  22811. super.copy( source );
  22812. this.parameters = Object.assign( {}, source.parameters );
  22813. return this;
  22814. }
  22815. /**
  22816. * Factory method for creating an instance of this class from the given
  22817. * JSON object.
  22818. *
  22819. * @param {Object} data - A JSON object representing the serialized geometry.
  22820. * @return {PolyhedronGeometry} A new instance.
  22821. */
  22822. static fromJSON( data ) {
  22823. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  22824. }
  22825. }
  22826. /**
  22827. * A geometry class for representing a dodecahedron.
  22828. *
  22829. * ```js
  22830. * const geometry = new THREE.DodecahedronGeometry();
  22831. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22832. * const dodecahedron = new THREE.Mesh( geometry, material );
  22833. * scene.add( dodecahedron );
  22834. * ```
  22835. *
  22836. * @augments PolyhedronGeometry
  22837. */
  22838. class DodecahedronGeometry extends PolyhedronGeometry {
  22839. /**
  22840. * Constructs a new dodecahedron geometry.
  22841. *
  22842. * @param {number} [radius=1] - Radius of the dodecahedron.
  22843. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  22844. */
  22845. constructor( radius = 1, detail = 0 ) {
  22846. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22847. const r = 1 / t;
  22848. const vertices = [
  22849. // (±1, ±1, ±1)
  22850. -1, -1, -1, -1, -1, 1,
  22851. -1, 1, -1, -1, 1, 1,
  22852. 1, -1, -1, 1, -1, 1,
  22853. 1, 1, -1, 1, 1, 1,
  22854. // (0, ±1/φ, ±φ)
  22855. 0, - r, - t, 0, - r, t,
  22856. 0, r, - t, 0, r, t,
  22857. // (±1/φ, ±φ, 0)
  22858. - r, - t, 0, - r, t, 0,
  22859. r, - t, 0, r, t, 0,
  22860. // (±φ, 0, ±1/φ)
  22861. - t, 0, - r, t, 0, - r,
  22862. - t, 0, r, t, 0, r
  22863. ];
  22864. const indices = [
  22865. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22866. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22867. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22868. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22869. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22870. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22871. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22872. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22873. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22874. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22875. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22876. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22877. ];
  22878. super( vertices, indices, radius, detail );
  22879. this.type = 'DodecahedronGeometry';
  22880. /**
  22881. * Holds the constructor parameters that have been
  22882. * used to generate the geometry. Any modification
  22883. * after instantiation does not change the geometry.
  22884. *
  22885. * @type {Object}
  22886. */
  22887. this.parameters = {
  22888. radius: radius,
  22889. detail: detail
  22890. };
  22891. }
  22892. /**
  22893. * Factory method for creating an instance of this class from the given
  22894. * JSON object.
  22895. *
  22896. * @param {Object} data - A JSON object representing the serialized geometry.
  22897. * @return {DodecahedronGeometry} A new instance.
  22898. */
  22899. static fromJSON( data ) {
  22900. return new DodecahedronGeometry( data.radius, data.detail );
  22901. }
  22902. }
  22903. const _v0$1 = /*@__PURE__*/ new Vector3();
  22904. const _v1$1 = /*@__PURE__*/ new Vector3();
  22905. const _normal = /*@__PURE__*/ new Vector3();
  22906. const _triangle = /*@__PURE__*/ new Triangle();
  22907. /**
  22908. * Can be used as a helper object to view the edges of a geometry.
  22909. *
  22910. * ```js
  22911. * const geometry = new THREE.BoxGeometry();
  22912. * const edges = new THREE.EdgesGeometry( geometry );
  22913. * const line = new THREE.LineSegments( edges );
  22914. * scene.add( line );
  22915. * ```
  22916. *
  22917. * Note: It is not yet possible to serialize/deserialize instances of this class.
  22918. *
  22919. * @augments BufferGeometry
  22920. */
  22921. class EdgesGeometry extends BufferGeometry {
  22922. /**
  22923. * Constructs a new edges geometry.
  22924. *
  22925. * @param {?BufferGeometry} [geometry=null] - The geometry.
  22926. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  22927. * between the face normals of the adjoining faces exceeds this value.
  22928. */
  22929. constructor( geometry = null, thresholdAngle = 1 ) {
  22930. super();
  22931. this.type = 'EdgesGeometry';
  22932. /**
  22933. * Holds the constructor parameters that have been
  22934. * used to generate the geometry. Any modification
  22935. * after instantiation does not change the geometry.
  22936. *
  22937. * @type {Object}
  22938. */
  22939. this.parameters = {
  22940. geometry: geometry,
  22941. thresholdAngle: thresholdAngle
  22942. };
  22943. if ( geometry !== null ) {
  22944. const precisionPoints = 4;
  22945. const precision = Math.pow( 10, precisionPoints );
  22946. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  22947. const indexAttr = geometry.getIndex();
  22948. const positionAttr = geometry.getAttribute( 'position' );
  22949. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  22950. const indexArr = [ 0, 0, 0 ];
  22951. const vertKeys = [ 'a', 'b', 'c' ];
  22952. const hashes = new Array( 3 );
  22953. const edgeData = {};
  22954. const vertices = [];
  22955. for ( let i = 0; i < indexCount; i += 3 ) {
  22956. if ( indexAttr ) {
  22957. indexArr[ 0 ] = indexAttr.getX( i );
  22958. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  22959. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  22960. } else {
  22961. indexArr[ 0 ] = i;
  22962. indexArr[ 1 ] = i + 1;
  22963. indexArr[ 2 ] = i + 2;
  22964. }
  22965. const { a, b, c } = _triangle;
  22966. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  22967. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  22968. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  22969. _triangle.getNormal( _normal );
  22970. // create hashes for the edge from the vertices
  22971. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  22972. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  22973. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  22974. // skip degenerate triangles
  22975. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  22976. continue;
  22977. }
  22978. // iterate over every edge
  22979. for ( let j = 0; j < 3; j ++ ) {
  22980. // get the first and next vertex making up the edge
  22981. const jNext = ( j + 1 ) % 3;
  22982. const vecHash0 = hashes[ j ];
  22983. const vecHash1 = hashes[ jNext ];
  22984. const v0 = _triangle[ vertKeys[ j ] ];
  22985. const v1 = _triangle[ vertKeys[ jNext ] ];
  22986. const hash = `${ vecHash0 }_${ vecHash1 }`;
  22987. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  22988. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  22989. // if we found a sibling edge add it into the vertex array if
  22990. // it meets the angle threshold and delete the edge from the map.
  22991. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  22992. vertices.push( v0.x, v0.y, v0.z );
  22993. vertices.push( v1.x, v1.y, v1.z );
  22994. }
  22995. edgeData[ reverseHash ] = null;
  22996. } else if ( ! ( hash in edgeData ) ) {
  22997. // if we've already got an edge here then skip adding a new one
  22998. edgeData[ hash ] = {
  22999. index0: indexArr[ j ],
  23000. index1: indexArr[ jNext ],
  23001. normal: _normal.clone(),
  23002. };
  23003. }
  23004. }
  23005. }
  23006. // iterate over all remaining, unmatched edges and add them to the vertex array
  23007. for ( const key in edgeData ) {
  23008. if ( edgeData[ key ] ) {
  23009. const { index0, index1 } = edgeData[ key ];
  23010. _v0$1.fromBufferAttribute( positionAttr, index0 );
  23011. _v1$1.fromBufferAttribute( positionAttr, index1 );
  23012. vertices.push( _v0$1.x, _v0$1.y, _v0$1.z );
  23013. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  23014. }
  23015. }
  23016. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23017. }
  23018. }
  23019. copy( source ) {
  23020. super.copy( source );
  23021. this.parameters = Object.assign( {}, source.parameters );
  23022. return this;
  23023. }
  23024. }
  23025. /**
  23026. * An abstract base class for creating an analytic curve object that contains methods
  23027. * for interpolation.
  23028. *
  23029. * @abstract
  23030. */
  23031. class Curve {
  23032. /**
  23033. * Constructs a new curve.
  23034. */
  23035. constructor() {
  23036. /**
  23037. * The type property is used for detecting the object type
  23038. * in context of serialization/deserialization.
  23039. *
  23040. * @type {string}
  23041. * @readonly
  23042. */
  23043. this.type = 'Curve';
  23044. /**
  23045. * This value determines the amount of divisions when calculating the
  23046. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  23047. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  23048. * recommended to increase the value of this property if the curve is very large.
  23049. *
  23050. * @type {number}
  23051. * @default 200
  23052. */
  23053. this.arcLengthDivisions = 200;
  23054. /**
  23055. * Must be set to `true` if the curve parameters have changed.
  23056. *
  23057. * @type {boolean}
  23058. * @default false
  23059. */
  23060. this.needsUpdate = false;
  23061. /**
  23062. * An internal cache that holds precomputed curve length values.
  23063. *
  23064. * @private
  23065. * @type {?Array<number>}
  23066. * @default null
  23067. */
  23068. this.cacheArcLengths = null;
  23069. }
  23070. /**
  23071. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23072. * for the given interpolation factor.
  23073. *
  23074. * @abstract
  23075. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23076. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23077. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23078. */
  23079. getPoint( /* t, optionalTarget */ ) {
  23080. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  23081. }
  23082. /**
  23083. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23084. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  23085. * of the curve which equidistant samples.
  23086. *
  23087. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23088. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23089. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23090. */
  23091. getPointAt( u, optionalTarget ) {
  23092. const t = this.getUtoTmapping( u );
  23093. return this.getPoint( t, optionalTarget );
  23094. }
  23095. /**
  23096. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  23097. * the curve shape.
  23098. *
  23099. * @param {number} [divisions=5] - The number of divisions.
  23100. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23101. */
  23102. getPoints( divisions = 5 ) {
  23103. const points = [];
  23104. for ( let d = 0; d <= divisions; d ++ ) {
  23105. points.push( this.getPoint( d / divisions ) );
  23106. }
  23107. return points;
  23108. }
  23109. // Get sequence of points using getPointAt( u )
  23110. /**
  23111. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  23112. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  23113. * curve.
  23114. *
  23115. * @param {number} [divisions=5] - The number of divisions.
  23116. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23117. */
  23118. getSpacedPoints( divisions = 5 ) {
  23119. const points = [];
  23120. for ( let d = 0; d <= divisions; d ++ ) {
  23121. points.push( this.getPointAt( d / divisions ) );
  23122. }
  23123. return points;
  23124. }
  23125. /**
  23126. * Returns the total arc length of the curve.
  23127. *
  23128. * @return {number} The length of the curve.
  23129. */
  23130. getLength() {
  23131. const lengths = this.getLengths();
  23132. return lengths[ lengths.length - 1 ];
  23133. }
  23134. /**
  23135. * Returns an array of cumulative segment lengths of the curve.
  23136. *
  23137. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  23138. * @return {Array<number>} An array holding the cumulative segment lengths.
  23139. */
  23140. getLengths( divisions = this.arcLengthDivisions ) {
  23141. if ( this.cacheArcLengths &&
  23142. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23143. ! this.needsUpdate ) {
  23144. return this.cacheArcLengths;
  23145. }
  23146. this.needsUpdate = false;
  23147. const cache = [];
  23148. let current, last = this.getPoint( 0 );
  23149. let sum = 0;
  23150. cache.push( 0 );
  23151. for ( let p = 1; p <= divisions; p ++ ) {
  23152. current = this.getPoint( p / divisions );
  23153. sum += current.distanceTo( last );
  23154. cache.push( sum );
  23155. last = current;
  23156. }
  23157. this.cacheArcLengths = cache;
  23158. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23159. }
  23160. /**
  23161. * Update the cumulative segment distance cache. The method must be called
  23162. * every time curve parameters are changed. If an updated curve is part of a
  23163. * composed curve like {@link CurvePath}, this method must be called on the
  23164. * composed curve, too.
  23165. */
  23166. updateArcLengths() {
  23167. this.needsUpdate = true;
  23168. this.getLengths();
  23169. }
  23170. /**
  23171. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  23172. * interpolation factor in the same range that can be ued to sample equidistant points
  23173. * from a curve.
  23174. *
  23175. * @param {number} u - The interpolation factor.
  23176. * @param {?number} distance - An optional distance on the curve.
  23177. * @return {number} The updated interpolation factor.
  23178. */
  23179. getUtoTmapping( u, distance = null ) {
  23180. const arcLengths = this.getLengths();
  23181. let i = 0;
  23182. const il = arcLengths.length;
  23183. let targetArcLength; // The targeted u distance value to get
  23184. if ( distance ) {
  23185. targetArcLength = distance;
  23186. } else {
  23187. targetArcLength = u * arcLengths[ il - 1 ];
  23188. }
  23189. // binary search for the index with largest value smaller than target u distance
  23190. let low = 0, high = il - 1, comparison;
  23191. while ( low <= high ) {
  23192. 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
  23193. comparison = arcLengths[ i ] - targetArcLength;
  23194. if ( comparison < 0 ) {
  23195. low = i + 1;
  23196. } else if ( comparison > 0 ) {
  23197. high = i - 1;
  23198. } else {
  23199. high = i;
  23200. break;
  23201. // DONE
  23202. }
  23203. }
  23204. i = high;
  23205. if ( arcLengths[ i ] === targetArcLength ) {
  23206. return i / ( il - 1 );
  23207. }
  23208. // we could get finer grain at lengths, or use simple interpolation between two points
  23209. const lengthBefore = arcLengths[ i ];
  23210. const lengthAfter = arcLengths[ i + 1 ];
  23211. const segmentLength = lengthAfter - lengthBefore;
  23212. // determine where we are between the 'before' and 'after' points
  23213. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23214. // add that fractional amount to t
  23215. const t = ( i + segmentFraction ) / ( il - 1 );
  23216. return t;
  23217. }
  23218. /**
  23219. * Returns a unit vector tangent for the given interpolation factor.
  23220. * If the derived curve does not implement its tangent derivation,
  23221. * two points a small delta apart will be used to find its gradient
  23222. * which seems to give a reasonable approximation.
  23223. *
  23224. * @param {number} t - The interpolation factor.
  23225. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23226. * @return {(Vector2|Vector3)} The tangent vector.
  23227. */
  23228. getTangent( t, optionalTarget ) {
  23229. const delta = 0.0001;
  23230. let t1 = t - delta;
  23231. let t2 = t + delta;
  23232. // Capping in case of danger
  23233. if ( t1 < 0 ) t1 = 0;
  23234. if ( t2 > 1 ) t2 = 1;
  23235. const pt1 = this.getPoint( t1 );
  23236. const pt2 = this.getPoint( t2 );
  23237. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  23238. tangent.copy( pt2 ).sub( pt1 ).normalize();
  23239. return tangent;
  23240. }
  23241. /**
  23242. * Same as {@link Curve#getTangent} but with equidistant samples.
  23243. *
  23244. * @param {number} u - The interpolation factor.
  23245. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23246. * @return {(Vector2|Vector3)} The tangent vector.
  23247. * @see {@link Curve#getPointAt}
  23248. */
  23249. getTangentAt( u, optionalTarget ) {
  23250. const t = this.getUtoTmapping( u );
  23251. return this.getTangent( t, optionalTarget );
  23252. }
  23253. /**
  23254. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  23255. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  23256. *
  23257. * @param {number} segments - The number of segments.
  23258. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23259. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  23260. */
  23261. computeFrenetFrames( segments, closed = false ) {
  23262. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23263. const normal = new Vector3();
  23264. const tangents = [];
  23265. const normals = [];
  23266. const binormals = [];
  23267. const vec = new Vector3();
  23268. const mat = new Matrix4();
  23269. // compute the tangent vectors for each segment on the curve
  23270. for ( let i = 0; i <= segments; i ++ ) {
  23271. const u = i / segments;
  23272. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23273. }
  23274. // select an initial normal vector perpendicular to the first tangent vector,
  23275. // and in the direction of the minimum tangent xyz component
  23276. normals[ 0 ] = new Vector3();
  23277. binormals[ 0 ] = new Vector3();
  23278. let min = Number.MAX_VALUE;
  23279. const tx = Math.abs( tangents[ 0 ].x );
  23280. const ty = Math.abs( tangents[ 0 ].y );
  23281. const tz = Math.abs( tangents[ 0 ].z );
  23282. if ( tx <= min ) {
  23283. min = tx;
  23284. normal.set( 1, 0, 0 );
  23285. }
  23286. if ( ty <= min ) {
  23287. min = ty;
  23288. normal.set( 0, 1, 0 );
  23289. }
  23290. if ( tz <= min ) {
  23291. normal.set( 0, 0, 1 );
  23292. }
  23293. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23294. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23295. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23296. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23297. for ( let i = 1; i <= segments; i ++ ) {
  23298. normals[ i ] = normals[ i - 1 ].clone();
  23299. binormals[ i ] = binormals[ i - 1 ].clone();
  23300. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23301. if ( vec.length() > Number.EPSILON ) {
  23302. vec.normalize();
  23303. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  23304. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23305. }
  23306. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23307. }
  23308. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23309. if ( closed === true ) {
  23310. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  23311. theta /= segments;
  23312. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23313. theta = - theta;
  23314. }
  23315. for ( let i = 1; i <= segments; i ++ ) {
  23316. // twist a little...
  23317. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23318. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23319. }
  23320. }
  23321. return {
  23322. tangents: tangents,
  23323. normals: normals,
  23324. binormals: binormals
  23325. };
  23326. }
  23327. /**
  23328. * Returns a new curve with copied values from this instance.
  23329. *
  23330. * @return {Curve} A clone of this instance.
  23331. */
  23332. clone() {
  23333. return new this.constructor().copy( this );
  23334. }
  23335. /**
  23336. * Copies the values of the given curve to this instance.
  23337. *
  23338. * @param {Curve} source - The curve to copy.
  23339. * @return {Curve} A reference to this curve.
  23340. */
  23341. copy( source ) {
  23342. this.arcLengthDivisions = source.arcLengthDivisions;
  23343. return this;
  23344. }
  23345. /**
  23346. * Serializes the curve into JSON.
  23347. *
  23348. * @return {Object} A JSON object representing the serialized curve.
  23349. * @see {@link ObjectLoader#parse}
  23350. */
  23351. toJSON() {
  23352. const data = {
  23353. metadata: {
  23354. version: 4.7,
  23355. type: 'Curve',
  23356. generator: 'Curve.toJSON'
  23357. }
  23358. };
  23359. data.arcLengthDivisions = this.arcLengthDivisions;
  23360. data.type = this.type;
  23361. return data;
  23362. }
  23363. /**
  23364. * Deserializes the curve from the given JSON.
  23365. *
  23366. * @param {Object} json - The JSON holding the serialized curve.
  23367. * @return {Curve} A reference to this curve.
  23368. */
  23369. fromJSON( json ) {
  23370. this.arcLengthDivisions = json.arcLengthDivisions;
  23371. return this;
  23372. }
  23373. }
  23374. /**
  23375. * A curve representing an ellipse.
  23376. *
  23377. * ```js
  23378. * const curve = new THREE.EllipseCurve(
  23379. * 0, 0,
  23380. * 10, 10,
  23381. * 0, 2 * Math.PI,
  23382. * false,
  23383. * 0
  23384. * );
  23385. *
  23386. * const points = curve.getPoints( 50 );
  23387. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23388. *
  23389. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23390. *
  23391. * // Create the final object to add to the scene
  23392. * const ellipse = new THREE.Line( geometry, material );
  23393. * ```
  23394. *
  23395. * @augments Curve
  23396. */
  23397. class EllipseCurve extends Curve {
  23398. /**
  23399. * Constructs a new ellipse curve.
  23400. *
  23401. * @param {number} [aX=0] - The X center of the ellipse.
  23402. * @param {number} [aY=0] - The Y center of the ellipse.
  23403. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  23404. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  23405. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23406. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23407. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23408. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23409. */
  23410. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  23411. super();
  23412. /**
  23413. * This flag can be used for type testing.
  23414. *
  23415. * @type {boolean}
  23416. * @readonly
  23417. * @default true
  23418. */
  23419. this.isEllipseCurve = true;
  23420. this.type = 'EllipseCurve';
  23421. /**
  23422. * The X center of the ellipse.
  23423. *
  23424. * @type {number}
  23425. * @default 0
  23426. */
  23427. this.aX = aX;
  23428. /**
  23429. * The Y center of the ellipse.
  23430. *
  23431. * @type {number}
  23432. * @default 0
  23433. */
  23434. this.aY = aY;
  23435. /**
  23436. * The radius of the ellipse in the x direction.
  23437. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  23438. *
  23439. * @type {number}
  23440. * @default 1
  23441. */
  23442. this.xRadius = xRadius;
  23443. /**
  23444. * The radius of the ellipse in the y direction.
  23445. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  23446. *
  23447. * @type {number}
  23448. * @default 1
  23449. */
  23450. this.yRadius = yRadius;
  23451. /**
  23452. * The start angle of the curve in radians starting from the positive X axis.
  23453. *
  23454. * @type {number}
  23455. * @default 0
  23456. */
  23457. this.aStartAngle = aStartAngle;
  23458. /**
  23459. * The end angle of the curve in radians starting from the positive X axis.
  23460. *
  23461. * @type {number}
  23462. * @default Math.PI*2
  23463. */
  23464. this.aEndAngle = aEndAngle;
  23465. /**
  23466. * Whether the ellipse is drawn clockwise or not.
  23467. *
  23468. * @type {boolean}
  23469. * @default false
  23470. */
  23471. this.aClockwise = aClockwise;
  23472. /**
  23473. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23474. *
  23475. * @type {number}
  23476. * @default 0
  23477. */
  23478. this.aRotation = aRotation;
  23479. }
  23480. /**
  23481. * Returns a point on the curve.
  23482. *
  23483. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23484. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23485. * @return {Vector2} The position on the curve.
  23486. */
  23487. getPoint( t, optionalTarget = new Vector2() ) {
  23488. const point = optionalTarget;
  23489. const twoPi = Math.PI * 2;
  23490. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23491. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23492. // ensures that deltaAngle is 0 .. 2 PI
  23493. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23494. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23495. if ( deltaAngle < Number.EPSILON ) {
  23496. if ( samePoints ) {
  23497. deltaAngle = 0;
  23498. } else {
  23499. deltaAngle = twoPi;
  23500. }
  23501. }
  23502. if ( this.aClockwise === true && ! samePoints ) {
  23503. if ( deltaAngle === twoPi ) {
  23504. deltaAngle = - twoPi;
  23505. } else {
  23506. deltaAngle = deltaAngle - twoPi;
  23507. }
  23508. }
  23509. const angle = this.aStartAngle + t * deltaAngle;
  23510. let x = this.aX + this.xRadius * Math.cos( angle );
  23511. let y = this.aY + this.yRadius * Math.sin( angle );
  23512. if ( this.aRotation !== 0 ) {
  23513. const cos = Math.cos( this.aRotation );
  23514. const sin = Math.sin( this.aRotation );
  23515. const tx = x - this.aX;
  23516. const ty = y - this.aY;
  23517. // Rotate the point about the center of the ellipse.
  23518. x = tx * cos - ty * sin + this.aX;
  23519. y = tx * sin + ty * cos + this.aY;
  23520. }
  23521. return point.set( x, y );
  23522. }
  23523. copy( source ) {
  23524. super.copy( source );
  23525. this.aX = source.aX;
  23526. this.aY = source.aY;
  23527. this.xRadius = source.xRadius;
  23528. this.yRadius = source.yRadius;
  23529. this.aStartAngle = source.aStartAngle;
  23530. this.aEndAngle = source.aEndAngle;
  23531. this.aClockwise = source.aClockwise;
  23532. this.aRotation = source.aRotation;
  23533. return this;
  23534. }
  23535. toJSON() {
  23536. const data = super.toJSON();
  23537. data.aX = this.aX;
  23538. data.aY = this.aY;
  23539. data.xRadius = this.xRadius;
  23540. data.yRadius = this.yRadius;
  23541. data.aStartAngle = this.aStartAngle;
  23542. data.aEndAngle = this.aEndAngle;
  23543. data.aClockwise = this.aClockwise;
  23544. data.aRotation = this.aRotation;
  23545. return data;
  23546. }
  23547. fromJSON( json ) {
  23548. super.fromJSON( json );
  23549. this.aX = json.aX;
  23550. this.aY = json.aY;
  23551. this.xRadius = json.xRadius;
  23552. this.yRadius = json.yRadius;
  23553. this.aStartAngle = json.aStartAngle;
  23554. this.aEndAngle = json.aEndAngle;
  23555. this.aClockwise = json.aClockwise;
  23556. this.aRotation = json.aRotation;
  23557. return this;
  23558. }
  23559. }
  23560. /**
  23561. * A curve representing an arc.
  23562. *
  23563. * @augments EllipseCurve
  23564. */
  23565. class ArcCurve extends EllipseCurve {
  23566. /**
  23567. * Constructs a new arc curve.
  23568. *
  23569. * @param {number} [aX=0] - The X center of the ellipse.
  23570. * @param {number} [aY=0] - The Y center of the ellipse.
  23571. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  23572. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23573. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23574. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23575. */
  23576. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23577. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23578. /**
  23579. * This flag can be used for type testing.
  23580. *
  23581. * @type {boolean}
  23582. * @readonly
  23583. * @default true
  23584. */
  23585. this.isArcCurve = true;
  23586. this.type = 'ArcCurve';
  23587. }
  23588. }
  23589. function CubicPoly() {
  23590. /**
  23591. * Centripetal CatmullRom Curve - which is useful for avoiding
  23592. * cusps and self-intersections in non-uniform catmull rom curves.
  23593. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23594. *
  23595. * curve.type accepts centripetal(default), chordal and catmullrom
  23596. * curve.tension is used for catmullrom which defaults to 0.5
  23597. */
  23598. /*
  23599. Based on an optimized c++ solution in
  23600. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23601. - http://ideone.com/NoEbVM
  23602. This CubicPoly class could be used for reusing some variables and calculations,
  23603. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23604. which can be placed in CurveUtils.
  23605. */
  23606. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23607. /*
  23608. * Compute coefficients for a cubic polynomial
  23609. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23610. * such that
  23611. * p(0) = x0, p(1) = x1
  23612. * and
  23613. * p'(0) = t0, p'(1) = t1.
  23614. */
  23615. function init( x0, x1, t0, t1 ) {
  23616. c0 = x0;
  23617. c1 = t0;
  23618. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23619. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23620. }
  23621. return {
  23622. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23623. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23624. },
  23625. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23626. // compute tangents when parameterized in [t1,t2]
  23627. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23628. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23629. // rescale tangents for parametrization in [0,1]
  23630. t1 *= dt1;
  23631. t2 *= dt1;
  23632. init( x1, x2, t1, t2 );
  23633. },
  23634. calc: function ( t ) {
  23635. const t2 = t * t;
  23636. const t3 = t2 * t;
  23637. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23638. }
  23639. };
  23640. }
  23641. //
  23642. const tmp = /*@__PURE__*/ new Vector3();
  23643. const px = /*@__PURE__*/ new CubicPoly();
  23644. const py = /*@__PURE__*/ new CubicPoly();
  23645. const pz = /*@__PURE__*/ new CubicPoly();
  23646. /**
  23647. * A curve representing a Catmull-Rom spline.
  23648. *
  23649. * ```js
  23650. * //Create a closed wavey loop
  23651. * const curve = new THREE.CatmullRomCurve3( [
  23652. * new THREE.Vector3( -10, 0, 10 ),
  23653. * new THREE.Vector3( -5, 5, 5 ),
  23654. * new THREE.Vector3( 0, 0, 0 ),
  23655. * new THREE.Vector3( 5, -5, 5 ),
  23656. * new THREE.Vector3( 10, 0, 10 )
  23657. * ] );
  23658. *
  23659. * const points = curve.getPoints( 50 );
  23660. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23661. *
  23662. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23663. *
  23664. * // Create the final object to add to the scene
  23665. * const curveObject = new THREE.Line( geometry, material );
  23666. * ```
  23667. *
  23668. * @augments Curve
  23669. */
  23670. class CatmullRomCurve3 extends Curve {
  23671. /**
  23672. * Constructs a new Catmull-Rom curve.
  23673. *
  23674. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  23675. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23676. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  23677. * @param {number} [tension=0.5] - Tension of the curve.
  23678. */
  23679. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23680. super();
  23681. /**
  23682. * This flag can be used for type testing.
  23683. *
  23684. * @type {boolean}
  23685. * @readonly
  23686. * @default true
  23687. */
  23688. this.isCatmullRomCurve3 = true;
  23689. this.type = 'CatmullRomCurve3';
  23690. /**
  23691. * An array of 3D points defining the curve.
  23692. *
  23693. * @type {Array<Vector3>}
  23694. */
  23695. this.points = points;
  23696. /**
  23697. * Whether the curve is closed or not.
  23698. *
  23699. * @type {boolean}
  23700. * @default false
  23701. */
  23702. this.closed = closed;
  23703. /**
  23704. * The curve type.
  23705. *
  23706. * @type {('centripetal'|'chordal'|'catmullrom')}
  23707. * @default 'centripetal'
  23708. */
  23709. this.curveType = curveType;
  23710. /**
  23711. * Tension of the curve.
  23712. *
  23713. * @type {number}
  23714. * @default 0.5
  23715. */
  23716. this.tension = tension;
  23717. }
  23718. /**
  23719. * Returns a point on the curve.
  23720. *
  23721. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23722. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23723. * @return {Vector3} The position on the curve.
  23724. */
  23725. getPoint( t, optionalTarget = new Vector3() ) {
  23726. const point = optionalTarget;
  23727. const points = this.points;
  23728. const l = points.length;
  23729. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23730. let intPoint = Math.floor( p );
  23731. let weight = p - intPoint;
  23732. if ( this.closed ) {
  23733. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23734. } else if ( weight === 0 && intPoint === l - 1 ) {
  23735. intPoint = l - 2;
  23736. weight = 1;
  23737. }
  23738. let p0, p3; // 4 points (p1 & p2 defined below)
  23739. if ( this.closed || intPoint > 0 ) {
  23740. p0 = points[ ( intPoint - 1 ) % l ];
  23741. } else {
  23742. // extrapolate first point
  23743. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23744. p0 = tmp;
  23745. }
  23746. const p1 = points[ intPoint % l ];
  23747. const p2 = points[ ( intPoint + 1 ) % l ];
  23748. if ( this.closed || intPoint + 2 < l ) {
  23749. p3 = points[ ( intPoint + 2 ) % l ];
  23750. } else {
  23751. // extrapolate last point
  23752. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23753. p3 = tmp;
  23754. }
  23755. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23756. // init Centripetal / Chordal Catmull-Rom
  23757. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23758. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23759. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23760. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23761. // safety check for repeated points
  23762. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23763. if ( dt0 < 1e-4 ) dt0 = dt1;
  23764. if ( dt2 < 1e-4 ) dt2 = dt1;
  23765. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  23766. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  23767. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  23768. } else if ( this.curveType === 'catmullrom' ) {
  23769. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  23770. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  23771. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  23772. }
  23773. point.set(
  23774. px.calc( weight ),
  23775. py.calc( weight ),
  23776. pz.calc( weight )
  23777. );
  23778. return point;
  23779. }
  23780. copy( source ) {
  23781. super.copy( source );
  23782. this.points = [];
  23783. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23784. const point = source.points[ i ];
  23785. this.points.push( point.clone() );
  23786. }
  23787. this.closed = source.closed;
  23788. this.curveType = source.curveType;
  23789. this.tension = source.tension;
  23790. return this;
  23791. }
  23792. toJSON() {
  23793. const data = super.toJSON();
  23794. data.points = [];
  23795. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23796. const point = this.points[ i ];
  23797. data.points.push( point.toArray() );
  23798. }
  23799. data.closed = this.closed;
  23800. data.curveType = this.curveType;
  23801. data.tension = this.tension;
  23802. return data;
  23803. }
  23804. fromJSON( json ) {
  23805. super.fromJSON( json );
  23806. this.points = [];
  23807. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23808. const point = json.points[ i ];
  23809. this.points.push( new Vector3().fromArray( point ) );
  23810. }
  23811. this.closed = json.closed;
  23812. this.curveType = json.curveType;
  23813. this.tension = json.tension;
  23814. return this;
  23815. }
  23816. }
  23817. // Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  23818. /**
  23819. * Computes a point on a Catmull-Rom spline.
  23820. *
  23821. * @param {number} t - The interpolation factor.
  23822. * @param {number} p0 - The first control point.
  23823. * @param {number} p1 - The second control point.
  23824. * @param {number} p2 - The third control point.
  23825. * @param {number} p3 - The fourth control point.
  23826. * @return {number} The calculated point on a Catmull-Rom spline.
  23827. */
  23828. function CatmullRom( t, p0, p1, p2, p3 ) {
  23829. const v0 = ( p2 - p0 ) * 0.5;
  23830. const v1 = ( p3 - p1 ) * 0.5;
  23831. const t2 = t * t;
  23832. const t3 = t * t2;
  23833. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23834. }
  23835. //
  23836. function QuadraticBezierP0( t, p ) {
  23837. const k = 1 - t;
  23838. return k * k * p;
  23839. }
  23840. function QuadraticBezierP1( t, p ) {
  23841. return 2 * ( 1 - t ) * t * p;
  23842. }
  23843. function QuadraticBezierP2( t, p ) {
  23844. return t * t * p;
  23845. }
  23846. /**
  23847. * Computes a point on a Quadratic Bezier curve.
  23848. *
  23849. * @param {number} t - The interpolation factor.
  23850. * @param {number} p0 - The first control point.
  23851. * @param {number} p1 - The second control point.
  23852. * @param {number} p2 - The third control point.
  23853. * @return {number} The calculated point on a Quadratic Bezier curve.
  23854. */
  23855. function QuadraticBezier( t, p0, p1, p2 ) {
  23856. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  23857. QuadraticBezierP2( t, p2 );
  23858. }
  23859. //
  23860. function CubicBezierP0( t, p ) {
  23861. const k = 1 - t;
  23862. return k * k * k * p;
  23863. }
  23864. function CubicBezierP1( t, p ) {
  23865. const k = 1 - t;
  23866. return 3 * k * k * t * p;
  23867. }
  23868. function CubicBezierP2( t, p ) {
  23869. return 3 * ( 1 - t ) * t * t * p;
  23870. }
  23871. function CubicBezierP3( t, p ) {
  23872. return t * t * t * p;
  23873. }
  23874. /**
  23875. * Computes a point on a Cubic Bezier curve.
  23876. *
  23877. * @param {number} t - The interpolation factor.
  23878. * @param {number} p0 - The first control point.
  23879. * @param {number} p1 - The second control point.
  23880. * @param {number} p2 - The third control point.
  23881. * @param {number} p3 - The fourth control point.
  23882. * @return {number} The calculated point on a Cubic Bezier curve.
  23883. */
  23884. function CubicBezier( t, p0, p1, p2, p3 ) {
  23885. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  23886. CubicBezierP3( t, p3 );
  23887. }
  23888. /**
  23889. * A curve representing a 2D Cubic Bezier curve.
  23890. *
  23891. * ```js
  23892. * const curve = new THREE.CubicBezierCurve(
  23893. * new THREE.Vector2( - 0, 0 ),
  23894. * new THREE.Vector2( - 5, 15 ),
  23895. * new THREE.Vector2( 20, 15 ),
  23896. * new THREE.Vector2( 10, 0 )
  23897. * );
  23898. *
  23899. * const points = curve.getPoints( 50 );
  23900. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23901. *
  23902. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23903. *
  23904. * // Create the final object to add to the scene
  23905. * const curveObject = new THREE.Line( geometry, material );
  23906. * ```
  23907. *
  23908. * @augments Curve
  23909. */
  23910. class CubicBezierCurve extends Curve {
  23911. /**
  23912. * Constructs a new Cubic Bezier curve.
  23913. *
  23914. * @param {Vector2} [v0] - The start point.
  23915. * @param {Vector2} [v1] - The first control point.
  23916. * @param {Vector2} [v2] - The second control point.
  23917. * @param {Vector2} [v3] - The end point.
  23918. */
  23919. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  23920. super();
  23921. /**
  23922. * This flag can be used for type testing.
  23923. *
  23924. * @type {boolean}
  23925. * @readonly
  23926. * @default true
  23927. */
  23928. this.isCubicBezierCurve = true;
  23929. this.type = 'CubicBezierCurve';
  23930. /**
  23931. * The start point.
  23932. *
  23933. * @type {Vector2}
  23934. */
  23935. this.v0 = v0;
  23936. /**
  23937. * The first control point.
  23938. *
  23939. * @type {Vector2}
  23940. */
  23941. this.v1 = v1;
  23942. /**
  23943. * The second control point.
  23944. *
  23945. * @type {Vector2}
  23946. */
  23947. this.v2 = v2;
  23948. /**
  23949. * The end point.
  23950. *
  23951. * @type {Vector2}
  23952. */
  23953. this.v3 = v3;
  23954. }
  23955. /**
  23956. * Returns a point on the curve.
  23957. *
  23958. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23959. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23960. * @return {Vector2} The position on the curve.
  23961. */
  23962. getPoint( t, optionalTarget = new Vector2() ) {
  23963. const point = optionalTarget;
  23964. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23965. point.set(
  23966. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23967. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  23968. );
  23969. return point;
  23970. }
  23971. copy( source ) {
  23972. super.copy( source );
  23973. this.v0.copy( source.v0 );
  23974. this.v1.copy( source.v1 );
  23975. this.v2.copy( source.v2 );
  23976. this.v3.copy( source.v3 );
  23977. return this;
  23978. }
  23979. toJSON() {
  23980. const data = super.toJSON();
  23981. data.v0 = this.v0.toArray();
  23982. data.v1 = this.v1.toArray();
  23983. data.v2 = this.v2.toArray();
  23984. data.v3 = this.v3.toArray();
  23985. return data;
  23986. }
  23987. fromJSON( json ) {
  23988. super.fromJSON( json );
  23989. this.v0.fromArray( json.v0 );
  23990. this.v1.fromArray( json.v1 );
  23991. this.v2.fromArray( json.v2 );
  23992. this.v3.fromArray( json.v3 );
  23993. return this;
  23994. }
  23995. }
  23996. /**
  23997. * A curve representing a 3D Cubic Bezier curve.
  23998. *
  23999. * @augments Curve
  24000. */
  24001. class CubicBezierCurve3 extends Curve {
  24002. /**
  24003. * Constructs a new Cubic Bezier curve.
  24004. *
  24005. * @param {Vector3} [v0] - The start point.
  24006. * @param {Vector3} [v1] - The first control point.
  24007. * @param {Vector3} [v2] - The second control point.
  24008. * @param {Vector3} [v3] - The end point.
  24009. */
  24010. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  24011. super();
  24012. /**
  24013. * This flag can be used for type testing.
  24014. *
  24015. * @type {boolean}
  24016. * @readonly
  24017. * @default true
  24018. */
  24019. this.isCubicBezierCurve3 = true;
  24020. this.type = 'CubicBezierCurve3';
  24021. /**
  24022. * The start point.
  24023. *
  24024. * @type {Vector3}
  24025. */
  24026. this.v0 = v0;
  24027. /**
  24028. * The first control point.
  24029. *
  24030. * @type {Vector3}
  24031. */
  24032. this.v1 = v1;
  24033. /**
  24034. * The second control point.
  24035. *
  24036. * @type {Vector3}
  24037. */
  24038. this.v2 = v2;
  24039. /**
  24040. * The end point.
  24041. *
  24042. * @type {Vector3}
  24043. */
  24044. this.v3 = v3;
  24045. }
  24046. /**
  24047. * Returns a point on the curve.
  24048. *
  24049. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24050. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24051. * @return {Vector3} The position on the curve.
  24052. */
  24053. getPoint( t, optionalTarget = new Vector3() ) {
  24054. const point = optionalTarget;
  24055. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24056. point.set(
  24057. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24058. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  24059. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  24060. );
  24061. return point;
  24062. }
  24063. copy( source ) {
  24064. super.copy( source );
  24065. this.v0.copy( source.v0 );
  24066. this.v1.copy( source.v1 );
  24067. this.v2.copy( source.v2 );
  24068. this.v3.copy( source.v3 );
  24069. return this;
  24070. }
  24071. toJSON() {
  24072. const data = super.toJSON();
  24073. data.v0 = this.v0.toArray();
  24074. data.v1 = this.v1.toArray();
  24075. data.v2 = this.v2.toArray();
  24076. data.v3 = this.v3.toArray();
  24077. return data;
  24078. }
  24079. fromJSON( json ) {
  24080. super.fromJSON( json );
  24081. this.v0.fromArray( json.v0 );
  24082. this.v1.fromArray( json.v1 );
  24083. this.v2.fromArray( json.v2 );
  24084. this.v3.fromArray( json.v3 );
  24085. return this;
  24086. }
  24087. }
  24088. /**
  24089. * A curve representing a 2D line segment.
  24090. *
  24091. * @augments Curve
  24092. */
  24093. class LineCurve extends Curve {
  24094. /**
  24095. * Constructs a new line curve.
  24096. *
  24097. * @param {Vector2} [v1] - The start point.
  24098. * @param {Vector2} [v2] - The end point.
  24099. */
  24100. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  24101. super();
  24102. /**
  24103. * This flag can be used for type testing.
  24104. *
  24105. * @type {boolean}
  24106. * @readonly
  24107. * @default true
  24108. */
  24109. this.isLineCurve = true;
  24110. this.type = 'LineCurve';
  24111. /**
  24112. * The start point.
  24113. *
  24114. * @type {Vector2}
  24115. */
  24116. this.v1 = v1;
  24117. /**
  24118. * The end point.
  24119. *
  24120. * @type {Vector2}
  24121. */
  24122. this.v2 = v2;
  24123. }
  24124. /**
  24125. * Returns a point on the line.
  24126. *
  24127. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24128. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24129. * @return {Vector2} The position on the line.
  24130. */
  24131. getPoint( t, optionalTarget = new Vector2() ) {
  24132. const point = optionalTarget;
  24133. if ( t === 1 ) {
  24134. point.copy( this.v2 );
  24135. } else {
  24136. point.copy( this.v2 ).sub( this.v1 );
  24137. point.multiplyScalar( t ).add( this.v1 );
  24138. }
  24139. return point;
  24140. }
  24141. // Line curve is linear, so we can overwrite default getPointAt
  24142. getPointAt( u, optionalTarget ) {
  24143. return this.getPoint( u, optionalTarget );
  24144. }
  24145. getTangent( t, optionalTarget = new Vector2() ) {
  24146. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24147. }
  24148. getTangentAt( u, optionalTarget ) {
  24149. return this.getTangent( u, optionalTarget );
  24150. }
  24151. copy( source ) {
  24152. super.copy( source );
  24153. this.v1.copy( source.v1 );
  24154. this.v2.copy( source.v2 );
  24155. return this;
  24156. }
  24157. toJSON() {
  24158. const data = super.toJSON();
  24159. data.v1 = this.v1.toArray();
  24160. data.v2 = this.v2.toArray();
  24161. return data;
  24162. }
  24163. fromJSON( json ) {
  24164. super.fromJSON( json );
  24165. this.v1.fromArray( json.v1 );
  24166. this.v2.fromArray( json.v2 );
  24167. return this;
  24168. }
  24169. }
  24170. /**
  24171. * A curve representing a 3D line segment.
  24172. *
  24173. * @augments Curve
  24174. */
  24175. class LineCurve3 extends Curve {
  24176. /**
  24177. * Constructs a new line curve.
  24178. *
  24179. * @param {Vector3} [v1] - The start point.
  24180. * @param {Vector3} [v2] - The end point.
  24181. */
  24182. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  24183. super();
  24184. /**
  24185. * This flag can be used for type testing.
  24186. *
  24187. * @type {boolean}
  24188. * @readonly
  24189. * @default true
  24190. */
  24191. this.isLineCurve3 = true;
  24192. this.type = 'LineCurve3';
  24193. /**
  24194. * The start point.
  24195. *
  24196. * @type {Vector3}
  24197. */
  24198. this.v1 = v1;
  24199. /**
  24200. * The end point.
  24201. *
  24202. * @type {Vector2}
  24203. */
  24204. this.v2 = v2;
  24205. }
  24206. /**
  24207. * Returns a point on the line.
  24208. *
  24209. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24210. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24211. * @return {Vector3} The position on the line.
  24212. */
  24213. getPoint( t, optionalTarget = new Vector3() ) {
  24214. const point = optionalTarget;
  24215. if ( t === 1 ) {
  24216. point.copy( this.v2 );
  24217. } else {
  24218. point.copy( this.v2 ).sub( this.v1 );
  24219. point.multiplyScalar( t ).add( this.v1 );
  24220. }
  24221. return point;
  24222. }
  24223. // Line curve is linear, so we can overwrite default getPointAt
  24224. getPointAt( u, optionalTarget ) {
  24225. return this.getPoint( u, optionalTarget );
  24226. }
  24227. getTangent( t, optionalTarget = new Vector3() ) {
  24228. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24229. }
  24230. getTangentAt( u, optionalTarget ) {
  24231. return this.getTangent( u, optionalTarget );
  24232. }
  24233. copy( source ) {
  24234. super.copy( source );
  24235. this.v1.copy( source.v1 );
  24236. this.v2.copy( source.v2 );
  24237. return this;
  24238. }
  24239. toJSON() {
  24240. const data = super.toJSON();
  24241. data.v1 = this.v1.toArray();
  24242. data.v2 = this.v2.toArray();
  24243. return data;
  24244. }
  24245. fromJSON( json ) {
  24246. super.fromJSON( json );
  24247. this.v1.fromArray( json.v1 );
  24248. this.v2.fromArray( json.v2 );
  24249. return this;
  24250. }
  24251. }
  24252. /**
  24253. * A curve representing a 2D Quadratic Bezier curve.
  24254. *
  24255. * ```js
  24256. * const curve = new THREE.QuadraticBezierCurve(
  24257. * new THREE.Vector2( - 10, 0 ),
  24258. * new THREE.Vector2( 20, 15 ),
  24259. * new THREE.Vector2( 10, 0 )
  24260. * )
  24261. *
  24262. * const points = curve.getPoints( 50 );
  24263. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24264. *
  24265. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24266. *
  24267. * // Create the final object to add to the scene
  24268. * const curveObject = new THREE.Line( geometry, material );
  24269. * ```
  24270. *
  24271. * @augments Curve
  24272. */
  24273. class QuadraticBezierCurve extends Curve {
  24274. /**
  24275. * Constructs a new Quadratic Bezier curve.
  24276. *
  24277. * @param {Vector2} [v0] - The start point.
  24278. * @param {Vector2} [v1] - The control point.
  24279. * @param {Vector2} [v2] - The end point.
  24280. */
  24281. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  24282. super();
  24283. /**
  24284. * This flag can be used for type testing.
  24285. *
  24286. * @type {boolean}
  24287. * @readonly
  24288. * @default true
  24289. */
  24290. this.isQuadraticBezierCurve = true;
  24291. this.type = 'QuadraticBezierCurve';
  24292. /**
  24293. * The start point.
  24294. *
  24295. * @type {Vector2}
  24296. */
  24297. this.v0 = v0;
  24298. /**
  24299. * The control point.
  24300. *
  24301. * @type {Vector2}
  24302. */
  24303. this.v1 = v1;
  24304. /**
  24305. * The end point.
  24306. *
  24307. * @type {Vector2}
  24308. */
  24309. this.v2 = v2;
  24310. }
  24311. /**
  24312. * Returns a point on the curve.
  24313. *
  24314. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24315. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24316. * @return {Vector2} The position on the curve.
  24317. */
  24318. getPoint( t, optionalTarget = new Vector2() ) {
  24319. const point = optionalTarget;
  24320. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24321. point.set(
  24322. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24323. QuadraticBezier( t, v0.y, v1.y, v2.y )
  24324. );
  24325. return point;
  24326. }
  24327. copy( source ) {
  24328. super.copy( source );
  24329. this.v0.copy( source.v0 );
  24330. this.v1.copy( source.v1 );
  24331. this.v2.copy( source.v2 );
  24332. return this;
  24333. }
  24334. toJSON() {
  24335. const data = super.toJSON();
  24336. data.v0 = this.v0.toArray();
  24337. data.v1 = this.v1.toArray();
  24338. data.v2 = this.v2.toArray();
  24339. return data;
  24340. }
  24341. fromJSON( json ) {
  24342. super.fromJSON( json );
  24343. this.v0.fromArray( json.v0 );
  24344. this.v1.fromArray( json.v1 );
  24345. this.v2.fromArray( json.v2 );
  24346. return this;
  24347. }
  24348. }
  24349. /**
  24350. * A curve representing a 3D Quadratic Bezier curve.
  24351. *
  24352. * @augments Curve
  24353. */
  24354. class QuadraticBezierCurve3 extends Curve {
  24355. /**
  24356. * Constructs a new Quadratic Bezier curve.
  24357. *
  24358. * @param {Vector3} [v0] - The start point.
  24359. * @param {Vector3} [v1] - The control point.
  24360. * @param {Vector3} [v2] - The end point.
  24361. */
  24362. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  24363. super();
  24364. /**
  24365. * This flag can be used for type testing.
  24366. *
  24367. * @type {boolean}
  24368. * @readonly
  24369. * @default true
  24370. */
  24371. this.isQuadraticBezierCurve3 = true;
  24372. this.type = 'QuadraticBezierCurve3';
  24373. /**
  24374. * The start point.
  24375. *
  24376. * @type {Vector3}
  24377. */
  24378. this.v0 = v0;
  24379. /**
  24380. * The control point.
  24381. *
  24382. * @type {Vector3}
  24383. */
  24384. this.v1 = v1;
  24385. /**
  24386. * The end point.
  24387. *
  24388. * @type {Vector3}
  24389. */
  24390. this.v2 = v2;
  24391. }
  24392. /**
  24393. * Returns a point on the curve.
  24394. *
  24395. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24396. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24397. * @return {Vector3} The position on the curve.
  24398. */
  24399. getPoint( t, optionalTarget = new Vector3() ) {
  24400. const point = optionalTarget;
  24401. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24402. point.set(
  24403. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24404. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  24405. QuadraticBezier( t, v0.z, v1.z, v2.z )
  24406. );
  24407. return point;
  24408. }
  24409. copy( source ) {
  24410. super.copy( source );
  24411. this.v0.copy( source.v0 );
  24412. this.v1.copy( source.v1 );
  24413. this.v2.copy( source.v2 );
  24414. return this;
  24415. }
  24416. toJSON() {
  24417. const data = super.toJSON();
  24418. data.v0 = this.v0.toArray();
  24419. data.v1 = this.v1.toArray();
  24420. data.v2 = this.v2.toArray();
  24421. return data;
  24422. }
  24423. fromJSON( json ) {
  24424. super.fromJSON( json );
  24425. this.v0.fromArray( json.v0 );
  24426. this.v1.fromArray( json.v1 );
  24427. this.v2.fromArray( json.v2 );
  24428. return this;
  24429. }
  24430. }
  24431. /**
  24432. * A curve representing a 2D spline curve.
  24433. *
  24434. * ```js
  24435. * // Create a sine-like wave
  24436. * const curve = new THREE.SplineCurve( [
  24437. * new THREE.Vector2( -10, 0 ),
  24438. * new THREE.Vector2( -5, 5 ),
  24439. * new THREE.Vector2( 0, 0 ),
  24440. * new THREE.Vector2( 5, -5 ),
  24441. * new THREE.Vector2( 10, 0 )
  24442. * ] );
  24443. *
  24444. * const points = curve.getPoints( 50 );
  24445. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24446. *
  24447. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24448. *
  24449. * // Create the final object to add to the scene
  24450. * const splineObject = new THREE.Line( geometry, material );
  24451. * ```
  24452. *
  24453. * @augments Curve
  24454. */
  24455. class SplineCurve extends Curve {
  24456. /**
  24457. * Constructs a new 2D spline curve.
  24458. *
  24459. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  24460. */
  24461. constructor( points = [] ) {
  24462. super();
  24463. /**
  24464. * This flag can be used for type testing.
  24465. *
  24466. * @type {boolean}
  24467. * @readonly
  24468. * @default true
  24469. */
  24470. this.isSplineCurve = true;
  24471. this.type = 'SplineCurve';
  24472. /**
  24473. * An array of 2D points defining the curve.
  24474. *
  24475. * @type {Array<Vector2>}
  24476. */
  24477. this.points = points;
  24478. }
  24479. /**
  24480. * Returns a point on the curve.
  24481. *
  24482. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24483. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24484. * @return {Vector2} The position on the curve.
  24485. */
  24486. getPoint( t, optionalTarget = new Vector2() ) {
  24487. const point = optionalTarget;
  24488. const points = this.points;
  24489. const p = ( points.length - 1 ) * t;
  24490. const intPoint = Math.floor( p );
  24491. const weight = p - intPoint;
  24492. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24493. const p1 = points[ intPoint ];
  24494. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24495. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24496. point.set(
  24497. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24498. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  24499. );
  24500. return point;
  24501. }
  24502. copy( source ) {
  24503. super.copy( source );
  24504. this.points = [];
  24505. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24506. const point = source.points[ i ];
  24507. this.points.push( point.clone() );
  24508. }
  24509. return this;
  24510. }
  24511. toJSON() {
  24512. const data = super.toJSON();
  24513. data.points = [];
  24514. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24515. const point = this.points[ i ];
  24516. data.points.push( point.toArray() );
  24517. }
  24518. return data;
  24519. }
  24520. fromJSON( json ) {
  24521. super.fromJSON( json );
  24522. this.points = [];
  24523. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24524. const point = json.points[ i ];
  24525. this.points.push( new Vector2().fromArray( point ) );
  24526. }
  24527. return this;
  24528. }
  24529. }
  24530. var Curves = /*#__PURE__*/Object.freeze({
  24531. __proto__: null,
  24532. ArcCurve: ArcCurve,
  24533. CatmullRomCurve3: CatmullRomCurve3,
  24534. CubicBezierCurve: CubicBezierCurve,
  24535. CubicBezierCurve3: CubicBezierCurve3,
  24536. EllipseCurve: EllipseCurve,
  24537. LineCurve: LineCurve,
  24538. LineCurve3: LineCurve3,
  24539. QuadraticBezierCurve: QuadraticBezierCurve,
  24540. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24541. SplineCurve: SplineCurve
  24542. });
  24543. /**
  24544. * A base class extending {@link Curve}. `CurvePath` is simply an
  24545. * array of connected curves, but retains the API of a curve.
  24546. *
  24547. * @augments Curve
  24548. */
  24549. class CurvePath extends Curve {
  24550. /**
  24551. * Constructs a new curve path.
  24552. */
  24553. constructor() {
  24554. super();
  24555. this.type = 'CurvePath';
  24556. /**
  24557. * An array of curves defining the
  24558. * path.
  24559. *
  24560. * @type {Array<Curve>}
  24561. */
  24562. this.curves = [];
  24563. /**
  24564. * Whether the path should automatically be closed
  24565. * by a line curve.
  24566. *
  24567. * @type {boolean}
  24568. * @default false
  24569. */
  24570. this.autoClose = false;
  24571. }
  24572. /**
  24573. * Adds a curve to this curve path.
  24574. *
  24575. * @param {Curve} curve - The curve to add.
  24576. */
  24577. add( curve ) {
  24578. this.curves.push( curve );
  24579. }
  24580. /**
  24581. * Adds a line curve to close the path.
  24582. *
  24583. * @return {CurvePath} A reference to this curve path.
  24584. */
  24585. closePath() {
  24586. // Add a line curve if start and end of lines are not connected
  24587. const startPoint = this.curves[ 0 ].getPoint( 0 );
  24588. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24589. if ( ! startPoint.equals( endPoint ) ) {
  24590. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  24591. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  24592. }
  24593. return this;
  24594. }
  24595. /**
  24596. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  24597. * for the given interpolation factor.
  24598. *
  24599. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24600. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  24601. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  24602. */
  24603. getPoint( t, optionalTarget ) {
  24604. // To get accurate point with reference to
  24605. // entire path distance at time t,
  24606. // following has to be done:
  24607. // 1. Length of each sub path have to be known
  24608. // 2. Locate and identify type of curve
  24609. // 3. Get t for the curve
  24610. // 4. Return curve.getPointAt(t')
  24611. const d = t * this.getLength();
  24612. const curveLengths = this.getCurveLengths();
  24613. let i = 0;
  24614. // To think about boundaries points.
  24615. while ( i < curveLengths.length ) {
  24616. if ( curveLengths[ i ] >= d ) {
  24617. const diff = curveLengths[ i ] - d;
  24618. const curve = this.curves[ i ];
  24619. const segmentLength = curve.getLength();
  24620. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24621. return curve.getPointAt( u, optionalTarget );
  24622. }
  24623. i ++;
  24624. }
  24625. return null;
  24626. // loop where sum != 0, sum > d , sum+1 <d
  24627. }
  24628. getLength() {
  24629. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24630. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24631. // getPoint() depends on getLength
  24632. const lens = this.getCurveLengths();
  24633. return lens[ lens.length - 1 ];
  24634. }
  24635. updateArcLengths() {
  24636. // cacheLengths must be recalculated.
  24637. this.needsUpdate = true;
  24638. this.cacheLengths = null;
  24639. this.getCurveLengths();
  24640. }
  24641. /**
  24642. * Returns list of cumulative curve lengths of the defined curves.
  24643. *
  24644. * @return {Array<number>} The curve lengths.
  24645. */
  24646. getCurveLengths() {
  24647. // Compute lengths and cache them
  24648. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24649. // We use cache values if curves and cache array are same length
  24650. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24651. return this.cacheLengths;
  24652. }
  24653. // Get length of sub-curve
  24654. // Push sums into cached array
  24655. const lengths = [];
  24656. let sums = 0;
  24657. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24658. sums += this.curves[ i ].getLength();
  24659. lengths.push( sums );
  24660. }
  24661. this.cacheLengths = lengths;
  24662. return lengths;
  24663. }
  24664. getSpacedPoints( divisions = 40 ) {
  24665. const points = [];
  24666. for ( let i = 0; i <= divisions; i ++ ) {
  24667. points.push( this.getPoint( i / divisions ) );
  24668. }
  24669. if ( this.autoClose ) {
  24670. points.push( points[ 0 ] );
  24671. }
  24672. return points;
  24673. }
  24674. getPoints( divisions = 12 ) {
  24675. const points = [];
  24676. let last;
  24677. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24678. const curve = curves[ i ];
  24679. const resolution = curve.isEllipseCurve ? divisions * 2
  24680. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  24681. : curve.isSplineCurve ? divisions * curve.points.length
  24682. : divisions;
  24683. const pts = curve.getPoints( resolution );
  24684. for ( let j = 0; j < pts.length; j ++ ) {
  24685. const point = pts[ j ];
  24686. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24687. points.push( point );
  24688. last = point;
  24689. }
  24690. }
  24691. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24692. points.push( points[ 0 ] );
  24693. }
  24694. return points;
  24695. }
  24696. copy( source ) {
  24697. super.copy( source );
  24698. this.curves = [];
  24699. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  24700. const curve = source.curves[ i ];
  24701. this.curves.push( curve.clone() );
  24702. }
  24703. this.autoClose = source.autoClose;
  24704. return this;
  24705. }
  24706. toJSON() {
  24707. const data = super.toJSON();
  24708. data.autoClose = this.autoClose;
  24709. data.curves = [];
  24710. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24711. const curve = this.curves[ i ];
  24712. data.curves.push( curve.toJSON() );
  24713. }
  24714. return data;
  24715. }
  24716. fromJSON( json ) {
  24717. super.fromJSON( json );
  24718. this.autoClose = json.autoClose;
  24719. this.curves = [];
  24720. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  24721. const curve = json.curves[ i ];
  24722. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24723. }
  24724. return this;
  24725. }
  24726. }
  24727. /**
  24728. * A 2D path representation. The class provides methods for creating paths
  24729. * and contours of 2D shapes similar to the 2D Canvas API.
  24730. *
  24731. * ```js
  24732. * const path = new THREE.Path();
  24733. *
  24734. * path.lineTo( 0, 0.8 );
  24735. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  24736. * path.lineTo( 1, 1 );
  24737. *
  24738. * const points = path.getPoints();
  24739. *
  24740. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24741. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  24742. *
  24743. * const line = new THREE.Line( geometry, material );
  24744. * scene.add( line );
  24745. * ```
  24746. *
  24747. * @augments CurvePath
  24748. */
  24749. class Path extends CurvePath {
  24750. /**
  24751. * Constructs a new path.
  24752. *
  24753. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  24754. */
  24755. constructor( points ) {
  24756. super();
  24757. this.type = 'Path';
  24758. /**
  24759. * The current offset of the path. Any new curve added will start here.
  24760. *
  24761. * @type {Vector2}
  24762. */
  24763. this.currentPoint = new Vector2();
  24764. if ( points ) {
  24765. this.setFromPoints( points );
  24766. }
  24767. }
  24768. /**
  24769. * Creates a path from the given list of points. The points are added
  24770. * to the path as instances of {@link LineCurve}.
  24771. *
  24772. * @param {Array<Vector2>} points - An array of 2D points.
  24773. * @return {Path} A reference to this path.
  24774. */
  24775. setFromPoints( points ) {
  24776. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  24777. for ( let i = 1, l = points.length; i < l; i ++ ) {
  24778. this.lineTo( points[ i ].x, points[ i ].y );
  24779. }
  24780. return this;
  24781. }
  24782. /**
  24783. * Moves {@link Path#currentPoint} to the given point.
  24784. *
  24785. * @param {number} x - The x coordinate.
  24786. * @param {number} y - The y coordinate.
  24787. * @return {Path} A reference to this path.
  24788. */
  24789. moveTo( x, y ) {
  24790. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  24791. return this;
  24792. }
  24793. /**
  24794. * Adds an instance of {@link LineCurve} to the path by connecting
  24795. * the current point with the given one.
  24796. *
  24797. * @param {number} x - The x coordinate of the end point.
  24798. * @param {number} y - The y coordinate of the end point.
  24799. * @return {Path} A reference to this path.
  24800. */
  24801. lineTo( x, y ) {
  24802. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  24803. this.curves.push( curve );
  24804. this.currentPoint.set( x, y );
  24805. return this;
  24806. }
  24807. /**
  24808. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  24809. * the current point with the given one.
  24810. *
  24811. * @param {number} aCPx - The x coordinate of the control point.
  24812. * @param {number} aCPy - The y coordinate of the control point.
  24813. * @param {number} aX - The x coordinate of the end point.
  24814. * @param {number} aY - The y coordinate of the end point.
  24815. * @return {Path} A reference to this path.
  24816. */
  24817. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  24818. const curve = new QuadraticBezierCurve(
  24819. this.currentPoint.clone(),
  24820. new Vector2( aCPx, aCPy ),
  24821. new Vector2( aX, aY )
  24822. );
  24823. this.curves.push( curve );
  24824. this.currentPoint.set( aX, aY );
  24825. return this;
  24826. }
  24827. /**
  24828. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  24829. * the current point with the given one.
  24830. *
  24831. * @param {number} aCP1x - The x coordinate of the first control point.
  24832. * @param {number} aCP1y - The y coordinate of the first control point.
  24833. * @param {number} aCP2x - The x coordinate of the second control point.
  24834. * @param {number} aCP2y - The y coordinate of the second control point.
  24835. * @param {number} aX - The x coordinate of the end point.
  24836. * @param {number} aY - The y coordinate of the end point.
  24837. * @return {Path} A reference to this path.
  24838. */
  24839. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24840. const curve = new CubicBezierCurve(
  24841. this.currentPoint.clone(),
  24842. new Vector2( aCP1x, aCP1y ),
  24843. new Vector2( aCP2x, aCP2y ),
  24844. new Vector2( aX, aY )
  24845. );
  24846. this.curves.push( curve );
  24847. this.currentPoint.set( aX, aY );
  24848. return this;
  24849. }
  24850. /**
  24851. * Adds an instance of {@link SplineCurve} to the path by connecting
  24852. * the current point with the given list of points.
  24853. *
  24854. * @param {Array<Vector2>} pts - An array of points in 2D space.
  24855. * @return {Path} A reference to this path.
  24856. */
  24857. splineThru( pts ) {
  24858. const npts = [ this.currentPoint.clone() ].concat( pts );
  24859. const curve = new SplineCurve( npts );
  24860. this.curves.push( curve );
  24861. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24862. return this;
  24863. }
  24864. /**
  24865. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  24866. * to the current point.
  24867. *
  24868. * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
  24869. * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
  24870. * @param {number} [aRadius=1] - The radius of the arc.
  24871. * @param {number} [aStartAngle=0] - The start angle in radians.
  24872. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24873. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24874. * @return {Path} A reference to this path.
  24875. */
  24876. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24877. const x0 = this.currentPoint.x;
  24878. const y0 = this.currentPoint.y;
  24879. this.absarc( aX + x0, aY + y0, aRadius,
  24880. aStartAngle, aEndAngle, aClockwise );
  24881. return this;
  24882. }
  24883. /**
  24884. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  24885. *
  24886. * @param {number} [aX=0] - The x coordinate of the center of the arc.
  24887. * @param {number} [aY=0] - The y coordinate of the center of the arc.
  24888. * @param {number} [aRadius=1] - The radius of the arc.
  24889. * @param {number} [aStartAngle=0] - The start angle in radians.
  24890. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24891. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24892. * @return {Path} A reference to this path.
  24893. */
  24894. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24895. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24896. return this;
  24897. }
  24898. /**
  24899. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  24900. * to the current point
  24901. *
  24902. * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
  24903. * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
  24904. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24905. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24906. * @param {number} [aStartAngle=0] - The start angle in radians.
  24907. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24908. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24909. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24910. * @return {Path} A reference to this path.
  24911. */
  24912. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24913. const x0 = this.currentPoint.x;
  24914. const y0 = this.currentPoint.y;
  24915. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24916. return this;
  24917. }
  24918. /**
  24919. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  24920. *
  24921. * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
  24922. * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
  24923. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24924. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24925. * @param {number} [aStartAngle=0] - The start angle in radians.
  24926. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24927. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24928. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24929. * @return {Path} A reference to this path.
  24930. */
  24931. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24932. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24933. if ( this.curves.length > 0 ) {
  24934. // if a previous curve is present, attempt to join
  24935. const firstPoint = curve.getPoint( 0 );
  24936. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24937. this.lineTo( firstPoint.x, firstPoint.y );
  24938. }
  24939. }
  24940. this.curves.push( curve );
  24941. const lastPoint = curve.getPoint( 1 );
  24942. this.currentPoint.copy( lastPoint );
  24943. return this;
  24944. }
  24945. copy( source ) {
  24946. super.copy( source );
  24947. this.currentPoint.copy( source.currentPoint );
  24948. return this;
  24949. }
  24950. toJSON() {
  24951. const data = super.toJSON();
  24952. data.currentPoint = this.currentPoint.toArray();
  24953. return data;
  24954. }
  24955. fromJSON( json ) {
  24956. super.fromJSON( json );
  24957. this.currentPoint.fromArray( json.currentPoint );
  24958. return this;
  24959. }
  24960. }
  24961. /**
  24962. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  24963. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  24964. * points, or to get triangulated faces.
  24965. *
  24966. * ```js
  24967. * const heartShape = new THREE.Shape();
  24968. *
  24969. * heartShape.moveTo( 25, 25 );
  24970. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  24971. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  24972. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  24973. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  24974. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  24975. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  24976. *
  24977. * const extrudeSettings = {
  24978. * depth: 8,
  24979. * bevelEnabled: true,
  24980. * bevelSegments: 2,
  24981. * steps: 2,
  24982. * bevelSize: 1,
  24983. * bevelThickness: 1
  24984. * };
  24985. *
  24986. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  24987. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  24988. * ```
  24989. *
  24990. * @augments Path
  24991. */
  24992. class Shape extends Path {
  24993. /**
  24994. * Constructs a new shape.
  24995. *
  24996. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  24997. */
  24998. constructor( points ) {
  24999. super( points );
  25000. /**
  25001. * The UUID of the shape.
  25002. *
  25003. * @type {string}
  25004. * @readonly
  25005. */
  25006. this.uuid = generateUUID();
  25007. this.type = 'Shape';
  25008. /**
  25009. * Defines the holes in the shape. Hole definitions must use the
  25010. * opposite winding order (CW/CCW) than the outer shape.
  25011. *
  25012. * @type {Array<Path>}
  25013. * @readonly
  25014. */
  25015. this.holes = [];
  25016. }
  25017. /**
  25018. * Returns an array representing each contour of the holes
  25019. * as a list of 2D points.
  25020. *
  25021. * @param {number} divisions - The fineness of the result.
  25022. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  25023. */
  25024. getPointsHoles( divisions ) {
  25025. const holesPts = [];
  25026. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25027. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  25028. }
  25029. return holesPts;
  25030. }
  25031. // get points of shape and holes (keypoints based on segments parameter)
  25032. /**
  25033. * Returns an object that holds contour data for the shape and its holes as
  25034. * arrays of 2D points.
  25035. *
  25036. * @param {number} divisions - The fineness of the result.
  25037. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  25038. */
  25039. extractPoints( divisions ) {
  25040. return {
  25041. shape: this.getPoints( divisions ),
  25042. holes: this.getPointsHoles( divisions )
  25043. };
  25044. }
  25045. copy( source ) {
  25046. super.copy( source );
  25047. this.holes = [];
  25048. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  25049. const hole = source.holes[ i ];
  25050. this.holes.push( hole.clone() );
  25051. }
  25052. return this;
  25053. }
  25054. toJSON() {
  25055. const data = super.toJSON();
  25056. data.uuid = this.uuid;
  25057. data.holes = [];
  25058. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25059. const hole = this.holes[ i ];
  25060. data.holes.push( hole.toJSON() );
  25061. }
  25062. return data;
  25063. }
  25064. fromJSON( json ) {
  25065. super.fromJSON( json );
  25066. this.uuid = json.uuid;
  25067. this.holes = [];
  25068. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  25069. const hole = json.holes[ i ];
  25070. this.holes.push( new Path().fromJSON( hole ) );
  25071. }
  25072. return this;
  25073. }
  25074. }
  25075. /* eslint-disable */
  25076. // copy of mapbox/earcut version 3.0.1
  25077. // https://github.com/mapbox/earcut/tree/v3.0.1
  25078. function earcut(data, holeIndices, dim = 2) {
  25079. const hasHoles = holeIndices && holeIndices.length;
  25080. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  25081. let outerNode = linkedList(data, 0, outerLen, dim, true);
  25082. const triangles = [];
  25083. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  25084. let minX, minY, invSize;
  25085. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  25086. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  25087. if (data.length > 80 * dim) {
  25088. minX = Infinity;
  25089. minY = Infinity;
  25090. let maxX = -Infinity;
  25091. let maxY = -Infinity;
  25092. for (let i = dim; i < outerLen; i += dim) {
  25093. const x = data[i];
  25094. const y = data[i + 1];
  25095. if (x < minX) minX = x;
  25096. if (y < minY) minY = y;
  25097. if (x > maxX) maxX = x;
  25098. if (y > maxY) maxY = y;
  25099. }
  25100. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  25101. invSize = Math.max(maxX - minX, maxY - minY);
  25102. invSize = invSize !== 0 ? 32767 / invSize : 0;
  25103. }
  25104. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  25105. return triangles;
  25106. }
  25107. // create a circular doubly linked list from polygon points in the specified winding order
  25108. function linkedList(data, start, end, dim, clockwise) {
  25109. let last;
  25110. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  25111. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25112. } else {
  25113. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25114. }
  25115. if (last && equals(last, last.next)) {
  25116. removeNode(last);
  25117. last = last.next;
  25118. }
  25119. return last;
  25120. }
  25121. // eliminate colinear or duplicate points
  25122. function filterPoints(start, end) {
  25123. if (!start) return start;
  25124. if (!end) end = start;
  25125. let p = start,
  25126. again;
  25127. do {
  25128. again = false;
  25129. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  25130. removeNode(p);
  25131. p = end = p.prev;
  25132. if (p === p.next) break;
  25133. again = true;
  25134. } else {
  25135. p = p.next;
  25136. }
  25137. } while (again || p !== end);
  25138. return end;
  25139. }
  25140. // main ear slicing loop which triangulates a polygon (given as a linked list)
  25141. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  25142. if (!ear) return;
  25143. // interlink polygon nodes in z-order
  25144. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  25145. let stop = ear;
  25146. // iterate through ears, slicing them one by one
  25147. while (ear.prev !== ear.next) {
  25148. const prev = ear.prev;
  25149. const next = ear.next;
  25150. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  25151. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  25152. removeNode(ear);
  25153. // skipping the next vertex leads to less sliver triangles
  25154. ear = next.next;
  25155. stop = next.next;
  25156. continue;
  25157. }
  25158. ear = next;
  25159. // if we looped through the whole remaining polygon and can't find any more ears
  25160. if (ear === stop) {
  25161. // try filtering points and slicing again
  25162. if (!pass) {
  25163. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  25164. // if this didn't work, try curing all small self-intersections locally
  25165. } else if (pass === 1) {
  25166. ear = cureLocalIntersections(filterPoints(ear), triangles);
  25167. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  25168. // as a last resort, try splitting the remaining polygon into two
  25169. } else if (pass === 2) {
  25170. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  25171. }
  25172. break;
  25173. }
  25174. }
  25175. }
  25176. // check whether a polygon node forms a valid ear with adjacent nodes
  25177. function isEar(ear) {
  25178. const a = ear.prev,
  25179. b = ear,
  25180. c = ear.next;
  25181. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25182. // now make sure we don't have other points inside the potential ear
  25183. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25184. // triangle bbox
  25185. const x0 = Math.min(ax, bx, cx),
  25186. y0 = Math.min(ay, by, cy),
  25187. x1 = Math.max(ax, bx, cx),
  25188. y1 = Math.max(ay, by, cy);
  25189. let p = c.next;
  25190. while (p !== a) {
  25191. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  25192. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  25193. area(p.prev, p, p.next) >= 0) return false;
  25194. p = p.next;
  25195. }
  25196. return true;
  25197. }
  25198. function isEarHashed(ear, minX, minY, invSize) {
  25199. const a = ear.prev,
  25200. b = ear,
  25201. c = ear.next;
  25202. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25203. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25204. // triangle bbox
  25205. const x0 = Math.min(ax, bx, cx),
  25206. y0 = Math.min(ay, by, cy),
  25207. x1 = Math.max(ax, bx, cx),
  25208. y1 = Math.max(ay, by, cy);
  25209. // z-order range for the current triangle bbox;
  25210. const minZ = zOrder(x0, y0, minX, minY, invSize),
  25211. maxZ = zOrder(x1, y1, minX, minY, invSize);
  25212. let p = ear.prevZ,
  25213. n = ear.nextZ;
  25214. // look for points inside the triangle in both directions
  25215. while (p && p.z >= minZ && n && n.z <= maxZ) {
  25216. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25217. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25218. p = p.prevZ;
  25219. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25220. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25221. n = n.nextZ;
  25222. }
  25223. // look for remaining points in decreasing z-order
  25224. while (p && p.z >= minZ) {
  25225. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25226. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25227. p = p.prevZ;
  25228. }
  25229. // look for remaining points in increasing z-order
  25230. while (n && n.z <= maxZ) {
  25231. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25232. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25233. n = n.nextZ;
  25234. }
  25235. return true;
  25236. }
  25237. // go through all polygon nodes and cure small local self-intersections
  25238. function cureLocalIntersections(start, triangles) {
  25239. let p = start;
  25240. do {
  25241. const a = p.prev,
  25242. b = p.next.next;
  25243. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  25244. triangles.push(a.i, p.i, b.i);
  25245. // remove two nodes involved
  25246. removeNode(p);
  25247. removeNode(p.next);
  25248. p = start = b;
  25249. }
  25250. p = p.next;
  25251. } while (p !== start);
  25252. return filterPoints(p);
  25253. }
  25254. // try splitting polygon into two and triangulate them independently
  25255. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  25256. // look for a valid diagonal that divides the polygon into two
  25257. let a = start;
  25258. do {
  25259. let b = a.next.next;
  25260. while (b !== a.prev) {
  25261. if (a.i !== b.i && isValidDiagonal(a, b)) {
  25262. // split the polygon in two by the diagonal
  25263. let c = splitPolygon(a, b);
  25264. // filter colinear points around the cuts
  25265. a = filterPoints(a, a.next);
  25266. c = filterPoints(c, c.next);
  25267. // run earcut on each half
  25268. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  25269. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  25270. return;
  25271. }
  25272. b = b.next;
  25273. }
  25274. a = a.next;
  25275. } while (a !== start);
  25276. }
  25277. // link every hole into the outer loop, producing a single-ring polygon without holes
  25278. function eliminateHoles(data, holeIndices, outerNode, dim) {
  25279. const queue = [];
  25280. for (let i = 0, len = holeIndices.length; i < len; i++) {
  25281. const start = holeIndices[i] * dim;
  25282. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  25283. const list = linkedList(data, start, end, dim, false);
  25284. if (list === list.next) list.steiner = true;
  25285. queue.push(getLeftmost(list));
  25286. }
  25287. queue.sort(compareXYSlope);
  25288. // process holes from left to right
  25289. for (let i = 0; i < queue.length; i++) {
  25290. outerNode = eliminateHole(queue[i], outerNode);
  25291. }
  25292. return outerNode;
  25293. }
  25294. function compareXYSlope(a, b) {
  25295. let result = a.x - b.x;
  25296. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  25297. // the bridge to the outer shell is always the point that they meet at.
  25298. if (result === 0) {
  25299. result = a.y - b.y;
  25300. if (result === 0) {
  25301. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  25302. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  25303. result = aSlope - bSlope;
  25304. }
  25305. }
  25306. return result;
  25307. }
  25308. // find a bridge between vertices that connects hole with an outer ring and and link it
  25309. function eliminateHole(hole, outerNode) {
  25310. const bridge = findHoleBridge(hole, outerNode);
  25311. if (!bridge) {
  25312. return outerNode;
  25313. }
  25314. const bridgeReverse = splitPolygon(bridge, hole);
  25315. // filter collinear points around the cuts
  25316. filterPoints(bridgeReverse, bridgeReverse.next);
  25317. return filterPoints(bridge, bridge.next);
  25318. }
  25319. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  25320. function findHoleBridge(hole, outerNode) {
  25321. let p = outerNode;
  25322. const hx = hole.x;
  25323. const hy = hole.y;
  25324. let qx = -Infinity;
  25325. let m;
  25326. // find a segment intersected by a ray from the hole's leftmost point to the left;
  25327. // segment's endpoint with lesser x will be potential connection point
  25328. // unless they intersect at a vertex, then choose the vertex
  25329. if (equals(hole, p)) return p;
  25330. do {
  25331. if (equals(hole, p.next)) return p.next;
  25332. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  25333. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  25334. if (x <= hx && x > qx) {
  25335. qx = x;
  25336. m = p.x < p.next.x ? p : p.next;
  25337. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  25338. }
  25339. }
  25340. p = p.next;
  25341. } while (p !== outerNode);
  25342. if (!m) return null;
  25343. // look for points inside the triangle of hole point, segment intersection and endpoint;
  25344. // if there are no points found, we have a valid connection;
  25345. // otherwise choose the point of the minimum angle with the ray as connection point
  25346. const stop = m;
  25347. const mx = m.x;
  25348. const my = m.y;
  25349. let tanMin = Infinity;
  25350. p = m;
  25351. do {
  25352. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  25353. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  25354. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  25355. if (locallyInside(p, hole) &&
  25356. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  25357. m = p;
  25358. tanMin = tan;
  25359. }
  25360. }
  25361. p = p.next;
  25362. } while (p !== stop);
  25363. return m;
  25364. }
  25365. // whether sector in vertex m contains sector in vertex p in the same coordinates
  25366. function sectorContainsSector(m, p) {
  25367. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  25368. }
  25369. // interlink polygon nodes in z-order
  25370. function indexCurve(start, minX, minY, invSize) {
  25371. let p = start;
  25372. do {
  25373. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  25374. p.prevZ = p.prev;
  25375. p.nextZ = p.next;
  25376. p = p.next;
  25377. } while (p !== start);
  25378. p.prevZ.nextZ = null;
  25379. p.prevZ = null;
  25380. sortLinked(p);
  25381. }
  25382. // Simon Tatham's linked list merge sort algorithm
  25383. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  25384. function sortLinked(list) {
  25385. let numMerges;
  25386. let inSize = 1;
  25387. do {
  25388. let p = list;
  25389. let e;
  25390. list = null;
  25391. let tail = null;
  25392. numMerges = 0;
  25393. while (p) {
  25394. numMerges++;
  25395. let q = p;
  25396. let pSize = 0;
  25397. for (let i = 0; i < inSize; i++) {
  25398. pSize++;
  25399. q = q.nextZ;
  25400. if (!q) break;
  25401. }
  25402. let qSize = inSize;
  25403. while (pSize > 0 || (qSize > 0 && q)) {
  25404. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  25405. e = p;
  25406. p = p.nextZ;
  25407. pSize--;
  25408. } else {
  25409. e = q;
  25410. q = q.nextZ;
  25411. qSize--;
  25412. }
  25413. if (tail) tail.nextZ = e;
  25414. else list = e;
  25415. e.prevZ = tail;
  25416. tail = e;
  25417. }
  25418. p = q;
  25419. }
  25420. tail.nextZ = null;
  25421. inSize *= 2;
  25422. } while (numMerges > 1);
  25423. return list;
  25424. }
  25425. // z-order of a point given coords and inverse of the longer side of data bbox
  25426. function zOrder(x, y, minX, minY, invSize) {
  25427. // coords are transformed into non-negative 15-bit integer range
  25428. x = (x - minX) * invSize | 0;
  25429. y = (y - minY) * invSize | 0;
  25430. x = (x | (x << 8)) & 0x00FF00FF;
  25431. x = (x | (x << 4)) & 0x0F0F0F0F;
  25432. x = (x | (x << 2)) & 0x33333333;
  25433. x = (x | (x << 1)) & 0x55555555;
  25434. y = (y | (y << 8)) & 0x00FF00FF;
  25435. y = (y | (y << 4)) & 0x0F0F0F0F;
  25436. y = (y | (y << 2)) & 0x33333333;
  25437. y = (y | (y << 1)) & 0x55555555;
  25438. return x | (y << 1);
  25439. }
  25440. // find the leftmost node of a polygon ring
  25441. function getLeftmost(start) {
  25442. let p = start,
  25443. leftmost = start;
  25444. do {
  25445. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  25446. p = p.next;
  25447. } while (p !== start);
  25448. return leftmost;
  25449. }
  25450. // check if a point lies within a convex triangle
  25451. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  25452. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  25453. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  25454. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  25455. }
  25456. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  25457. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  25458. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  25459. }
  25460. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25461. function isValidDiagonal(a, b) {
  25462. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges
  25463. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  25464. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25465. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25466. }
  25467. // signed area of a triangle
  25468. function area(p, q, r) {
  25469. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25470. }
  25471. // check if two points are equal
  25472. function equals(p1, p2) {
  25473. return p1.x === p2.x && p1.y === p2.y;
  25474. }
  25475. // check if two segments intersect
  25476. function intersects(p1, q1, p2, q2) {
  25477. const o1 = sign(area(p1, q1, p2));
  25478. const o2 = sign(area(p1, q1, q2));
  25479. const o3 = sign(area(p2, q2, p1));
  25480. const o4 = sign(area(p2, q2, q1));
  25481. if (o1 !== o2 && o3 !== o4) return true; // general case
  25482. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25483. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25484. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25485. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25486. return false;
  25487. }
  25488. // for collinear points p, q, r, check if point q lies on segment pr
  25489. function onSegment(p, q, r) {
  25490. 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);
  25491. }
  25492. function sign(num) {
  25493. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25494. }
  25495. // check if a polygon diagonal intersects any polygon segments
  25496. function intersectsPolygon(a, b) {
  25497. let p = a;
  25498. do {
  25499. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25500. intersects(p, p.next, a, b)) return true;
  25501. p = p.next;
  25502. } while (p !== a);
  25503. return false;
  25504. }
  25505. // check if a polygon diagonal is locally inside the polygon
  25506. function locallyInside(a, b) {
  25507. return area(a.prev, a, a.next) < 0 ?
  25508. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  25509. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  25510. }
  25511. // check if the middle point of a polygon diagonal is inside the polygon
  25512. function middleInside(a, b) {
  25513. let p = a;
  25514. let inside = false;
  25515. const px = (a.x + b.x) / 2;
  25516. const py = (a.y + b.y) / 2;
  25517. do {
  25518. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  25519. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  25520. inside = !inside;
  25521. p = p.next;
  25522. } while (p !== a);
  25523. return inside;
  25524. }
  25525. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25526. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25527. function splitPolygon(a, b) {
  25528. const a2 = createNode(a.i, a.x, a.y),
  25529. b2 = createNode(b.i, b.x, b.y),
  25530. an = a.next,
  25531. bp = b.prev;
  25532. a.next = b;
  25533. b.prev = a;
  25534. a2.next = an;
  25535. an.prev = a2;
  25536. b2.next = a2;
  25537. a2.prev = b2;
  25538. bp.next = b2;
  25539. b2.prev = bp;
  25540. return b2;
  25541. }
  25542. // create a node and optionally link it with previous one (in a circular doubly linked list)
  25543. function insertNode(i, x, y, last) {
  25544. const p = createNode(i, x, y);
  25545. if (!last) {
  25546. p.prev = p;
  25547. p.next = p;
  25548. } else {
  25549. p.next = last.next;
  25550. p.prev = last;
  25551. last.next.prev = p;
  25552. last.next = p;
  25553. }
  25554. return p;
  25555. }
  25556. function removeNode(p) {
  25557. p.next.prev = p.prev;
  25558. p.prev.next = p.next;
  25559. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  25560. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  25561. }
  25562. function createNode(i, x, y) {
  25563. return {
  25564. i, // vertex index in coordinates array
  25565. x, y, // vertex coordinates
  25566. prev: null, // previous and next vertex nodes in a polygon ring
  25567. next: null,
  25568. z: 0, // z-order curve value
  25569. prevZ: null, // previous and next nodes in z-order
  25570. nextZ: null,
  25571. steiner: false // indicates whether this is a steiner point
  25572. };
  25573. }
  25574. function signedArea(data, start, end, dim) {
  25575. let sum = 0;
  25576. for (let i = start, j = end - dim; i < end; i += dim) {
  25577. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  25578. j = i;
  25579. }
  25580. return sum;
  25581. }
  25582. class Earcut {
  25583. /**
  25584. * Triangulates the given shape definition by returning an array of triangles.
  25585. *
  25586. * @param {Array<number>} data - An array with 2D points.
  25587. * @param {Array<number>} holeIndices - An array with indices defining holes.
  25588. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  25589. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  25590. * representing vertex indices.
  25591. */
  25592. static triangulate( data, holeIndices, dim = 2 ) {
  25593. return earcut( data, holeIndices, dim );
  25594. }
  25595. }
  25596. /**
  25597. * A class containing utility functions for shapes.
  25598. *
  25599. * @hideconstructor
  25600. */
  25601. class ShapeUtils {
  25602. /**
  25603. * Calculate area of a ( 2D ) contour polygon.
  25604. *
  25605. * @param {Array<Vector2>} contour - An array of 2D points.
  25606. * @return {number} The area.
  25607. */
  25608. static area( contour ) {
  25609. const n = contour.length;
  25610. let a = 0.0;
  25611. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  25612. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  25613. }
  25614. return a * 0.5;
  25615. }
  25616. /**
  25617. * Returns `true` if the given contour uses a clockwise winding order.
  25618. *
  25619. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  25620. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  25621. */
  25622. static isClockWise( pts ) {
  25623. return ShapeUtils.area( pts ) < 0;
  25624. }
  25625. /**
  25626. * Triangulates the given shape definition.
  25627. *
  25628. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  25629. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  25630. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  25631. */
  25632. static triangulateShape( contour, holes ) {
  25633. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25634. const holeIndices = []; // array of hole indices
  25635. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25636. removeDupEndPts( contour );
  25637. addContour( vertices, contour );
  25638. //
  25639. let holeIndex = contour.length;
  25640. holes.forEach( removeDupEndPts );
  25641. for ( let i = 0; i < holes.length; i ++ ) {
  25642. holeIndices.push( holeIndex );
  25643. holeIndex += holes[ i ].length;
  25644. addContour( vertices, holes[ i ] );
  25645. }
  25646. //
  25647. const triangles = Earcut.triangulate( vertices, holeIndices );
  25648. //
  25649. for ( let i = 0; i < triangles.length; i += 3 ) {
  25650. faces.push( triangles.slice( i, i + 3 ) );
  25651. }
  25652. return faces;
  25653. }
  25654. }
  25655. function removeDupEndPts( points ) {
  25656. const l = points.length;
  25657. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  25658. points.pop();
  25659. }
  25660. }
  25661. function addContour( vertices, contour ) {
  25662. for ( let i = 0; i < contour.length; i ++ ) {
  25663. vertices.push( contour[ i ].x );
  25664. vertices.push( contour[ i ].y );
  25665. }
  25666. }
  25667. /**
  25668. * Creates extruded geometry from a path shape.
  25669. *
  25670. * ```js
  25671. * const length = 12, width = 8;
  25672. *
  25673. * const shape = new THREE.Shape();
  25674. * shape.moveTo( 0,0 );
  25675. * shape.lineTo( 0, width );
  25676. * shape.lineTo( length, width );
  25677. * shape.lineTo( length, 0 );
  25678. * shape.lineTo( 0, 0 );
  25679. *
  25680. * const geometry = new THREE.ExtrudeGeometry( shape );
  25681. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  25682. * const mesh = new THREE.Mesh( geometry, material ) ;
  25683. * scene.add( mesh );
  25684. * ```
  25685. *
  25686. * @augments BufferGeometry
  25687. */
  25688. class ExtrudeGeometry extends BufferGeometry {
  25689. /**
  25690. * Constructs a new extrude geometry.
  25691. *
  25692. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  25693. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  25694. */
  25695. 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 = {} ) {
  25696. super();
  25697. this.type = 'ExtrudeGeometry';
  25698. /**
  25699. * Holds the constructor parameters that have been
  25700. * used to generate the geometry. Any modification
  25701. * after instantiation does not change the geometry.
  25702. *
  25703. * @type {Object}
  25704. */
  25705. this.parameters = {
  25706. shapes: shapes,
  25707. options: options
  25708. };
  25709. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  25710. const scope = this;
  25711. const verticesArray = [];
  25712. const uvArray = [];
  25713. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25714. const shape = shapes[ i ];
  25715. addShape( shape );
  25716. }
  25717. // build geometry
  25718. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  25719. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  25720. this.computeVertexNormals();
  25721. // functions
  25722. function addShape( shape ) {
  25723. const placeholder = [];
  25724. // options
  25725. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  25726. const steps = options.steps !== undefined ? options.steps : 1;
  25727. const depth = options.depth !== undefined ? options.depth : 1;
  25728. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  25729. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  25730. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  25731. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  25732. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  25733. const extrudePath = options.extrudePath;
  25734. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  25735. //
  25736. let extrudePts, extrudeByPath = false;
  25737. let splineTube, binormal, normal, position2;
  25738. if ( extrudePath ) {
  25739. extrudePts = extrudePath.getSpacedPoints( steps );
  25740. extrudeByPath = true;
  25741. bevelEnabled = false; // bevels not supported for path extrusion
  25742. // SETUP TNB variables
  25743. // TODO1 - have a .isClosed in spline?
  25744. splineTube = extrudePath.computeFrenetFrames( steps, false );
  25745. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  25746. binormal = new Vector3();
  25747. normal = new Vector3();
  25748. position2 = new Vector3();
  25749. }
  25750. // Safeguards if bevels are not enabled
  25751. if ( ! bevelEnabled ) {
  25752. bevelSegments = 0;
  25753. bevelThickness = 0;
  25754. bevelSize = 0;
  25755. bevelOffset = 0;
  25756. }
  25757. // Variables initialization
  25758. const shapePoints = shape.extractPoints( curveSegments );
  25759. let vertices = shapePoints.shape;
  25760. const holes = shapePoints.holes;
  25761. const reverse = ! ShapeUtils.isClockWise( vertices );
  25762. if ( reverse ) {
  25763. vertices = vertices.reverse();
  25764. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  25765. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25766. const ahole = holes[ h ];
  25767. if ( ShapeUtils.isClockWise( ahole ) ) {
  25768. holes[ h ] = ahole.reverse();
  25769. }
  25770. }
  25771. }
  25772. /**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.
  25773. * @param {Array<Vector2>} points
  25774. */
  25775. function mergeOverlappingPoints( points ) {
  25776. const THRESHOLD = 1e-10;
  25777. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  25778. let prevPos = points[ 0 ];
  25779. for ( let i = 1; i <= points.length; i ++ ) {
  25780. const currentIndex = i % points.length;
  25781. const currentPos = points[ currentIndex ];
  25782. const dx = currentPos.x - prevPos.x;
  25783. const dy = currentPos.y - prevPos.y;
  25784. const distSq = dx * dx + dy * dy;
  25785. const scalingFactorSqrt = Math.max(
  25786. Math.abs( currentPos.x ),
  25787. Math.abs( currentPos.y ),
  25788. Math.abs( prevPos.x ),
  25789. Math.abs( prevPos.y )
  25790. );
  25791. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  25792. if ( distSq <= thresholdSqScaled ) {
  25793. points.splice( currentIndex, 1 );
  25794. i --;
  25795. continue;
  25796. }
  25797. prevPos = currentPos;
  25798. }
  25799. }
  25800. mergeOverlappingPoints( vertices );
  25801. holes.forEach( mergeOverlappingPoints );
  25802. const numHoles = holes.length;
  25803. /* Vertices */
  25804. const contour = vertices; // vertices has all points but contour has only points of circumference
  25805. for ( let h = 0; h < numHoles; h ++ ) {
  25806. const ahole = holes[ h ];
  25807. vertices = vertices.concat( ahole );
  25808. }
  25809. function scalePt2( pt, vec, size ) {
  25810. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  25811. return pt.clone().addScaledVector( vec, size );
  25812. }
  25813. const vlen = vertices.length;
  25814. // Find directions for point movement
  25815. function getBevelVec( inPt, inPrev, inNext ) {
  25816. // computes for inPt the corresponding point inPt' on a new contour
  25817. // shifted by 1 unit (length of normalized vector) to the left
  25818. // if we walk along contour clockwise, this new contour is outside the old one
  25819. //
  25820. // inPt' is the intersection of the two lines parallel to the two
  25821. // adjacent edges of inPt at a distance of 1 unit on the left side.
  25822. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  25823. // good reading for geometry algorithms (here: line-line intersection)
  25824. // http://geomalgorithms.com/a05-_intersect-1.html
  25825. const v_prev_x = inPt.x - inPrev.x,
  25826. v_prev_y = inPt.y - inPrev.y;
  25827. const v_next_x = inNext.x - inPt.x,
  25828. v_next_y = inNext.y - inPt.y;
  25829. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  25830. // check for collinear edges
  25831. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25832. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  25833. // not collinear
  25834. // length of vectors for normalizing
  25835. const v_prev_len = Math.sqrt( v_prev_lensq );
  25836. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  25837. // shift adjacent points by unit vectors to the left
  25838. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  25839. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  25840. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  25841. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  25842. // scaling factor for v_prev to intersection point
  25843. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  25844. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  25845. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25846. // vector from inPt to intersection point
  25847. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  25848. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  25849. // Don't normalize!, otherwise sharp corners become ugly
  25850. // but prevent crazy spikes
  25851. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  25852. if ( v_trans_lensq <= 2 ) {
  25853. return new Vector2( v_trans_x, v_trans_y );
  25854. } else {
  25855. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  25856. }
  25857. } else {
  25858. // handle special case of collinear edges
  25859. let direction_eq = false; // assumes: opposite
  25860. if ( v_prev_x > Number.EPSILON ) {
  25861. if ( v_next_x > Number.EPSILON ) {
  25862. direction_eq = true;
  25863. }
  25864. } else {
  25865. if ( v_prev_x < - Number.EPSILON ) {
  25866. if ( v_next_x < - Number.EPSILON ) {
  25867. direction_eq = true;
  25868. }
  25869. } else {
  25870. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  25871. direction_eq = true;
  25872. }
  25873. }
  25874. }
  25875. if ( direction_eq ) {
  25876. // console.log("Warning: lines are a straight sequence");
  25877. v_trans_x = - v_prev_y;
  25878. v_trans_y = v_prev_x;
  25879. shrink_by = Math.sqrt( v_prev_lensq );
  25880. } else {
  25881. // console.log("Warning: lines are a straight spike");
  25882. v_trans_x = v_prev_x;
  25883. v_trans_y = v_prev_y;
  25884. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  25885. }
  25886. }
  25887. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  25888. }
  25889. const contourMovements = [];
  25890. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25891. if ( j === il ) j = 0;
  25892. if ( k === il ) k = 0;
  25893. // (j)---(i)---(k)
  25894. // console.log('i,j,k', i, j , k)
  25895. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  25896. }
  25897. const holesMovements = [];
  25898. let oneHoleMovements, verticesMovements = contourMovements.concat();
  25899. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25900. const ahole = holes[ h ];
  25901. oneHoleMovements = [];
  25902. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25903. if ( j === il ) j = 0;
  25904. if ( k === il ) k = 0;
  25905. // (j)---(i)---(k)
  25906. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  25907. }
  25908. holesMovements.push( oneHoleMovements );
  25909. verticesMovements = verticesMovements.concat( oneHoleMovements );
  25910. }
  25911. let faces;
  25912. if ( bevelSegments === 0 ) {
  25913. faces = ShapeUtils.triangulateShape( contour, holes );
  25914. } else {
  25915. const contractedContourVertices = [];
  25916. const expandedHoleVertices = [];
  25917. // Loop bevelSegments, 1 for the front, 1 for the back
  25918. for ( let b = 0; b < bevelSegments; b ++ ) {
  25919. //for ( b = bevelSegments; b > 0; b -- ) {
  25920. const t = b / bevelSegments;
  25921. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25922. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25923. // contract shape
  25924. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25925. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25926. v( vert.x, vert.y, - z );
  25927. if ( t === 0 ) contractedContourVertices.push( vert );
  25928. }
  25929. // expand holes
  25930. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25931. const ahole = holes[ h ];
  25932. oneHoleMovements = holesMovements[ h ];
  25933. const oneHoleVertices = [];
  25934. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25935. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25936. v( vert.x, vert.y, - z );
  25937. if ( t === 0 ) oneHoleVertices.push( vert );
  25938. }
  25939. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  25940. }
  25941. }
  25942. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  25943. }
  25944. const flen = faces.length;
  25945. const bs = bevelSize + bevelOffset;
  25946. // Back facing vertices
  25947. for ( let i = 0; i < vlen; i ++ ) {
  25948. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25949. if ( ! extrudeByPath ) {
  25950. v( vert.x, vert.y, 0 );
  25951. } else {
  25952. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  25953. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  25954. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  25955. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  25956. v( position2.x, position2.y, position2.z );
  25957. }
  25958. }
  25959. // Add stepped vertices...
  25960. // Including front facing vertices
  25961. for ( let s = 1; s <= steps; s ++ ) {
  25962. for ( let i = 0; i < vlen; i ++ ) {
  25963. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25964. if ( ! extrudeByPath ) {
  25965. v( vert.x, vert.y, depth / steps * s );
  25966. } else {
  25967. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  25968. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  25969. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  25970. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  25971. v( position2.x, position2.y, position2.z );
  25972. }
  25973. }
  25974. }
  25975. // Add bevel segments planes
  25976. //for ( b = 1; b <= bevelSegments; b ++ ) {
  25977. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  25978. const t = b / bevelSegments;
  25979. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25980. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25981. // contract shape
  25982. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25983. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25984. v( vert.x, vert.y, depth + z );
  25985. }
  25986. // expand holes
  25987. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25988. const ahole = holes[ h ];
  25989. oneHoleMovements = holesMovements[ h ];
  25990. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25991. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25992. if ( ! extrudeByPath ) {
  25993. v( vert.x, vert.y, depth + z );
  25994. } else {
  25995. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  25996. }
  25997. }
  25998. }
  25999. }
  26000. /* Faces */
  26001. // Top and bottom faces
  26002. buildLidFaces();
  26003. // Sides faces
  26004. buildSideFaces();
  26005. ///// Internal functions
  26006. function buildLidFaces() {
  26007. const start = verticesArray.length / 3;
  26008. if ( bevelEnabled ) {
  26009. let layer = 0; // steps + 1
  26010. let offset = vlen * layer;
  26011. // Bottom faces
  26012. for ( let i = 0; i < flen; i ++ ) {
  26013. const face = faces[ i ];
  26014. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  26015. }
  26016. layer = steps + bevelSegments * 2;
  26017. offset = vlen * layer;
  26018. // Top faces
  26019. for ( let i = 0; i < flen; i ++ ) {
  26020. const face = faces[ i ];
  26021. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  26022. }
  26023. } else {
  26024. // Bottom faces
  26025. for ( let i = 0; i < flen; i ++ ) {
  26026. const face = faces[ i ];
  26027. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  26028. }
  26029. // Top faces
  26030. for ( let i = 0; i < flen; i ++ ) {
  26031. const face = faces[ i ];
  26032. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  26033. }
  26034. }
  26035. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  26036. }
  26037. // Create faces for the z-sides of the shape
  26038. function buildSideFaces() {
  26039. const start = verticesArray.length / 3;
  26040. let layeroffset = 0;
  26041. sidewalls( contour, layeroffset );
  26042. layeroffset += contour.length;
  26043. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26044. const ahole = holes[ h ];
  26045. sidewalls( ahole, layeroffset );
  26046. //, true
  26047. layeroffset += ahole.length;
  26048. }
  26049. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  26050. }
  26051. function sidewalls( contour, layeroffset ) {
  26052. let i = contour.length;
  26053. while ( -- i >= 0 ) {
  26054. const j = i;
  26055. let k = i - 1;
  26056. if ( k < 0 ) k = contour.length - 1;
  26057. //console.log('b', i,j, i-1, k,vertices.length);
  26058. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  26059. const slen1 = vlen * s;
  26060. const slen2 = vlen * ( s + 1 );
  26061. const a = layeroffset + j + slen1,
  26062. b = layeroffset + k + slen1,
  26063. c = layeroffset + k + slen2,
  26064. d = layeroffset + j + slen2;
  26065. f4( a, b, c, d );
  26066. }
  26067. }
  26068. }
  26069. function v( x, y, z ) {
  26070. placeholder.push( x );
  26071. placeholder.push( y );
  26072. placeholder.push( z );
  26073. }
  26074. function f3( a, b, c ) {
  26075. addVertex( a );
  26076. addVertex( b );
  26077. addVertex( c );
  26078. const nextIndex = verticesArray.length / 3;
  26079. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26080. addUV( uvs[ 0 ] );
  26081. addUV( uvs[ 1 ] );
  26082. addUV( uvs[ 2 ] );
  26083. }
  26084. function f4( a, b, c, d ) {
  26085. addVertex( a );
  26086. addVertex( b );
  26087. addVertex( d );
  26088. addVertex( b );
  26089. addVertex( c );
  26090. addVertex( d );
  26091. const nextIndex = verticesArray.length / 3;
  26092. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26093. addUV( uvs[ 0 ] );
  26094. addUV( uvs[ 1 ] );
  26095. addUV( uvs[ 3 ] );
  26096. addUV( uvs[ 1 ] );
  26097. addUV( uvs[ 2 ] );
  26098. addUV( uvs[ 3 ] );
  26099. }
  26100. function addVertex( index ) {
  26101. verticesArray.push( placeholder[ index * 3 + 0 ] );
  26102. verticesArray.push( placeholder[ index * 3 + 1 ] );
  26103. verticesArray.push( placeholder[ index * 3 + 2 ] );
  26104. }
  26105. function addUV( vector2 ) {
  26106. uvArray.push( vector2.x );
  26107. uvArray.push( vector2.y );
  26108. }
  26109. }
  26110. }
  26111. copy( source ) {
  26112. super.copy( source );
  26113. this.parameters = Object.assign( {}, source.parameters );
  26114. return this;
  26115. }
  26116. toJSON() {
  26117. const data = super.toJSON();
  26118. const shapes = this.parameters.shapes;
  26119. const options = this.parameters.options;
  26120. return toJSON$1( shapes, options, data );
  26121. }
  26122. /**
  26123. * Factory method for creating an instance of this class from the given
  26124. * JSON object.
  26125. *
  26126. * @param {Object} data - A JSON object representing the serialized geometry.
  26127. * @param {Array<Shape>} shapes - An array of shapes.
  26128. * @return {ExtrudeGeometry} A new instance.
  26129. */
  26130. static fromJSON( data, shapes ) {
  26131. const geometryShapes = [];
  26132. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26133. const shape = shapes[ data.shapes[ j ] ];
  26134. geometryShapes.push( shape );
  26135. }
  26136. const extrudePath = data.options.extrudePath;
  26137. if ( extrudePath !== undefined ) {
  26138. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  26139. }
  26140. return new ExtrudeGeometry( geometryShapes, data.options );
  26141. }
  26142. }
  26143. const WorldUVGenerator = {
  26144. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  26145. const a_x = vertices[ indexA * 3 ];
  26146. const a_y = vertices[ indexA * 3 + 1 ];
  26147. const b_x = vertices[ indexB * 3 ];
  26148. const b_y = vertices[ indexB * 3 + 1 ];
  26149. const c_x = vertices[ indexC * 3 ];
  26150. const c_y = vertices[ indexC * 3 + 1 ];
  26151. return [
  26152. new Vector2( a_x, a_y ),
  26153. new Vector2( b_x, b_y ),
  26154. new Vector2( c_x, c_y )
  26155. ];
  26156. },
  26157. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  26158. const a_x = vertices[ indexA * 3 ];
  26159. const a_y = vertices[ indexA * 3 + 1 ];
  26160. const a_z = vertices[ indexA * 3 + 2 ];
  26161. const b_x = vertices[ indexB * 3 ];
  26162. const b_y = vertices[ indexB * 3 + 1 ];
  26163. const b_z = vertices[ indexB * 3 + 2 ];
  26164. const c_x = vertices[ indexC * 3 ];
  26165. const c_y = vertices[ indexC * 3 + 1 ];
  26166. const c_z = vertices[ indexC * 3 + 2 ];
  26167. const d_x = vertices[ indexD * 3 ];
  26168. const d_y = vertices[ indexD * 3 + 1 ];
  26169. const d_z = vertices[ indexD * 3 + 2 ];
  26170. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  26171. return [
  26172. new Vector2( a_x, 1 - a_z ),
  26173. new Vector2( b_x, 1 - b_z ),
  26174. new Vector2( c_x, 1 - c_z ),
  26175. new Vector2( d_x, 1 - d_z )
  26176. ];
  26177. } else {
  26178. return [
  26179. new Vector2( a_y, 1 - a_z ),
  26180. new Vector2( b_y, 1 - b_z ),
  26181. new Vector2( c_y, 1 - c_z ),
  26182. new Vector2( d_y, 1 - d_z )
  26183. ];
  26184. }
  26185. }
  26186. };
  26187. function toJSON$1( shapes, options, data ) {
  26188. data.shapes = [];
  26189. if ( Array.isArray( shapes ) ) {
  26190. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26191. const shape = shapes[ i ];
  26192. data.shapes.push( shape.uuid );
  26193. }
  26194. } else {
  26195. data.shapes.push( shapes.uuid );
  26196. }
  26197. data.options = Object.assign( {}, options );
  26198. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  26199. return data;
  26200. }
  26201. /**
  26202. * A geometry class for representing an icosahedron.
  26203. *
  26204. * ```js
  26205. * const geometry = new THREE.IcosahedronGeometry();
  26206. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26207. * const icosahedron = new THREE.Mesh( geometry, material );
  26208. * scene.add( icosahedron );
  26209. * ```
  26210. *
  26211. * @augments PolyhedronGeometry
  26212. */
  26213. class IcosahedronGeometry extends PolyhedronGeometry {
  26214. /**
  26215. * Constructs a new icosahedron geometry.
  26216. *
  26217. * @param {number} [radius=1] - Radius of the icosahedron.
  26218. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  26219. */
  26220. constructor( radius = 1, detail = 0 ) {
  26221. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  26222. const vertices = [
  26223. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  26224. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  26225. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  26226. ];
  26227. const indices = [
  26228. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  26229. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  26230. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  26231. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  26232. ];
  26233. super( vertices, indices, radius, detail );
  26234. this.type = 'IcosahedronGeometry';
  26235. /**
  26236. * Holds the constructor parameters that have been
  26237. * used to generate the geometry. Any modification
  26238. * after instantiation does not change the geometry.
  26239. *
  26240. * @type {Object}
  26241. */
  26242. this.parameters = {
  26243. radius: radius,
  26244. detail: detail
  26245. };
  26246. }
  26247. /**
  26248. * Factory method for creating an instance of this class from the given
  26249. * JSON object.
  26250. *
  26251. * @param {Object} data - A JSON object representing the serialized geometry.
  26252. * @return {IcosahedronGeometry} A new instance.
  26253. */
  26254. static fromJSON( data ) {
  26255. return new IcosahedronGeometry( data.radius, data.detail );
  26256. }
  26257. }
  26258. /**
  26259. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  26260. *
  26261. * ```js
  26262. * const points = [];
  26263. * for ( let i = 0; i < 10; i ++ ) {
  26264. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  26265. * }
  26266. * const geometry = new THREE.LatheGeometry( points );
  26267. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26268. * const lathe = new THREE.Mesh( geometry, material );
  26269. * scene.add( lathe );
  26270. * ```
  26271. *
  26272. * @augments BufferGeometry
  26273. */
  26274. class LatheGeometry extends BufferGeometry {
  26275. /**
  26276. * Constructs a new lathe geometry.
  26277. *
  26278. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  26279. * must be greater than zero.
  26280. * @param {number} [segments=12] - The number of circumference segments to generate.
  26281. * @param {number} [phiStart=0] - The starting angle in radians.
  26282. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  26283. * closed lathe, less than 2PI is a portion.
  26284. */
  26285. 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 ) {
  26286. super();
  26287. this.type = 'LatheGeometry';
  26288. /**
  26289. * Holds the constructor parameters that have been
  26290. * used to generate the geometry. Any modification
  26291. * after instantiation does not change the geometry.
  26292. *
  26293. * @type {Object}
  26294. */
  26295. this.parameters = {
  26296. points: points,
  26297. segments: segments,
  26298. phiStart: phiStart,
  26299. phiLength: phiLength
  26300. };
  26301. segments = Math.floor( segments );
  26302. // clamp phiLength so it's in range of [ 0, 2PI ]
  26303. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  26304. // buffers
  26305. const indices = [];
  26306. const vertices = [];
  26307. const uvs = [];
  26308. const initNormals = [];
  26309. const normals = [];
  26310. // helper variables
  26311. const inverseSegments = 1.0 / segments;
  26312. const vertex = new Vector3();
  26313. const uv = new Vector2();
  26314. const normal = new Vector3();
  26315. const curNormal = new Vector3();
  26316. const prevNormal = new Vector3();
  26317. let dx = 0;
  26318. let dy = 0;
  26319. // pre-compute normals for initial "meridian"
  26320. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26321. switch ( j ) {
  26322. case 0: // special handling for 1st vertex on path
  26323. dx = points[ j + 1 ].x - points[ j ].x;
  26324. dy = points[ j + 1 ].y - points[ j ].y;
  26325. normal.x = dy * 1.0;
  26326. normal.y = - dx;
  26327. normal.z = dy * 0.0;
  26328. prevNormal.copy( normal );
  26329. normal.normalize();
  26330. initNormals.push( normal.x, normal.y, normal.z );
  26331. break;
  26332. case ( points.length - 1 ): // special handling for last Vertex on path
  26333. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  26334. break;
  26335. default: // default handling for all vertices in between
  26336. dx = points[ j + 1 ].x - points[ j ].x;
  26337. dy = points[ j + 1 ].y - points[ j ].y;
  26338. normal.x = dy * 1.0;
  26339. normal.y = - dx;
  26340. normal.z = dy * 0.0;
  26341. curNormal.copy( normal );
  26342. normal.x += prevNormal.x;
  26343. normal.y += prevNormal.y;
  26344. normal.z += prevNormal.z;
  26345. normal.normalize();
  26346. initNormals.push( normal.x, normal.y, normal.z );
  26347. prevNormal.copy( curNormal );
  26348. }
  26349. }
  26350. // generate vertices, uvs and normals
  26351. for ( let i = 0; i <= segments; i ++ ) {
  26352. const phi = phiStart + i * inverseSegments * phiLength;
  26353. const sin = Math.sin( phi );
  26354. const cos = Math.cos( phi );
  26355. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26356. // vertex
  26357. vertex.x = points[ j ].x * sin;
  26358. vertex.y = points[ j ].y;
  26359. vertex.z = points[ j ].x * cos;
  26360. vertices.push( vertex.x, vertex.y, vertex.z );
  26361. // uv
  26362. uv.x = i / segments;
  26363. uv.y = j / ( points.length - 1 );
  26364. uvs.push( uv.x, uv.y );
  26365. // normal
  26366. const x = initNormals[ 3 * j + 0 ] * sin;
  26367. const y = initNormals[ 3 * j + 1 ];
  26368. const z = initNormals[ 3 * j + 0 ] * cos;
  26369. normals.push( x, y, z );
  26370. }
  26371. }
  26372. // indices
  26373. for ( let i = 0; i < segments; i ++ ) {
  26374. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  26375. const base = j + i * points.length;
  26376. const a = base;
  26377. const b = base + points.length;
  26378. const c = base + points.length + 1;
  26379. const d = base + 1;
  26380. // faces
  26381. indices.push( a, b, d );
  26382. indices.push( c, d, b );
  26383. }
  26384. }
  26385. // build geometry
  26386. this.setIndex( indices );
  26387. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26388. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26389. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26390. }
  26391. copy( source ) {
  26392. super.copy( source );
  26393. this.parameters = Object.assign( {}, source.parameters );
  26394. return this;
  26395. }
  26396. /**
  26397. * Factory method for creating an instance of this class from the given
  26398. * JSON object.
  26399. *
  26400. * @param {Object} data - A JSON object representing the serialized geometry.
  26401. * @return {LatheGeometry} A new instance.
  26402. */
  26403. static fromJSON( data ) {
  26404. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  26405. }
  26406. }
  26407. /**
  26408. * A geometry class for representing an octahedron.
  26409. *
  26410. * ```js
  26411. * const geometry = new THREE.OctahedronGeometry();
  26412. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26413. * const octahedron = new THREE.Mesh( geometry, material );
  26414. * scene.add( octahedron );
  26415. * ```
  26416. *
  26417. * @augments PolyhedronGeometry
  26418. */
  26419. class OctahedronGeometry extends PolyhedronGeometry {
  26420. /**
  26421. * Constructs a new octahedron geometry.
  26422. *
  26423. * @param {number} [radius=1] - Radius of the octahedron.
  26424. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  26425. */
  26426. constructor( radius = 1, detail = 0 ) {
  26427. const vertices = [
  26428. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  26429. 0, -1, 0, 0, 0, 1, 0, 0, -1
  26430. ];
  26431. const indices = [
  26432. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  26433. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  26434. 1, 3, 4, 1, 4, 2
  26435. ];
  26436. super( vertices, indices, radius, detail );
  26437. this.type = 'OctahedronGeometry';
  26438. /**
  26439. * Holds the constructor parameters that have been
  26440. * used to generate the geometry. Any modification
  26441. * after instantiation does not change the geometry.
  26442. *
  26443. * @type {Object}
  26444. */
  26445. this.parameters = {
  26446. radius: radius,
  26447. detail: detail
  26448. };
  26449. }
  26450. /**
  26451. * Factory method for creating an instance of this class from the given
  26452. * JSON object.
  26453. *
  26454. * @param {Object} data - A JSON object representing the serialized geometry.
  26455. * @return {OctahedronGeometry} A new instance.
  26456. */
  26457. static fromJSON( data ) {
  26458. return new OctahedronGeometry( data.radius, data.detail );
  26459. }
  26460. }
  26461. /**
  26462. * A geometry class for representing a plane.
  26463. *
  26464. * ```js
  26465. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  26466. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26467. * const plane = new THREE.Mesh( geometry, material );
  26468. * scene.add( plane );
  26469. * ```
  26470. *
  26471. * @augments BufferGeometry
  26472. */
  26473. class PlaneGeometry extends BufferGeometry {
  26474. /**
  26475. * Constructs a new plane geometry.
  26476. *
  26477. * @param {number} [width=1] - The width along the X axis.
  26478. * @param {number} [height=1] - The height along the Y axis
  26479. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  26480. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  26481. */
  26482. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  26483. super();
  26484. this.type = 'PlaneGeometry';
  26485. /**
  26486. * Holds the constructor parameters that have been
  26487. * used to generate the geometry. Any modification
  26488. * after instantiation does not change the geometry.
  26489. *
  26490. * @type {Object}
  26491. */
  26492. this.parameters = {
  26493. width: width,
  26494. height: height,
  26495. widthSegments: widthSegments,
  26496. heightSegments: heightSegments
  26497. };
  26498. const width_half = width / 2;
  26499. const height_half = height / 2;
  26500. const gridX = Math.floor( widthSegments );
  26501. const gridY = Math.floor( heightSegments );
  26502. const gridX1 = gridX + 1;
  26503. const gridY1 = gridY + 1;
  26504. const segment_width = width / gridX;
  26505. const segment_height = height / gridY;
  26506. //
  26507. const indices = [];
  26508. const vertices = [];
  26509. const normals = [];
  26510. const uvs = [];
  26511. for ( let iy = 0; iy < gridY1; iy ++ ) {
  26512. const y = iy * segment_height - height_half;
  26513. for ( let ix = 0; ix < gridX1; ix ++ ) {
  26514. const x = ix * segment_width - width_half;
  26515. vertices.push( x, - y, 0 );
  26516. normals.push( 0, 0, 1 );
  26517. uvs.push( ix / gridX );
  26518. uvs.push( 1 - ( iy / gridY ) );
  26519. }
  26520. }
  26521. for ( let iy = 0; iy < gridY; iy ++ ) {
  26522. for ( let ix = 0; ix < gridX; ix ++ ) {
  26523. const a = ix + gridX1 * iy;
  26524. const b = ix + gridX1 * ( iy + 1 );
  26525. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  26526. const d = ( ix + 1 ) + gridX1 * iy;
  26527. indices.push( a, b, d );
  26528. indices.push( b, c, d );
  26529. }
  26530. }
  26531. this.setIndex( indices );
  26532. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26533. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26534. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26535. }
  26536. copy( source ) {
  26537. super.copy( source );
  26538. this.parameters = Object.assign( {}, source.parameters );
  26539. return this;
  26540. }
  26541. /**
  26542. * Factory method for creating an instance of this class from the given
  26543. * JSON object.
  26544. *
  26545. * @param {Object} data - A JSON object representing the serialized geometry.
  26546. * @return {PlaneGeometry} A new instance.
  26547. */
  26548. static fromJSON( data ) {
  26549. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  26550. }
  26551. }
  26552. /**
  26553. * A class for generating a two-dimensional ring geometry.
  26554. *
  26555. * ```js
  26556. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  26557. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26558. * const mesh = new THREE.Mesh( geometry, material );
  26559. * scene.add( mesh );
  26560. * ```
  26561. *
  26562. * @augments BufferGeometry
  26563. */
  26564. class RingGeometry extends BufferGeometry {
  26565. /**
  26566. * Constructs a new ring geometry.
  26567. *
  26568. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  26569. * @param {number} [outerRadius=1] - The outer radius of the ring.
  26570. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  26571. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  26572. * @param {number} [thetaStart=0] - Starting angle in radians.
  26573. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  26574. */
  26575. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26576. super();
  26577. this.type = 'RingGeometry';
  26578. /**
  26579. * Holds the constructor parameters that have been
  26580. * used to generate the geometry. Any modification
  26581. * after instantiation does not change the geometry.
  26582. *
  26583. * @type {Object}
  26584. */
  26585. this.parameters = {
  26586. innerRadius: innerRadius,
  26587. outerRadius: outerRadius,
  26588. thetaSegments: thetaSegments,
  26589. phiSegments: phiSegments,
  26590. thetaStart: thetaStart,
  26591. thetaLength: thetaLength
  26592. };
  26593. thetaSegments = Math.max( 3, thetaSegments );
  26594. phiSegments = Math.max( 1, phiSegments );
  26595. // buffers
  26596. const indices = [];
  26597. const vertices = [];
  26598. const normals = [];
  26599. const uvs = [];
  26600. // some helper variables
  26601. let radius = innerRadius;
  26602. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  26603. const vertex = new Vector3();
  26604. const uv = new Vector2();
  26605. // generate vertices, normals and uvs
  26606. for ( let j = 0; j <= phiSegments; j ++ ) {
  26607. for ( let i = 0; i <= thetaSegments; i ++ ) {
  26608. // values are generate from the inside of the ring to the outside
  26609. const segment = thetaStart + i / thetaSegments * thetaLength;
  26610. // vertex
  26611. vertex.x = radius * Math.cos( segment );
  26612. vertex.y = radius * Math.sin( segment );
  26613. vertices.push( vertex.x, vertex.y, vertex.z );
  26614. // normal
  26615. normals.push( 0, 0, 1 );
  26616. // uv
  26617. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  26618. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  26619. uvs.push( uv.x, uv.y );
  26620. }
  26621. // increase the radius for next row of vertices
  26622. radius += radiusStep;
  26623. }
  26624. // indices
  26625. for ( let j = 0; j < phiSegments; j ++ ) {
  26626. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  26627. for ( let i = 0; i < thetaSegments; i ++ ) {
  26628. const segment = i + thetaSegmentLevel;
  26629. const a = segment;
  26630. const b = segment + thetaSegments + 1;
  26631. const c = segment + thetaSegments + 2;
  26632. const d = segment + 1;
  26633. // faces
  26634. indices.push( a, b, d );
  26635. indices.push( b, c, d );
  26636. }
  26637. }
  26638. // build geometry
  26639. this.setIndex( indices );
  26640. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26641. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26642. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26643. }
  26644. copy( source ) {
  26645. super.copy( source );
  26646. this.parameters = Object.assign( {}, source.parameters );
  26647. return this;
  26648. }
  26649. /**
  26650. * Factory method for creating an instance of this class from the given
  26651. * JSON object.
  26652. *
  26653. * @param {Object} data - A JSON object representing the serialized geometry.
  26654. * @return {RingGeometry} A new instance.
  26655. */
  26656. static fromJSON( data ) {
  26657. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  26658. }
  26659. }
  26660. /**
  26661. * Creates an one-sided polygonal geometry from one or more path shapes.
  26662. *
  26663. * ```js
  26664. * const arcShape = new THREE.Shape()
  26665. * .moveTo( 5, 1 )
  26666. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  26667. *
  26668. * const geometry = new THREE.ShapeGeometry( arcShape );
  26669. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  26670. * const mesh = new THREE.Mesh( geometry, material ) ;
  26671. * scene.add( mesh );
  26672. * ```
  26673. *
  26674. * @augments BufferGeometry
  26675. */
  26676. class ShapeGeometry extends BufferGeometry {
  26677. /**
  26678. * Constructs a new shape geometry.
  26679. *
  26680. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26681. * @param {number} [curveSegments=12] - Number of segments per shape.
  26682. */
  26683. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  26684. super();
  26685. this.type = 'ShapeGeometry';
  26686. /**
  26687. * Holds the constructor parameters that have been
  26688. * used to generate the geometry. Any modification
  26689. * after instantiation does not change the geometry.
  26690. *
  26691. * @type {Object}
  26692. */
  26693. this.parameters = {
  26694. shapes: shapes,
  26695. curveSegments: curveSegments
  26696. };
  26697. // buffers
  26698. const indices = [];
  26699. const vertices = [];
  26700. const normals = [];
  26701. const uvs = [];
  26702. // helper variables
  26703. let groupStart = 0;
  26704. let groupCount = 0;
  26705. // allow single and array values for "shapes" parameter
  26706. if ( Array.isArray( shapes ) === false ) {
  26707. addShape( shapes );
  26708. } else {
  26709. for ( let i = 0; i < shapes.length; i ++ ) {
  26710. addShape( shapes[ i ] );
  26711. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  26712. groupStart += groupCount;
  26713. groupCount = 0;
  26714. }
  26715. }
  26716. // build geometry
  26717. this.setIndex( indices );
  26718. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26719. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26720. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26721. // helper functions
  26722. function addShape( shape ) {
  26723. const indexOffset = vertices.length / 3;
  26724. const points = shape.extractPoints( curveSegments );
  26725. let shapeVertices = points.shape;
  26726. const shapeHoles = points.holes;
  26727. // check direction of vertices
  26728. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  26729. shapeVertices = shapeVertices.reverse();
  26730. }
  26731. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26732. const shapeHole = shapeHoles[ i ];
  26733. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  26734. shapeHoles[ i ] = shapeHole.reverse();
  26735. }
  26736. }
  26737. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  26738. // join vertices of inner and outer paths to a single array
  26739. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26740. const shapeHole = shapeHoles[ i ];
  26741. shapeVertices = shapeVertices.concat( shapeHole );
  26742. }
  26743. // vertices, normals, uvs
  26744. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  26745. const vertex = shapeVertices[ i ];
  26746. vertices.push( vertex.x, vertex.y, 0 );
  26747. normals.push( 0, 0, 1 );
  26748. uvs.push( vertex.x, vertex.y ); // world uvs
  26749. }
  26750. // indices
  26751. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  26752. const face = faces[ i ];
  26753. const a = face[ 0 ] + indexOffset;
  26754. const b = face[ 1 ] + indexOffset;
  26755. const c = face[ 2 ] + indexOffset;
  26756. indices.push( a, b, c );
  26757. groupCount += 3;
  26758. }
  26759. }
  26760. }
  26761. copy( source ) {
  26762. super.copy( source );
  26763. this.parameters = Object.assign( {}, source.parameters );
  26764. return this;
  26765. }
  26766. toJSON() {
  26767. const data = super.toJSON();
  26768. const shapes = this.parameters.shapes;
  26769. return toJSON( shapes, data );
  26770. }
  26771. /**
  26772. * Factory method for creating an instance of this class from the given
  26773. * JSON object.
  26774. *
  26775. * @param {Object} data - A JSON object representing the serialized geometry.
  26776. * @param {Array<Shape>} shapes - An array of shapes.
  26777. * @return {ShapeGeometry} A new instance.
  26778. */
  26779. static fromJSON( data, shapes ) {
  26780. const geometryShapes = [];
  26781. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26782. const shape = shapes[ data.shapes[ j ] ];
  26783. geometryShapes.push( shape );
  26784. }
  26785. return new ShapeGeometry( geometryShapes, data.curveSegments );
  26786. }
  26787. }
  26788. function toJSON( shapes, data ) {
  26789. data.shapes = [];
  26790. if ( Array.isArray( shapes ) ) {
  26791. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26792. const shape = shapes[ i ];
  26793. data.shapes.push( shape.uuid );
  26794. }
  26795. } else {
  26796. data.shapes.push( shapes.uuid );
  26797. }
  26798. return data;
  26799. }
  26800. /**
  26801. * A class for generating a sphere geometry.
  26802. *
  26803. * ```js
  26804. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  26805. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26806. * const sphere = new THREE.Mesh( geometry, material );
  26807. * scene.add( sphere );
  26808. * ```
  26809. *
  26810. * @augments BufferGeometry
  26811. */
  26812. class SphereGeometry extends BufferGeometry {
  26813. /**
  26814. * Constructs a new sphere geometry.
  26815. *
  26816. * @param {number} [radius=1] - The sphere radius.
  26817. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  26818. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  26819. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  26820. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  26821. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  26822. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  26823. */
  26824. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  26825. super();
  26826. this.type = 'SphereGeometry';
  26827. /**
  26828. * Holds the constructor parameters that have been
  26829. * used to generate the geometry. Any modification
  26830. * after instantiation does not change the geometry.
  26831. *
  26832. * @type {Object}
  26833. */
  26834. this.parameters = {
  26835. radius: radius,
  26836. widthSegments: widthSegments,
  26837. heightSegments: heightSegments,
  26838. phiStart: phiStart,
  26839. phiLength: phiLength,
  26840. thetaStart: thetaStart,
  26841. thetaLength: thetaLength
  26842. };
  26843. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  26844. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  26845. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  26846. let index = 0;
  26847. const grid = [];
  26848. const vertex = new Vector3();
  26849. const normal = new Vector3();
  26850. // buffers
  26851. const indices = [];
  26852. const vertices = [];
  26853. const normals = [];
  26854. const uvs = [];
  26855. // generate vertices, normals and uvs
  26856. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  26857. const verticesRow = [];
  26858. const v = iy / heightSegments;
  26859. // special case for the poles
  26860. let uOffset = 0;
  26861. if ( iy === 0 && thetaStart === 0 ) {
  26862. uOffset = 0.5 / widthSegments;
  26863. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  26864. uOffset = -0.5 / widthSegments;
  26865. }
  26866. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  26867. const u = ix / widthSegments;
  26868. // vertex
  26869. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26870. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  26871. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26872. vertices.push( vertex.x, vertex.y, vertex.z );
  26873. // normal
  26874. normal.copy( vertex ).normalize();
  26875. normals.push( normal.x, normal.y, normal.z );
  26876. // uv
  26877. uvs.push( u + uOffset, 1 - v );
  26878. verticesRow.push( index ++ );
  26879. }
  26880. grid.push( verticesRow );
  26881. }
  26882. // indices
  26883. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  26884. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  26885. const a = grid[ iy ][ ix + 1 ];
  26886. const b = grid[ iy ][ ix ];
  26887. const c = grid[ iy + 1 ][ ix ];
  26888. const d = grid[ iy + 1 ][ ix + 1 ];
  26889. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  26890. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  26891. }
  26892. }
  26893. // build geometry
  26894. this.setIndex( indices );
  26895. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26896. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26897. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26898. }
  26899. copy( source ) {
  26900. super.copy( source );
  26901. this.parameters = Object.assign( {}, source.parameters );
  26902. return this;
  26903. }
  26904. /**
  26905. * Factory method for creating an instance of this class from the given
  26906. * JSON object.
  26907. *
  26908. * @param {Object} data - A JSON object representing the serialized geometry.
  26909. * @return {SphereGeometry} A new instance.
  26910. */
  26911. static fromJSON( data ) {
  26912. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  26913. }
  26914. }
  26915. /**
  26916. * A geometry class for representing an tetrahedron.
  26917. *
  26918. * ```js
  26919. * const geometry = new THREE.TetrahedronGeometry();
  26920. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26921. * const tetrahedron = new THREE.Mesh( geometry, material );
  26922. * scene.add( tetrahedron );
  26923. * ```
  26924. *
  26925. * @augments PolyhedronGeometry
  26926. */
  26927. class TetrahedronGeometry extends PolyhedronGeometry {
  26928. /**
  26929. * Constructs a new tetrahedron geometry.
  26930. *
  26931. * @param {number} [radius=1] - Radius of the tetrahedron.
  26932. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  26933. */
  26934. constructor( radius = 1, detail = 0 ) {
  26935. const vertices = [
  26936. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  26937. ];
  26938. const indices = [
  26939. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  26940. ];
  26941. super( vertices, indices, radius, detail );
  26942. this.type = 'TetrahedronGeometry';
  26943. /**
  26944. * Holds the constructor parameters that have been
  26945. * used to generate the geometry. Any modification
  26946. * after instantiation does not change the geometry.
  26947. *
  26948. * @type {Object}
  26949. */
  26950. this.parameters = {
  26951. radius: radius,
  26952. detail: detail
  26953. };
  26954. }
  26955. /**
  26956. * Factory method for creating an instance of this class from the given
  26957. * JSON object.
  26958. *
  26959. * @param {Object} data - A JSON object representing the serialized geometry.
  26960. * @return {TetrahedronGeometry} A new instance.
  26961. */
  26962. static fromJSON( data ) {
  26963. return new TetrahedronGeometry( data.radius, data.detail );
  26964. }
  26965. }
  26966. /**
  26967. * A geometry class for representing an torus.
  26968. *
  26969. * ```js
  26970. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  26971. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26972. * const torus = new THREE.Mesh( geometry, material );
  26973. * scene.add( torus );
  26974. * ```
  26975. *
  26976. * @augments BufferGeometry
  26977. */
  26978. class TorusGeometry extends BufferGeometry {
  26979. /**
  26980. * Constructs a new torus geometry.
  26981. *
  26982. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  26983. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  26984. * @param {number} [radialSegments=12] - The number of radial segments.
  26985. * @param {number} [tubularSegments=48] - The number of tubular segments.
  26986. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  26987. */
  26988. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  26989. super();
  26990. this.type = 'TorusGeometry';
  26991. /**
  26992. * Holds the constructor parameters that have been
  26993. * used to generate the geometry. Any modification
  26994. * after instantiation does not change the geometry.
  26995. *
  26996. * @type {Object}
  26997. */
  26998. this.parameters = {
  26999. radius: radius,
  27000. tube: tube,
  27001. radialSegments: radialSegments,
  27002. tubularSegments: tubularSegments,
  27003. arc: arc
  27004. };
  27005. radialSegments = Math.floor( radialSegments );
  27006. tubularSegments = Math.floor( tubularSegments );
  27007. // buffers
  27008. const indices = [];
  27009. const vertices = [];
  27010. const normals = [];
  27011. const uvs = [];
  27012. // helper variables
  27013. const center = new Vector3();
  27014. const vertex = new Vector3();
  27015. const normal = new Vector3();
  27016. // generate vertices, normals and uvs
  27017. for ( let j = 0; j <= radialSegments; j ++ ) {
  27018. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27019. const u = i / tubularSegments * arc;
  27020. const v = j / radialSegments * Math.PI * 2;
  27021. // vertex
  27022. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  27023. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  27024. vertex.z = tube * Math.sin( v );
  27025. vertices.push( vertex.x, vertex.y, vertex.z );
  27026. // normal
  27027. center.x = radius * Math.cos( u );
  27028. center.y = radius * Math.sin( u );
  27029. normal.subVectors( vertex, center ).normalize();
  27030. normals.push( normal.x, normal.y, normal.z );
  27031. // uv
  27032. uvs.push( i / tubularSegments );
  27033. uvs.push( j / radialSegments );
  27034. }
  27035. }
  27036. // generate indices
  27037. for ( let j = 1; j <= radialSegments; j ++ ) {
  27038. for ( let i = 1; i <= tubularSegments; i ++ ) {
  27039. // indices
  27040. const a = ( tubularSegments + 1 ) * j + i - 1;
  27041. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  27042. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  27043. const d = ( tubularSegments + 1 ) * j + i;
  27044. // faces
  27045. indices.push( a, b, d );
  27046. indices.push( b, c, d );
  27047. }
  27048. }
  27049. // build geometry
  27050. this.setIndex( indices );
  27051. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27052. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27053. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27054. }
  27055. copy( source ) {
  27056. super.copy( source );
  27057. this.parameters = Object.assign( {}, source.parameters );
  27058. return this;
  27059. }
  27060. /**
  27061. * Factory method for creating an instance of this class from the given
  27062. * JSON object.
  27063. *
  27064. * @param {Object} data - A JSON object representing the serialized geometry.
  27065. * @return {TorusGeometry} A new instance.
  27066. */
  27067. static fromJSON( data ) {
  27068. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  27069. }
  27070. }
  27071. /**
  27072. * Creates a torus knot, the particular shape of which is defined by a pair
  27073. * of coprime integers, p and q. If p and q are not coprime, the result will
  27074. * be a torus link.
  27075. *
  27076. * ```js
  27077. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  27078. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27079. * const torusKnot = new THREE.Mesh( geometry, material );
  27080. * scene.add( torusKnot );
  27081. * ```
  27082. *
  27083. * @augments BufferGeometry
  27084. */
  27085. class TorusKnotGeometry extends BufferGeometry {
  27086. /**
  27087. * Constructs a new torus knot geometry.
  27088. *
  27089. * @param {number} [radius=1] - Radius of the torus knot.
  27090. * @param {number} [tube=0.4] - Radius of the tube.
  27091. * @param {number} [tubularSegments=64] - The number of tubular segments.
  27092. * @param {number} [radialSegments=8] - The number of radial segments.
  27093. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  27094. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  27095. */
  27096. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  27097. super();
  27098. this.type = 'TorusKnotGeometry';
  27099. /**
  27100. * Holds the constructor parameters that have been
  27101. * used to generate the geometry. Any modification
  27102. * after instantiation does not change the geometry.
  27103. *
  27104. * @type {Object}
  27105. */
  27106. this.parameters = {
  27107. radius: radius,
  27108. tube: tube,
  27109. tubularSegments: tubularSegments,
  27110. radialSegments: radialSegments,
  27111. p: p,
  27112. q: q
  27113. };
  27114. tubularSegments = Math.floor( tubularSegments );
  27115. radialSegments = Math.floor( radialSegments );
  27116. // buffers
  27117. const indices = [];
  27118. const vertices = [];
  27119. const normals = [];
  27120. const uvs = [];
  27121. // helper variables
  27122. const vertex = new Vector3();
  27123. const normal = new Vector3();
  27124. const P1 = new Vector3();
  27125. const P2 = new Vector3();
  27126. const B = new Vector3();
  27127. const T = new Vector3();
  27128. const N = new Vector3();
  27129. // generate vertices, normals and uvs
  27130. for ( let i = 0; i <= tubularSegments; ++ i ) {
  27131. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  27132. const u = i / tubularSegments * p * Math.PI * 2;
  27133. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  27134. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  27135. calculatePositionOnCurve( u, p, q, radius, P1 );
  27136. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  27137. // calculate orthonormal basis
  27138. T.subVectors( P2, P1 );
  27139. N.addVectors( P2, P1 );
  27140. B.crossVectors( T, N );
  27141. N.crossVectors( B, T );
  27142. // normalize B, N. T can be ignored, we don't use it
  27143. B.normalize();
  27144. N.normalize();
  27145. for ( let j = 0; j <= radialSegments; ++ j ) {
  27146. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  27147. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  27148. const v = j / radialSegments * Math.PI * 2;
  27149. const cx = - tube * Math.cos( v );
  27150. const cy = tube * Math.sin( v );
  27151. // now calculate the final vertex position.
  27152. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  27153. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  27154. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  27155. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  27156. vertices.push( vertex.x, vertex.y, vertex.z );
  27157. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  27158. normal.subVectors( vertex, P1 ).normalize();
  27159. normals.push( normal.x, normal.y, normal.z );
  27160. // uv
  27161. uvs.push( i / tubularSegments );
  27162. uvs.push( j / radialSegments );
  27163. }
  27164. }
  27165. // generate indices
  27166. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27167. for ( let i = 1; i <= radialSegments; i ++ ) {
  27168. // indices
  27169. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27170. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27171. const c = ( radialSegments + 1 ) * j + i;
  27172. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27173. // faces
  27174. indices.push( a, b, d );
  27175. indices.push( b, c, d );
  27176. }
  27177. }
  27178. // build geometry
  27179. this.setIndex( indices );
  27180. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27181. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27182. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27183. // this function calculates the current position on the torus curve
  27184. function calculatePositionOnCurve( u, p, q, radius, position ) {
  27185. const cu = Math.cos( u );
  27186. const su = Math.sin( u );
  27187. const quOverP = q / p * u;
  27188. const cs = Math.cos( quOverP );
  27189. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  27190. position.y = radius * ( 2 + cs ) * su * 0.5;
  27191. position.z = radius * Math.sin( quOverP ) * 0.5;
  27192. }
  27193. }
  27194. copy( source ) {
  27195. super.copy( source );
  27196. this.parameters = Object.assign( {}, source.parameters );
  27197. return this;
  27198. }
  27199. /**
  27200. * Factory method for creating an instance of this class from the given
  27201. * JSON object.
  27202. *
  27203. * @param {Object} data - A JSON object representing the serialized geometry.
  27204. * @return {TorusKnotGeometry} A new instance.
  27205. */
  27206. static fromJSON( data ) {
  27207. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  27208. }
  27209. }
  27210. /**
  27211. * Creates a tube that extrudes along a 3D curve.
  27212. *
  27213. * ```js
  27214. * class CustomSinCurve extends THREE.Curve {
  27215. *
  27216. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  27217. *
  27218. * const tx = t * 3 - 1.5;
  27219. * const ty = Math.sin( 2 * Math.PI * t );
  27220. * const tz = 0;
  27221. *
  27222. * return optionalTarget.set( tx, ty, tz );
  27223. * }
  27224. *
  27225. * }
  27226. *
  27227. * const path = new CustomSinCurve( 10 );
  27228. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  27229. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  27230. * const mesh = new THREE.Mesh( geometry, material );
  27231. * scene.add( mesh );
  27232. * ```
  27233. *
  27234. * @augments BufferGeometry
  27235. */
  27236. class TubeGeometry extends BufferGeometry {
  27237. /**
  27238. * Constructs a new tube geometry.
  27239. *
  27240. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  27241. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  27242. * @param {number} [radius=1] -The radius of the tube.
  27243. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  27244. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  27245. */
  27246. 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 ) {
  27247. super();
  27248. this.type = 'TubeGeometry';
  27249. /**
  27250. * Holds the constructor parameters that have been
  27251. * used to generate the geometry. Any modification
  27252. * after instantiation does not change the geometry.
  27253. *
  27254. * @type {Object}
  27255. */
  27256. this.parameters = {
  27257. path: path,
  27258. tubularSegments: tubularSegments,
  27259. radius: radius,
  27260. radialSegments: radialSegments,
  27261. closed: closed
  27262. };
  27263. const frames = path.computeFrenetFrames( tubularSegments, closed );
  27264. // expose internals
  27265. this.tangents = frames.tangents;
  27266. this.normals = frames.normals;
  27267. this.binormals = frames.binormals;
  27268. // helper variables
  27269. const vertex = new Vector3();
  27270. const normal = new Vector3();
  27271. const uv = new Vector2();
  27272. let P = new Vector3();
  27273. // buffer
  27274. const vertices = [];
  27275. const normals = [];
  27276. const uvs = [];
  27277. const indices = [];
  27278. // create buffer data
  27279. generateBufferData();
  27280. // build geometry
  27281. this.setIndex( indices );
  27282. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27283. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27284. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27285. // functions
  27286. function generateBufferData() {
  27287. for ( let i = 0; i < tubularSegments; i ++ ) {
  27288. generateSegment( i );
  27289. }
  27290. // if the geometry is not closed, generate the last row of vertices and normals
  27291. // at the regular position on the given path
  27292. //
  27293. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  27294. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  27295. // uvs are generated in a separate function.
  27296. // this makes it easy compute correct values for closed geometries
  27297. generateUVs();
  27298. // finally create faces
  27299. generateIndices();
  27300. }
  27301. function generateSegment( i ) {
  27302. // we use getPointAt to sample evenly distributed points from the given path
  27303. P = path.getPointAt( i / tubularSegments, P );
  27304. // retrieve corresponding normal and binormal
  27305. const N = frames.normals[ i ];
  27306. const B = frames.binormals[ i ];
  27307. // generate normals and vertices for the current segment
  27308. for ( let j = 0; j <= radialSegments; j ++ ) {
  27309. const v = j / radialSegments * Math.PI * 2;
  27310. const sin = Math.sin( v );
  27311. const cos = - Math.cos( v );
  27312. // normal
  27313. normal.x = ( cos * N.x + sin * B.x );
  27314. normal.y = ( cos * N.y + sin * B.y );
  27315. normal.z = ( cos * N.z + sin * B.z );
  27316. normal.normalize();
  27317. normals.push( normal.x, normal.y, normal.z );
  27318. // vertex
  27319. vertex.x = P.x + radius * normal.x;
  27320. vertex.y = P.y + radius * normal.y;
  27321. vertex.z = P.z + radius * normal.z;
  27322. vertices.push( vertex.x, vertex.y, vertex.z );
  27323. }
  27324. }
  27325. function generateIndices() {
  27326. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27327. for ( let i = 1; i <= radialSegments; i ++ ) {
  27328. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27329. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27330. const c = ( radialSegments + 1 ) * j + i;
  27331. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27332. // faces
  27333. indices.push( a, b, d );
  27334. indices.push( b, c, d );
  27335. }
  27336. }
  27337. }
  27338. function generateUVs() {
  27339. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27340. for ( let j = 0; j <= radialSegments; j ++ ) {
  27341. uv.x = i / tubularSegments;
  27342. uv.y = j / radialSegments;
  27343. uvs.push( uv.x, uv.y );
  27344. }
  27345. }
  27346. }
  27347. }
  27348. copy( source ) {
  27349. super.copy( source );
  27350. this.parameters = Object.assign( {}, source.parameters );
  27351. return this;
  27352. }
  27353. toJSON() {
  27354. const data = super.toJSON();
  27355. data.path = this.parameters.path.toJSON();
  27356. return data;
  27357. }
  27358. /**
  27359. * Factory method for creating an instance of this class from the given
  27360. * JSON object.
  27361. *
  27362. * @param {Object} data - A JSON object representing the serialized geometry.
  27363. * @return {TubeGeometry} A new instance.
  27364. */
  27365. static fromJSON( data ) {
  27366. // This only works for built-in curves (e.g. CatmullRomCurve3).
  27367. // User defined curves or instances of CurvePath will not be deserialized.
  27368. return new TubeGeometry(
  27369. new Curves[ data.path.type ]().fromJSON( data.path ),
  27370. data.tubularSegments,
  27371. data.radius,
  27372. data.radialSegments,
  27373. data.closed
  27374. );
  27375. }
  27376. }
  27377. /**
  27378. * Can be used as a helper object to visualize a geometry as a wireframe.
  27379. *
  27380. * ```js
  27381. * const geometry = new THREE.SphereGeometry();
  27382. *
  27383. * const wireframe = new THREE.WireframeGeometry( geometry );
  27384. *
  27385. * const line = new THREE.LineSegments( wireframe );
  27386. * line.material.depthWrite = false;
  27387. * line.material.opacity = 0.25;
  27388. * line.material.transparent = true;
  27389. *
  27390. * scene.add( line );
  27391. * ```
  27392. *
  27393. * Note: It is not yet possible to serialize/deserialize instances of this class.
  27394. *
  27395. * @augments BufferGeometry
  27396. */
  27397. class WireframeGeometry extends BufferGeometry {
  27398. /**
  27399. * Constructs a new wireframe geometry.
  27400. *
  27401. * @param {?BufferGeometry} [geometry=null] - The geometry.
  27402. */
  27403. constructor( geometry = null ) {
  27404. super();
  27405. this.type = 'WireframeGeometry';
  27406. /**
  27407. * Holds the constructor parameters that have been
  27408. * used to generate the geometry. Any modification
  27409. * after instantiation does not change the geometry.
  27410. *
  27411. * @type {Object}
  27412. */
  27413. this.parameters = {
  27414. geometry: geometry
  27415. };
  27416. if ( geometry !== null ) {
  27417. // buffer
  27418. const vertices = [];
  27419. const edges = new Set();
  27420. // helper variables
  27421. const start = new Vector3();
  27422. const end = new Vector3();
  27423. if ( geometry.index !== null ) {
  27424. // indexed BufferGeometry
  27425. const position = geometry.attributes.position;
  27426. const indices = geometry.index;
  27427. let groups = geometry.groups;
  27428. if ( groups.length === 0 ) {
  27429. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  27430. }
  27431. // create a data structure that contains all edges without duplicates
  27432. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  27433. const group = groups[ o ];
  27434. const groupStart = group.start;
  27435. const groupCount = group.count;
  27436. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  27437. for ( let j = 0; j < 3; j ++ ) {
  27438. const index1 = indices.getX( i + j );
  27439. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  27440. start.fromBufferAttribute( position, index1 );
  27441. end.fromBufferAttribute( position, index2 );
  27442. if ( isUniqueEdge( start, end, edges ) === true ) {
  27443. vertices.push( start.x, start.y, start.z );
  27444. vertices.push( end.x, end.y, end.z );
  27445. }
  27446. }
  27447. }
  27448. }
  27449. } else {
  27450. // non-indexed BufferGeometry
  27451. const position = geometry.attributes.position;
  27452. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  27453. for ( let j = 0; j < 3; j ++ ) {
  27454. // three edges per triangle, an edge is represented as (index1, index2)
  27455. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  27456. const index1 = 3 * i + j;
  27457. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  27458. start.fromBufferAttribute( position, index1 );
  27459. end.fromBufferAttribute( position, index2 );
  27460. if ( isUniqueEdge( start, end, edges ) === true ) {
  27461. vertices.push( start.x, start.y, start.z );
  27462. vertices.push( end.x, end.y, end.z );
  27463. }
  27464. }
  27465. }
  27466. }
  27467. // build geometry
  27468. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27469. }
  27470. }
  27471. copy( source ) {
  27472. super.copy( source );
  27473. this.parameters = Object.assign( {}, source.parameters );
  27474. return this;
  27475. }
  27476. }
  27477. function isUniqueEdge( start, end, edges ) {
  27478. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  27479. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  27480. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  27481. return false;
  27482. } else {
  27483. edges.add( hash1 );
  27484. edges.add( hash2 );
  27485. return true;
  27486. }
  27487. }
  27488. var Geometries = /*#__PURE__*/Object.freeze({
  27489. __proto__: null,
  27490. BoxGeometry: BoxGeometry,
  27491. CapsuleGeometry: CapsuleGeometry,
  27492. CircleGeometry: CircleGeometry,
  27493. ConeGeometry: ConeGeometry,
  27494. CylinderGeometry: CylinderGeometry,
  27495. DodecahedronGeometry: DodecahedronGeometry,
  27496. EdgesGeometry: EdgesGeometry,
  27497. ExtrudeGeometry: ExtrudeGeometry,
  27498. IcosahedronGeometry: IcosahedronGeometry,
  27499. LatheGeometry: LatheGeometry,
  27500. OctahedronGeometry: OctahedronGeometry,
  27501. PlaneGeometry: PlaneGeometry,
  27502. PolyhedronGeometry: PolyhedronGeometry,
  27503. RingGeometry: RingGeometry,
  27504. ShapeGeometry: ShapeGeometry,
  27505. SphereGeometry: SphereGeometry,
  27506. TetrahedronGeometry: TetrahedronGeometry,
  27507. TorusGeometry: TorusGeometry,
  27508. TorusKnotGeometry: TorusKnotGeometry,
  27509. TubeGeometry: TubeGeometry,
  27510. WireframeGeometry: WireframeGeometry
  27511. });
  27512. /**
  27513. * This material can receive shadows, but otherwise is completely transparent.
  27514. *
  27515. * ```js
  27516. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  27517. * geometry.rotateX( - Math.PI / 2 );
  27518. *
  27519. * const material = new THREE.ShadowMaterial();
  27520. * material.opacity = 0.2;
  27521. *
  27522. * const plane = new THREE.Mesh( geometry, material );
  27523. * plane.position.y = -200;
  27524. * plane.receiveShadow = true;
  27525. * scene.add( plane );
  27526. * ```
  27527. *
  27528. * @augments Material
  27529. */
  27530. class ShadowMaterial extends Material {
  27531. /**
  27532. * Constructs a new shadow material.
  27533. *
  27534. * @param {Object} [parameters] - An object with one or more properties
  27535. * defining the material's appearance. Any property of the material
  27536. * (including any property from inherited materials) can be passed
  27537. * in here. Color values can be passed any type of value accepted
  27538. * by {@link Color#set}.
  27539. */
  27540. constructor( parameters ) {
  27541. super();
  27542. /**
  27543. * This flag can be used for type testing.
  27544. *
  27545. * @type {boolean}
  27546. * @readonly
  27547. * @default true
  27548. */
  27549. this.isShadowMaterial = true;
  27550. this.type = 'ShadowMaterial';
  27551. /**
  27552. * Color of the material.
  27553. *
  27554. * @type {Color}
  27555. * @default (0,0,0)
  27556. */
  27557. this.color = new Color( 0x000000 );
  27558. /**
  27559. * Overwritten since shadow materials are transparent
  27560. * by default.
  27561. *
  27562. * @type {boolean}
  27563. * @default true
  27564. */
  27565. this.transparent = true;
  27566. /**
  27567. * Whether the material is affected by fog or not.
  27568. *
  27569. * @type {boolean}
  27570. * @default true
  27571. */
  27572. this.fog = true;
  27573. this.setValues( parameters );
  27574. }
  27575. copy( source ) {
  27576. super.copy( source );
  27577. this.color.copy( source.color );
  27578. this.fog = source.fog;
  27579. return this;
  27580. }
  27581. }
  27582. /**
  27583. * This class works just like {@link ShaderMaterial}, except that definitions
  27584. * of built-in uniforms and attributes are not automatically prepended to the
  27585. * GLSL shader code.
  27586. *
  27587. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  27588. *
  27589. * @augments ShaderMaterial
  27590. */
  27591. class RawShaderMaterial extends ShaderMaterial {
  27592. /**
  27593. * Constructs a new raw shader material.
  27594. *
  27595. * @param {Object} [parameters] - An object with one or more properties
  27596. * defining the material's appearance. Any property of the material
  27597. * (including any property from inherited materials) can be passed
  27598. * in here. Color values can be passed any type of value accepted
  27599. * by {@link Color#set}.
  27600. */
  27601. constructor( parameters ) {
  27602. super( parameters );
  27603. /**
  27604. * This flag can be used for type testing.
  27605. *
  27606. * @type {boolean}
  27607. * @readonly
  27608. * @default true
  27609. */
  27610. this.isRawShaderMaterial = true;
  27611. this.type = 'RawShaderMaterial';
  27612. }
  27613. }
  27614. /**
  27615. * A standard physically based material, using Metallic-Roughness workflow.
  27616. *
  27617. * Physically based rendering (PBR) has recently become the standard in many
  27618. * 3D applications, such as [Unity]{@link https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/},
  27619. * [Unreal]{@link https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/} and
  27620. * [3D Studio Max]{@link http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017}.
  27621. *
  27622. * This approach differs from older approaches in that instead of using
  27623. * approximations for the way in which light interacts with a surface, a
  27624. * physically correct model is used. The idea is that, instead of tweaking
  27625. * materials to look good under specific lighting, a material can be created
  27626. * that will react 'correctly' under all lighting scenarios.
  27627. *
  27628. * In practice this gives a more accurate and realistic looking result than
  27629. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  27630. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  27631. * shading.
  27632. *
  27633. * Note that for best results you should always specify an environment map when using this material.
  27634. *
  27635. * For a non-technical introduction to the concept of PBR and how to set up a
  27636. * PBR material, check out these articles by the people at [marmoset]{@link https://www.marmoset.co}:
  27637. *
  27638. * - [Basic Theory of Physically Based Rendering]{@link https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/}
  27639. * - [Physically Based Rendering and You Can Too]{@link https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/}
  27640. *
  27641. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  27642. * [paper from Disney]{@link https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf}
  27643. * (pdf), by Brent Burley.
  27644. *
  27645. * @augments Material
  27646. */
  27647. class MeshStandardMaterial extends Material {
  27648. /**
  27649. * Constructs a new mesh standard material.
  27650. *
  27651. * @param {Object} [parameters] - An object with one or more properties
  27652. * defining the material's appearance. Any property of the material
  27653. * (including any property from inherited materials) can be passed
  27654. * in here. Color values can be passed any type of value accepted
  27655. * by {@link Color#set}.
  27656. */
  27657. constructor( parameters ) {
  27658. super();
  27659. /**
  27660. * This flag can be used for type testing.
  27661. *
  27662. * @type {boolean}
  27663. * @readonly
  27664. * @default true
  27665. */
  27666. this.isMeshStandardMaterial = true;
  27667. this.type = 'MeshStandardMaterial';
  27668. this.defines = { 'STANDARD': '' };
  27669. /**
  27670. * Color of the material.
  27671. *
  27672. * @type {Color}
  27673. * @default (1,1,1)
  27674. */
  27675. this.color = new Color( 0xffffff ); // diffuse
  27676. /**
  27677. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  27678. * means fully diffuse. If `roughnessMap` is also provided,
  27679. * both values are multiplied.
  27680. *
  27681. * @type {number}
  27682. * @default 1
  27683. */
  27684. this.roughness = 1.0;
  27685. /**
  27686. * How much the material is like a metal. Non-metallic materials such as wood
  27687. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  27688. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  27689. * If `metalnessMap` is also provided, both values are multiplied.
  27690. *
  27691. * @type {number}
  27692. * @default 0
  27693. */
  27694. this.metalness = 0.0;
  27695. /**
  27696. * The color map. May optionally include an alpha channel, typically combined
  27697. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27698. * color is modulated by the diffuse `color`.
  27699. *
  27700. * @type {?Texture}
  27701. * @default null
  27702. */
  27703. this.map = null;
  27704. /**
  27705. * The light map. Requires a second set of UVs.
  27706. *
  27707. * @type {?Texture}
  27708. * @default null
  27709. */
  27710. this.lightMap = null;
  27711. /**
  27712. * Intensity of the baked light.
  27713. *
  27714. * @type {number}
  27715. * @default 1
  27716. */
  27717. this.lightMapIntensity = 1.0;
  27718. /**
  27719. * The red channel of this texture is used as the ambient occlusion map.
  27720. * Requires a second set of UVs.
  27721. *
  27722. * @type {?Texture}
  27723. * @default null
  27724. */
  27725. this.aoMap = null;
  27726. /**
  27727. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  27728. * disables ambient occlusion. Where intensity is `1` and the AO map's
  27729. * red channel is also `1`, ambient light is fully occluded on a surface.
  27730. *
  27731. * @type {number}
  27732. * @default 1
  27733. */
  27734. this.aoMapIntensity = 1.0;
  27735. /**
  27736. * Emissive (light) color of the material, essentially a solid color
  27737. * unaffected by other lighting.
  27738. *
  27739. * @type {Color}
  27740. * @default (0,0,0)
  27741. */
  27742. this.emissive = new Color( 0x000000 );
  27743. /**
  27744. * Intensity of the emissive light. Modulates the emissive color.
  27745. *
  27746. * @type {number}
  27747. * @default 1
  27748. */
  27749. this.emissiveIntensity = 1.0;
  27750. /**
  27751. * Set emissive (glow) map. The emissive map color is modulated by the
  27752. * emissive color and the emissive intensity. If you have an emissive map,
  27753. * be sure to set the emissive color to something other than black.
  27754. *
  27755. * @type {?Texture}
  27756. * @default null
  27757. */
  27758. this.emissiveMap = null;
  27759. /**
  27760. * The texture to create a bump map. The black and white values map to the
  27761. * perceived depth in relation to the lights. Bump doesn't actually affect
  27762. * the geometry of the object, only the lighting. If a normal map is defined
  27763. * this will be ignored.
  27764. *
  27765. * @type {?Texture}
  27766. * @default null
  27767. */
  27768. this.bumpMap = null;
  27769. /**
  27770. * How much the bump map affects the material. Typical range is `[0,1]`.
  27771. *
  27772. * @type {number}
  27773. * @default 1
  27774. */
  27775. this.bumpScale = 1;
  27776. /**
  27777. * The texture to create a normal map. The RGB values affect the surface
  27778. * normal for each pixel fragment and change the way the color is lit. Normal
  27779. * maps do not change the actual shape of the surface, only the lighting. In
  27780. * case the material has a normal map authored using the left handed
  27781. * convention, the `y` component of `normalScale` should be negated to compensate
  27782. * for the different handedness.
  27783. *
  27784. * @type {?Texture}
  27785. * @default null
  27786. */
  27787. this.normalMap = null;
  27788. /**
  27789. * The type of normal map.
  27790. *
  27791. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  27792. * @default TangentSpaceNormalMap
  27793. */
  27794. this.normalMapType = TangentSpaceNormalMap;
  27795. /**
  27796. * How much the normal map affects the material. Typical value range is `[0,1]`.
  27797. *
  27798. * @type {Vector2}
  27799. * @default (1,1)
  27800. */
  27801. this.normalScale = new Vector2( 1, 1 );
  27802. /**
  27803. * The displacement map affects the position of the mesh's vertices. Unlike
  27804. * other maps which only affect the light and shade of the material the
  27805. * displaced vertices can cast shadows, block other objects, and otherwise
  27806. * act as real geometry. The displacement texture is an image where the value
  27807. * of each pixel (white being the highest) is mapped against, and
  27808. * repositions, the vertices of the mesh.
  27809. *
  27810. * @type {?Texture}
  27811. * @default null
  27812. */
  27813. this.displacementMap = null;
  27814. /**
  27815. * How much the displacement map affects the mesh (where black is no
  27816. * displacement, and white is maximum displacement). Without a displacement
  27817. * map set, this value is not applied.
  27818. *
  27819. * @type {number}
  27820. * @default 0
  27821. */
  27822. this.displacementScale = 1;
  27823. /**
  27824. * The offset of the displacement map's values on the mesh's vertices.
  27825. * The bias is added to the scaled sample of the displacement map.
  27826. * Without a displacement map set, this value is not applied.
  27827. *
  27828. * @type {number}
  27829. * @default 0
  27830. */
  27831. this.displacementBias = 0;
  27832. /**
  27833. * The green channel of this texture is used to alter the roughness of the
  27834. * material.
  27835. *
  27836. * @type {?Texture}
  27837. * @default null
  27838. */
  27839. this.roughnessMap = null;
  27840. /**
  27841. * The blue channel of this texture is used to alter the metalness of the
  27842. * material.
  27843. *
  27844. * @type {?Texture}
  27845. * @default null
  27846. */
  27847. this.metalnessMap = null;
  27848. /**
  27849. * The alpha map is a grayscale texture that controls the opacity across the
  27850. * surface (black: fully transparent; white: fully opaque).
  27851. *
  27852. * Only the color of the texture is used, ignoring the alpha channel if one
  27853. * exists. For RGB and RGBA textures, the renderer will use the green channel
  27854. * when sampling this texture due to the extra bit of precision provided for
  27855. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  27856. * luminance/alpha textures will also still work as expected.
  27857. *
  27858. * @type {?Texture}
  27859. * @default null
  27860. */
  27861. this.alphaMap = null;
  27862. /**
  27863. * The environment map. To ensure a physically correct rendering, environment maps
  27864. * are internally pre-processed with {@link PMREMGenerator}.
  27865. *
  27866. * @type {?Texture}
  27867. * @default null
  27868. */
  27869. this.envMap = null;
  27870. /**
  27871. * The rotation of the environment map in radians.
  27872. *
  27873. * @type {Euler}
  27874. * @default (0,0,0)
  27875. */
  27876. this.envMapRotation = new Euler();
  27877. /**
  27878. * Scales the effect of the environment map by multiplying its color.
  27879. *
  27880. * @type {number}
  27881. * @default 1
  27882. */
  27883. this.envMapIntensity = 1.0;
  27884. /**
  27885. * Renders the geometry as a wireframe.
  27886. *
  27887. * @type {boolean}
  27888. * @default false
  27889. */
  27890. this.wireframe = false;
  27891. /**
  27892. * Controls the thickness of the wireframe.
  27893. *
  27894. * Can only be used with {@link SVGRenderer}.
  27895. *
  27896. * @type {number}
  27897. * @default 1
  27898. */
  27899. this.wireframeLinewidth = 1;
  27900. /**
  27901. * Defines appearance of wireframe ends.
  27902. *
  27903. * Can only be used with {@link SVGRenderer}.
  27904. *
  27905. * @type {('round'|'bevel'|'miter')}
  27906. * @default 'round'
  27907. */
  27908. this.wireframeLinecap = 'round';
  27909. /**
  27910. * Defines appearance of wireframe joints.
  27911. *
  27912. * Can only be used with {@link SVGRenderer}.
  27913. *
  27914. * @type {('round'|'bevel'|'miter')}
  27915. * @default 'round'
  27916. */
  27917. this.wireframeLinejoin = 'round';
  27918. /**
  27919. * Whether the material is rendered with flat shading or not.
  27920. *
  27921. * @type {boolean}
  27922. * @default false
  27923. */
  27924. this.flatShading = false;
  27925. /**
  27926. * Whether the material is affected by fog or not.
  27927. *
  27928. * @type {boolean}
  27929. * @default true
  27930. */
  27931. this.fog = true;
  27932. this.setValues( parameters );
  27933. }
  27934. copy( source ) {
  27935. super.copy( source );
  27936. this.defines = { 'STANDARD': '' };
  27937. this.color.copy( source.color );
  27938. this.roughness = source.roughness;
  27939. this.metalness = source.metalness;
  27940. this.map = source.map;
  27941. this.lightMap = source.lightMap;
  27942. this.lightMapIntensity = source.lightMapIntensity;
  27943. this.aoMap = source.aoMap;
  27944. this.aoMapIntensity = source.aoMapIntensity;
  27945. this.emissive.copy( source.emissive );
  27946. this.emissiveMap = source.emissiveMap;
  27947. this.emissiveIntensity = source.emissiveIntensity;
  27948. this.bumpMap = source.bumpMap;
  27949. this.bumpScale = source.bumpScale;
  27950. this.normalMap = source.normalMap;
  27951. this.normalMapType = source.normalMapType;
  27952. this.normalScale.copy( source.normalScale );
  27953. this.displacementMap = source.displacementMap;
  27954. this.displacementScale = source.displacementScale;
  27955. this.displacementBias = source.displacementBias;
  27956. this.roughnessMap = source.roughnessMap;
  27957. this.metalnessMap = source.metalnessMap;
  27958. this.alphaMap = source.alphaMap;
  27959. this.envMap = source.envMap;
  27960. this.envMapRotation.copy( source.envMapRotation );
  27961. this.envMapIntensity = source.envMapIntensity;
  27962. this.wireframe = source.wireframe;
  27963. this.wireframeLinewidth = source.wireframeLinewidth;
  27964. this.wireframeLinecap = source.wireframeLinecap;
  27965. this.wireframeLinejoin = source.wireframeLinejoin;
  27966. this.flatShading = source.flatShading;
  27967. this.fog = source.fog;
  27968. return this;
  27969. }
  27970. }
  27971. /**
  27972. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  27973. * physically-based rendering properties:
  27974. *
  27975. * - Anisotropy: Ability to represent the anisotropic property of materials
  27976. * as observable with brushed metals.
  27977. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  27978. * a clear, reflective layer on top of another layer that may be irregular or rough.
  27979. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  27980. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  27981. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  27982. * wings of many insects.
  27983. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  27984. * transparent materials are less reflective. Physically-based transmission provides a more
  27985. * realistic option for thin, transparent surfaces like glass.
  27986. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  27987. * - Sheen: Can be used for representing cloth and fabric materials.
  27988. *
  27989. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  27990. * higher performance cost, per pixel, than other three.js materials. Most
  27991. * effects are disabled by default, and add cost as they are enabled. For
  27992. * best results, always specify an environment map when using this material.
  27993. *
  27994. * @augments MeshStandardMaterial
  27995. */
  27996. class MeshPhysicalMaterial extends MeshStandardMaterial {
  27997. /**
  27998. * Constructs a new mesh physical material.
  27999. *
  28000. * @param {Object} [parameters] - An object with one or more properties
  28001. * defining the material's appearance. Any property of the material
  28002. * (including any property from inherited materials) can be passed
  28003. * in here. Color values can be passed any type of value accepted
  28004. * by {@link Color#set}.
  28005. */
  28006. constructor( parameters ) {
  28007. super();
  28008. /**
  28009. * This flag can be used for type testing.
  28010. *
  28011. * @type {boolean}
  28012. * @readonly
  28013. * @default true
  28014. */
  28015. this.isMeshPhysicalMaterial = true;
  28016. this.defines = {
  28017. 'STANDARD': '',
  28018. 'PHYSICAL': ''
  28019. };
  28020. this.type = 'MeshPhysicalMaterial';
  28021. /**
  28022. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  28023. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  28024. * property provides additional rotation to the vectors in the texture.
  28025. *
  28026. * @type {number}
  28027. * @default 1
  28028. */
  28029. this.anisotropyRotation = 0;
  28030. /**
  28031. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  28032. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  28033. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  28034. *
  28035. * @type {?Texture}
  28036. * @default null
  28037. */
  28038. this.anisotropyMap = null;
  28039. /**
  28040. * The red channel of this texture is multiplied against `clearcoat`,
  28041. * for per-pixel control over a coating's intensity.
  28042. *
  28043. * @type {?Texture}
  28044. * @default null
  28045. */
  28046. this.clearcoatMap = null;
  28047. /**
  28048. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  28049. *
  28050. * @type {number}
  28051. * @default 0
  28052. */
  28053. this.clearcoatRoughness = 0.0;
  28054. /**
  28055. * The green channel of this texture is multiplied against
  28056. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  28057. *
  28058. * @type {?Texture}
  28059. * @default null
  28060. */
  28061. this.clearcoatRoughnessMap = null;
  28062. /**
  28063. * How much `clearcoatNormalMap` affects the clear coat layer, from
  28064. * `(0,0)` to `(1,1)`.
  28065. *
  28066. * @type {Vector2}
  28067. * @default (1,1)
  28068. */
  28069. this.clearcoatNormalScale = new Vector2( 1, 1 );
  28070. /**
  28071. * Can be used to enable independent normals for the clear coat layer.
  28072. *
  28073. * @type {?Texture}
  28074. * @default null
  28075. */
  28076. this.clearcoatNormalMap = null;
  28077. /**
  28078. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  28079. *
  28080. * @type {number}
  28081. * @default 1.5
  28082. */
  28083. this.ior = 1.5;
  28084. /**
  28085. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  28086. * corresponds to an index-of-refraction of `1.5`.
  28087. *
  28088. * This models the reflectivity of non-metallic materials. It has no effect
  28089. * when `metalness` is `1.0`
  28090. *
  28091. * @name MeshPhysicalMaterial#reflectivity
  28092. * @type {number}
  28093. * @default 0.5
  28094. */
  28095. Object.defineProperty( this, 'reflectivity', {
  28096. get: function () {
  28097. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  28098. },
  28099. set: function ( reflectivity ) {
  28100. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  28101. }
  28102. } );
  28103. /**
  28104. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  28105. * control over iridescence.
  28106. *
  28107. * @type {?Texture}
  28108. * @default null
  28109. */
  28110. this.iridescenceMap = null;
  28111. /**
  28112. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  28113. * Between `1.0` to `2.333`.
  28114. *
  28115. * @type {number}
  28116. * @default 1.3
  28117. */
  28118. this.iridescenceIOR = 1.3;
  28119. /**
  28120. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  28121. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  28122. *
  28123. * @type {Array<number,number>}
  28124. * @default [100,400]
  28125. */
  28126. this.iridescenceThicknessRange = [ 100, 400 ];
  28127. /**
  28128. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  28129. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  28130. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  28131. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  28132. * - Values in-between will linearly interpolate between the elements of the array.
  28133. *
  28134. * @type {?Texture}
  28135. * @default null
  28136. */
  28137. this.iridescenceThicknessMap = null;
  28138. /**
  28139. * The sheen tint.
  28140. *
  28141. * @type {Color}
  28142. * @default (0,0,0)
  28143. */
  28144. this.sheenColor = new Color( 0x000000 );
  28145. /**
  28146. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  28147. * over sheen tint.
  28148. *
  28149. * @type {?Texture}
  28150. * @default null
  28151. */
  28152. this.sheenColorMap = null;
  28153. /**
  28154. * Roughness of the sheen layer, from `0.0` to `1.0`.
  28155. *
  28156. * @type {number}
  28157. * @default 1
  28158. */
  28159. this.sheenRoughness = 1.0;
  28160. /**
  28161. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28162. * over sheen roughness.
  28163. *
  28164. * @type {?Texture}
  28165. * @default null
  28166. */
  28167. this.sheenRoughnessMap = null;
  28168. /**
  28169. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28170. * optical transparency.
  28171. *
  28172. * @type {?Texture}
  28173. * @default null
  28174. */
  28175. this.transmissionMap = null;
  28176. /**
  28177. * The thickness of the volume beneath the surface. The value is given in the
  28178. * coordinate space of the mesh. If the value is `0` the material is
  28179. * thin-walled. Otherwise the material is a volume boundary.
  28180. *
  28181. * @type {number}
  28182. * @default 0
  28183. */
  28184. this.thickness = 0;
  28185. /**
  28186. * A texture that defines the thickness, stored in the green channel. This will
  28187. * be multiplied by `thickness`.
  28188. *
  28189. * @type {?Texture}
  28190. * @default null
  28191. */
  28192. this.thicknessMap = null;
  28193. /**
  28194. * Density of the medium given as the average distance that light travels in
  28195. * the medium before interacting with a particle. The value is given in world
  28196. * space units, and must be greater than zero.
  28197. *
  28198. * @type {number}
  28199. * @default Infinity
  28200. */
  28201. this.attenuationDistance = Infinity;
  28202. /**
  28203. * The color that white light turns into due to absorption when reaching the
  28204. * attenuation distance.
  28205. *
  28206. * @type {Color}
  28207. * @default (1,1,1)
  28208. */
  28209. this.attenuationColor = new Color( 1, 1, 1 );
  28210. /**
  28211. * A float that scales the amount of specular reflection for non-metals only.
  28212. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28213. *
  28214. * @type {number}
  28215. * @default 1
  28216. */
  28217. this.specularIntensity = 1.0;
  28218. /**
  28219. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28220. * for per-pixel control over specular intensity.
  28221. *
  28222. * @type {?Texture}
  28223. * @default null
  28224. */
  28225. this.specularIntensityMap = null;
  28226. /**
  28227. * Tints the specular reflection at normal incidence for non-metals only.
  28228. *
  28229. * @type {Color}
  28230. * @default (1,1,1)
  28231. */
  28232. this.specularColor = new Color( 1, 1, 1 );
  28233. /**
  28234. * The RGB channels of this texture are multiplied against `specularColor`,
  28235. * for per-pixel control over specular color.
  28236. *
  28237. * @type {?Texture}
  28238. * @default null
  28239. */
  28240. this.specularColorMap = null;
  28241. this._anisotropy = 0;
  28242. this._clearcoat = 0;
  28243. this._dispersion = 0;
  28244. this._iridescence = 0;
  28245. this._sheen = 0.0;
  28246. this._transmission = 0;
  28247. this.setValues( parameters );
  28248. }
  28249. /**
  28250. * The anisotropy strength.
  28251. *
  28252. * @type {number}
  28253. * @default 0
  28254. */
  28255. get anisotropy() {
  28256. return this._anisotropy;
  28257. }
  28258. set anisotropy( value ) {
  28259. if ( this._anisotropy > 0 !== value > 0 ) {
  28260. this.version ++;
  28261. }
  28262. this._anisotropy = value;
  28263. }
  28264. /**
  28265. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28266. * clear coat related properties to enable multilayer materials that have a
  28267. * thin translucent layer over the base layer.
  28268. *
  28269. * @type {number}
  28270. * @default 0
  28271. */
  28272. get clearcoat() {
  28273. return this._clearcoat;
  28274. }
  28275. set clearcoat( value ) {
  28276. if ( this._clearcoat > 0 !== value > 0 ) {
  28277. this.version ++;
  28278. }
  28279. this._clearcoat = value;
  28280. }
  28281. /**
  28282. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28283. * the surface and the viewer, from `0.0` to `1.0`.
  28284. *
  28285. * @type {number}
  28286. * @default 0
  28287. */
  28288. get iridescence() {
  28289. return this._iridescence;
  28290. }
  28291. set iridescence( value ) {
  28292. if ( this._iridescence > 0 !== value > 0 ) {
  28293. this.version ++;
  28294. }
  28295. this._iridescence = value;
  28296. }
  28297. /**
  28298. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28299. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28300. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28301. *
  28302. * @type {number}
  28303. * @default 0
  28304. */
  28305. get dispersion() {
  28306. return this._dispersion;
  28307. }
  28308. set dispersion( value ) {
  28309. if ( this._dispersion > 0 !== value > 0 ) {
  28310. this.version ++;
  28311. }
  28312. this._dispersion = value;
  28313. }
  28314. /**
  28315. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28316. *
  28317. * @type {number}
  28318. * @default 0
  28319. */
  28320. get sheen() {
  28321. return this._sheen;
  28322. }
  28323. set sheen( value ) {
  28324. if ( this._sheen > 0 !== value > 0 ) {
  28325. this.version ++;
  28326. }
  28327. this._sheen = value;
  28328. }
  28329. /**
  28330. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28331. *
  28332. * Thin, transparent or semitransparent, plastic or glass materials remain
  28333. * largely reflective even if they are fully transmissive. The transmission
  28334. * property can be used to model these materials.
  28335. *
  28336. * When transmission is non-zero, `opacity` should be set to `1`.
  28337. *
  28338. * @type {number}
  28339. * @default 0
  28340. */
  28341. get transmission() {
  28342. return this._transmission;
  28343. }
  28344. set transmission( value ) {
  28345. if ( this._transmission > 0 !== value > 0 ) {
  28346. this.version ++;
  28347. }
  28348. this._transmission = value;
  28349. }
  28350. copy( source ) {
  28351. super.copy( source );
  28352. this.defines = {
  28353. 'STANDARD': '',
  28354. 'PHYSICAL': ''
  28355. };
  28356. this.anisotropy = source.anisotropy;
  28357. this.anisotropyRotation = source.anisotropyRotation;
  28358. this.anisotropyMap = source.anisotropyMap;
  28359. this.clearcoat = source.clearcoat;
  28360. this.clearcoatMap = source.clearcoatMap;
  28361. this.clearcoatRoughness = source.clearcoatRoughness;
  28362. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28363. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28364. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28365. this.dispersion = source.dispersion;
  28366. this.ior = source.ior;
  28367. this.iridescence = source.iridescence;
  28368. this.iridescenceMap = source.iridescenceMap;
  28369. this.iridescenceIOR = source.iridescenceIOR;
  28370. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28371. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28372. this.sheen = source.sheen;
  28373. this.sheenColor.copy( source.sheenColor );
  28374. this.sheenColorMap = source.sheenColorMap;
  28375. this.sheenRoughness = source.sheenRoughness;
  28376. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28377. this.transmission = source.transmission;
  28378. this.transmissionMap = source.transmissionMap;
  28379. this.thickness = source.thickness;
  28380. this.thicknessMap = source.thicknessMap;
  28381. this.attenuationDistance = source.attenuationDistance;
  28382. this.attenuationColor.copy( source.attenuationColor );
  28383. this.specularIntensity = source.specularIntensity;
  28384. this.specularIntensityMap = source.specularIntensityMap;
  28385. this.specularColor.copy( source.specularColor );
  28386. this.specularColorMap = source.specularColorMap;
  28387. return this;
  28388. }
  28389. }
  28390. /**
  28391. * A material for shiny surfaces with specular highlights.
  28392. *
  28393. * The material uses a non-physically based [Blinn-Phong]{@link https://en.wikipedia.org/wiki/Blinn-Phong_shading_model}
  28394. * model for calculating reflectance. Unlike the Lambertian model used in the
  28395. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28396. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28397. *
  28398. * Performance will generally be greater when using this material over the
  28399. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28400. * some graphical accuracy.
  28401. *
  28402. * @augments Material
  28403. */
  28404. class MeshPhongMaterial extends Material {
  28405. /**
  28406. * Constructs a new mesh phong material.
  28407. *
  28408. * @param {Object} [parameters] - An object with one or more properties
  28409. * defining the material's appearance. Any property of the material
  28410. * (including any property from inherited materials) can be passed
  28411. * in here. Color values can be passed any type of value accepted
  28412. * by {@link Color#set}.
  28413. */
  28414. constructor( parameters ) {
  28415. super();
  28416. /**
  28417. * This flag can be used for type testing.
  28418. *
  28419. * @type {boolean}
  28420. * @readonly
  28421. * @default true
  28422. */
  28423. this.isMeshPhongMaterial = true;
  28424. this.type = 'MeshPhongMaterial';
  28425. /**
  28426. * Color of the material.
  28427. *
  28428. * @type {Color}
  28429. * @default (1,1,1)
  28430. */
  28431. this.color = new Color( 0xffffff ); // diffuse
  28432. /**
  28433. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28434. *
  28435. * This defines how shiny the material is and the color of its shine.
  28436. *
  28437. * @type {Color}
  28438. */
  28439. this.specular = new Color( 0x111111 );
  28440. /**
  28441. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28442. *
  28443. * @type {number}
  28444. * @default 30
  28445. */
  28446. this.shininess = 30;
  28447. /**
  28448. * The color map. May optionally include an alpha channel, typically combined
  28449. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28450. * color is modulated by the diffuse `color`.
  28451. *
  28452. * @type {?Texture}
  28453. * @default null
  28454. */
  28455. this.map = null;
  28456. /**
  28457. * The light map. Requires a second set of UVs.
  28458. *
  28459. * @type {?Texture}
  28460. * @default null
  28461. */
  28462. this.lightMap = null;
  28463. /**
  28464. * Intensity of the baked light.
  28465. *
  28466. * @type {number}
  28467. * @default 1
  28468. */
  28469. this.lightMapIntensity = 1.0;
  28470. /**
  28471. * The red channel of this texture is used as the ambient occlusion map.
  28472. * Requires a second set of UVs.
  28473. *
  28474. * @type {?Texture}
  28475. * @default null
  28476. */
  28477. this.aoMap = null;
  28478. /**
  28479. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28480. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28481. * red channel is also `1`, ambient light is fully occluded on a surface.
  28482. *
  28483. * @type {number}
  28484. * @default 1
  28485. */
  28486. this.aoMapIntensity = 1.0;
  28487. /**
  28488. * Emissive (light) color of the material, essentially a solid color
  28489. * unaffected by other lighting.
  28490. *
  28491. * @type {Color}
  28492. * @default (0,0,0)
  28493. */
  28494. this.emissive = new Color( 0x000000 );
  28495. /**
  28496. * Intensity of the emissive light. Modulates the emissive color.
  28497. *
  28498. * @type {number}
  28499. * @default 1
  28500. */
  28501. this.emissiveIntensity = 1.0;
  28502. /**
  28503. * Set emissive (glow) map. The emissive map color is modulated by the
  28504. * emissive color and the emissive intensity. If you have an emissive map,
  28505. * be sure to set the emissive color to something other than black.
  28506. *
  28507. * @type {?Texture}
  28508. * @default null
  28509. */
  28510. this.emissiveMap = null;
  28511. /**
  28512. * The texture to create a bump map. The black and white values map to the
  28513. * perceived depth in relation to the lights. Bump doesn't actually affect
  28514. * the geometry of the object, only the lighting. If a normal map is defined
  28515. * this will be ignored.
  28516. *
  28517. * @type {?Texture}
  28518. * @default null
  28519. */
  28520. this.bumpMap = null;
  28521. /**
  28522. * How much the bump map affects the material. Typical range is `[0,1]`.
  28523. *
  28524. * @type {number}
  28525. * @default 1
  28526. */
  28527. this.bumpScale = 1;
  28528. /**
  28529. * The texture to create a normal map. The RGB values affect the surface
  28530. * normal for each pixel fragment and change the way the color is lit. Normal
  28531. * maps do not change the actual shape of the surface, only the lighting. In
  28532. * case the material has a normal map authored using the left handed
  28533. * convention, the `y` component of `normalScale` should be negated to compensate
  28534. * for the different handedness.
  28535. *
  28536. * @type {?Texture}
  28537. * @default null
  28538. */
  28539. this.normalMap = null;
  28540. /**
  28541. * The type of normal map.
  28542. *
  28543. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28544. * @default TangentSpaceNormalMap
  28545. */
  28546. this.normalMapType = TangentSpaceNormalMap;
  28547. /**
  28548. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28549. *
  28550. * @type {Vector2}
  28551. * @default (1,1)
  28552. */
  28553. this.normalScale = new Vector2( 1, 1 );
  28554. /**
  28555. * The displacement map affects the position of the mesh's vertices. Unlike
  28556. * other maps which only affect the light and shade of the material the
  28557. * displaced vertices can cast shadows, block other objects, and otherwise
  28558. * act as real geometry. The displacement texture is an image where the value
  28559. * of each pixel (white being the highest) is mapped against, and
  28560. * repositions, the vertices of the mesh.
  28561. *
  28562. * @type {?Texture}
  28563. * @default null
  28564. */
  28565. this.displacementMap = null;
  28566. /**
  28567. * How much the displacement map affects the mesh (where black is no
  28568. * displacement, and white is maximum displacement). Without a displacement
  28569. * map set, this value is not applied.
  28570. *
  28571. * @type {number}
  28572. * @default 0
  28573. */
  28574. this.displacementScale = 1;
  28575. /**
  28576. * The offset of the displacement map's values on the mesh's vertices.
  28577. * The bias is added to the scaled sample of the displacement map.
  28578. * Without a displacement map set, this value is not applied.
  28579. *
  28580. * @type {number}
  28581. * @default 0
  28582. */
  28583. this.displacementBias = 0;
  28584. /**
  28585. * The specular map value affects both how much the specular surface
  28586. * highlight contributes and how much of the environment map affects the
  28587. * surface.
  28588. *
  28589. * @type {?Texture}
  28590. * @default null
  28591. */
  28592. this.specularMap = null;
  28593. /**
  28594. * The alpha map is a grayscale texture that controls the opacity across the
  28595. * surface (black: fully transparent; white: fully opaque).
  28596. *
  28597. * Only the color of the texture is used, ignoring the alpha channel if one
  28598. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28599. * when sampling this texture due to the extra bit of precision provided for
  28600. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28601. * luminance/alpha textures will also still work as expected.
  28602. *
  28603. * @type {?Texture}
  28604. * @default null
  28605. */
  28606. this.alphaMap = null;
  28607. /**
  28608. * The environment map.
  28609. *
  28610. * @type {?Texture}
  28611. * @default null
  28612. */
  28613. this.envMap = null;
  28614. /**
  28615. * The rotation of the environment map in radians.
  28616. *
  28617. * @type {Euler}
  28618. * @default (0,0,0)
  28619. */
  28620. this.envMapRotation = new Euler();
  28621. /**
  28622. * How to combine the result of the surface's color with the environment map, if any.
  28623. *
  28624. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  28625. * blend between the two colors.
  28626. *
  28627. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  28628. * @default MultiplyOperation
  28629. */
  28630. this.combine = MultiplyOperation;
  28631. /**
  28632. * How much the environment map affects the surface.
  28633. * The valid range is between `0` (no reflections) and `1` (full reflections).
  28634. *
  28635. * @type {number}
  28636. * @default 1
  28637. */
  28638. this.reflectivity = 1;
  28639. /**
  28640. * The index of refraction (IOR) of air (approximately 1) divided by the
  28641. * index of refraction of the material. It is used with environment mapping
  28642. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  28643. * The refraction ratio should not exceed `1`.
  28644. *
  28645. * @type {number}
  28646. * @default 0.98
  28647. */
  28648. this.refractionRatio = 0.98;
  28649. /**
  28650. * Renders the geometry as a wireframe.
  28651. *
  28652. * @type {boolean}
  28653. * @default false
  28654. */
  28655. this.wireframe = false;
  28656. /**
  28657. * Controls the thickness of the wireframe.
  28658. *
  28659. * Can only be used with {@link SVGRenderer}.
  28660. *
  28661. * @type {number}
  28662. * @default 1
  28663. */
  28664. this.wireframeLinewidth = 1;
  28665. /**
  28666. * Defines appearance of wireframe ends.
  28667. *
  28668. * Can only be used with {@link SVGRenderer}.
  28669. *
  28670. * @type {('round'|'bevel'|'miter')}
  28671. * @default 'round'
  28672. */
  28673. this.wireframeLinecap = 'round';
  28674. /**
  28675. * Defines appearance of wireframe joints.
  28676. *
  28677. * Can only be used with {@link SVGRenderer}.
  28678. *
  28679. * @type {('round'|'bevel'|'miter')}
  28680. * @default 'round'
  28681. */
  28682. this.wireframeLinejoin = 'round';
  28683. /**
  28684. * Whether the material is rendered with flat shading or not.
  28685. *
  28686. * @type {boolean}
  28687. * @default false
  28688. */
  28689. this.flatShading = false;
  28690. /**
  28691. * Whether the material is affected by fog or not.
  28692. *
  28693. * @type {boolean}
  28694. * @default true
  28695. */
  28696. this.fog = true;
  28697. this.setValues( parameters );
  28698. }
  28699. copy( source ) {
  28700. super.copy( source );
  28701. this.color.copy( source.color );
  28702. this.specular.copy( source.specular );
  28703. this.shininess = source.shininess;
  28704. this.map = source.map;
  28705. this.lightMap = source.lightMap;
  28706. this.lightMapIntensity = source.lightMapIntensity;
  28707. this.aoMap = source.aoMap;
  28708. this.aoMapIntensity = source.aoMapIntensity;
  28709. this.emissive.copy( source.emissive );
  28710. this.emissiveMap = source.emissiveMap;
  28711. this.emissiveIntensity = source.emissiveIntensity;
  28712. this.bumpMap = source.bumpMap;
  28713. this.bumpScale = source.bumpScale;
  28714. this.normalMap = source.normalMap;
  28715. this.normalMapType = source.normalMapType;
  28716. this.normalScale.copy( source.normalScale );
  28717. this.displacementMap = source.displacementMap;
  28718. this.displacementScale = source.displacementScale;
  28719. this.displacementBias = source.displacementBias;
  28720. this.specularMap = source.specularMap;
  28721. this.alphaMap = source.alphaMap;
  28722. this.envMap = source.envMap;
  28723. this.envMapRotation.copy( source.envMapRotation );
  28724. this.combine = source.combine;
  28725. this.reflectivity = source.reflectivity;
  28726. this.refractionRatio = source.refractionRatio;
  28727. this.wireframe = source.wireframe;
  28728. this.wireframeLinewidth = source.wireframeLinewidth;
  28729. this.wireframeLinecap = source.wireframeLinecap;
  28730. this.wireframeLinejoin = source.wireframeLinejoin;
  28731. this.flatShading = source.flatShading;
  28732. this.fog = source.fog;
  28733. return this;
  28734. }
  28735. }
  28736. /**
  28737. * A material implementing toon shading.
  28738. *
  28739. * @augments Material
  28740. */
  28741. class MeshToonMaterial extends Material {
  28742. /**
  28743. * Constructs a new mesh toon material.
  28744. *
  28745. * @param {Object} [parameters] - An object with one or more properties
  28746. * defining the material's appearance. Any property of the material
  28747. * (including any property from inherited materials) can be passed
  28748. * in here. Color values can be passed any type of value accepted
  28749. * by {@link Color#set}.
  28750. */
  28751. constructor( parameters ) {
  28752. super();
  28753. /**
  28754. * This flag can be used for type testing.
  28755. *
  28756. * @type {boolean}
  28757. * @readonly
  28758. * @default true
  28759. */
  28760. this.isMeshToonMaterial = true;
  28761. this.defines = { 'TOON': '' };
  28762. this.type = 'MeshToonMaterial';
  28763. /**
  28764. * Color of the material.
  28765. *
  28766. * @type {Color}
  28767. * @default (1,1,1)
  28768. */
  28769. this.color = new Color( 0xffffff );
  28770. /**
  28771. * The color map. May optionally include an alpha channel, typically combined
  28772. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28773. * color is modulated by the diffuse `color`.
  28774. *
  28775. * @type {?Texture}
  28776. * @default null
  28777. */
  28778. this.map = null;
  28779. /**
  28780. * Gradient map for toon shading. It's required to set
  28781. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@linkNearestFilter}
  28782. * when using this type of texture.
  28783. *
  28784. * @type {?Texture}
  28785. * @default null
  28786. */
  28787. this.gradientMap = null;
  28788. /**
  28789. * The light map. Requires a second set of UVs.
  28790. *
  28791. * @type {?Texture}
  28792. * @default null
  28793. */
  28794. this.lightMap = null;
  28795. /**
  28796. * Intensity of the baked light.
  28797. *
  28798. * @type {number}
  28799. * @default 1
  28800. */
  28801. this.lightMapIntensity = 1.0;
  28802. /**
  28803. * The red channel of this texture is used as the ambient occlusion map.
  28804. * Requires a second set of UVs.
  28805. *
  28806. * @type {?Texture}
  28807. * @default null
  28808. */
  28809. this.aoMap = null;
  28810. /**
  28811. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28812. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28813. * red channel is also `1`, ambient light is fully occluded on a surface.
  28814. *
  28815. * @type {number}
  28816. * @default 1
  28817. */
  28818. this.aoMapIntensity = 1.0;
  28819. /**
  28820. * Emissive (light) color of the material, essentially a solid color
  28821. * unaffected by other lighting.
  28822. *
  28823. * @type {Color}
  28824. * @default (0,0,0)
  28825. */
  28826. this.emissive = new Color( 0x000000 );
  28827. /**
  28828. * Intensity of the emissive light. Modulates the emissive color.
  28829. *
  28830. * @type {number}
  28831. * @default 1
  28832. */
  28833. this.emissiveIntensity = 1.0;
  28834. /**
  28835. * Set emissive (glow) map. The emissive map color is modulated by the
  28836. * emissive color and the emissive intensity. If you have an emissive map,
  28837. * be sure to set the emissive color to something other than black.
  28838. *
  28839. * @type {?Texture}
  28840. * @default null
  28841. */
  28842. this.emissiveMap = null;
  28843. /**
  28844. * The texture to create a bump map. The black and white values map to the
  28845. * perceived depth in relation to the lights. Bump doesn't actually affect
  28846. * the geometry of the object, only the lighting. If a normal map is defined
  28847. * this will be ignored.
  28848. *
  28849. * @type {?Texture}
  28850. * @default null
  28851. */
  28852. this.bumpMap = null;
  28853. /**
  28854. * How much the bump map affects the material. Typical range is `[0,1]`.
  28855. *
  28856. * @type {number}
  28857. * @default 1
  28858. */
  28859. this.bumpScale = 1;
  28860. /**
  28861. * The texture to create a normal map. The RGB values affect the surface
  28862. * normal for each pixel fragment and change the way the color is lit. Normal
  28863. * maps do not change the actual shape of the surface, only the lighting. In
  28864. * case the material has a normal map authored using the left handed
  28865. * convention, the `y` component of `normalScale` should be negated to compensate
  28866. * for the different handedness.
  28867. *
  28868. * @type {?Texture}
  28869. * @default null
  28870. */
  28871. this.normalMap = null;
  28872. /**
  28873. * The type of normal map.
  28874. *
  28875. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28876. * @default TangentSpaceNormalMap
  28877. */
  28878. this.normalMapType = TangentSpaceNormalMap;
  28879. /**
  28880. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28881. *
  28882. * @type {Vector2}
  28883. * @default (1,1)
  28884. */
  28885. this.normalScale = new Vector2( 1, 1 );
  28886. /**
  28887. * The displacement map affects the position of the mesh's vertices. Unlike
  28888. * other maps which only affect the light and shade of the material the
  28889. * displaced vertices can cast shadows, block other objects, and otherwise
  28890. * act as real geometry. The displacement texture is an image where the value
  28891. * of each pixel (white being the highest) is mapped against, and
  28892. * repositions, the vertices of the mesh.
  28893. *
  28894. * @type {?Texture}
  28895. * @default null
  28896. */
  28897. this.displacementMap = null;
  28898. /**
  28899. * How much the displacement map affects the mesh (where black is no
  28900. * displacement, and white is maximum displacement). Without a displacement
  28901. * map set, this value is not applied.
  28902. *
  28903. * @type {number}
  28904. * @default 0
  28905. */
  28906. this.displacementScale = 1;
  28907. /**
  28908. * The offset of the displacement map's values on the mesh's vertices.
  28909. * The bias is added to the scaled sample of the displacement map.
  28910. * Without a displacement map set, this value is not applied.
  28911. *
  28912. * @type {number}
  28913. * @default 0
  28914. */
  28915. this.displacementBias = 0;
  28916. /**
  28917. * The alpha map is a grayscale texture that controls the opacity across the
  28918. * surface (black: fully transparent; white: fully opaque).
  28919. *
  28920. * Only the color of the texture is used, ignoring the alpha channel if one
  28921. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28922. * when sampling this texture due to the extra bit of precision provided for
  28923. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28924. * luminance/alpha textures will also still work as expected.
  28925. *
  28926. * @type {?Texture}
  28927. * @default null
  28928. */
  28929. this.alphaMap = null;
  28930. /**
  28931. * Renders the geometry as a wireframe.
  28932. *
  28933. * @type {boolean}
  28934. * @default false
  28935. */
  28936. this.wireframe = false;
  28937. /**
  28938. * Controls the thickness of the wireframe.
  28939. *
  28940. * Can only be used with {@link SVGRenderer}.
  28941. *
  28942. * @type {number}
  28943. * @default 1
  28944. */
  28945. this.wireframeLinewidth = 1;
  28946. /**
  28947. * Defines appearance of wireframe ends.
  28948. *
  28949. * Can only be used with {@link SVGRenderer}.
  28950. *
  28951. * @type {('round'|'bevel'|'miter')}
  28952. * @default 'round'
  28953. */
  28954. this.wireframeLinecap = 'round';
  28955. /**
  28956. * Defines appearance of wireframe joints.
  28957. *
  28958. * Can only be used with {@link SVGRenderer}.
  28959. *
  28960. * @type {('round'|'bevel'|'miter')}
  28961. * @default 'round'
  28962. */
  28963. this.wireframeLinejoin = 'round';
  28964. /**
  28965. * Whether the material is affected by fog or not.
  28966. *
  28967. * @type {boolean}
  28968. * @default true
  28969. */
  28970. this.fog = true;
  28971. this.setValues( parameters );
  28972. }
  28973. copy( source ) {
  28974. super.copy( source );
  28975. this.color.copy( source.color );
  28976. this.map = source.map;
  28977. this.gradientMap = source.gradientMap;
  28978. this.lightMap = source.lightMap;
  28979. this.lightMapIntensity = source.lightMapIntensity;
  28980. this.aoMap = source.aoMap;
  28981. this.aoMapIntensity = source.aoMapIntensity;
  28982. this.emissive.copy( source.emissive );
  28983. this.emissiveMap = source.emissiveMap;
  28984. this.emissiveIntensity = source.emissiveIntensity;
  28985. this.bumpMap = source.bumpMap;
  28986. this.bumpScale = source.bumpScale;
  28987. this.normalMap = source.normalMap;
  28988. this.normalMapType = source.normalMapType;
  28989. this.normalScale.copy( source.normalScale );
  28990. this.displacementMap = source.displacementMap;
  28991. this.displacementScale = source.displacementScale;
  28992. this.displacementBias = source.displacementBias;
  28993. this.alphaMap = source.alphaMap;
  28994. this.wireframe = source.wireframe;
  28995. this.wireframeLinewidth = source.wireframeLinewidth;
  28996. this.wireframeLinecap = source.wireframeLinecap;
  28997. this.wireframeLinejoin = source.wireframeLinejoin;
  28998. this.fog = source.fog;
  28999. return this;
  29000. }
  29001. }
  29002. /**
  29003. * A material that maps the normal vectors to RGB colors.
  29004. *
  29005. * @augments Material
  29006. */
  29007. class MeshNormalMaterial extends Material {
  29008. /**
  29009. * Constructs a new mesh normal material.
  29010. *
  29011. * @param {Object} [parameters] - An object with one or more properties
  29012. * defining the material's appearance. Any property of the material
  29013. * (including any property from inherited materials) can be passed
  29014. * in here. Color values can be passed any type of value accepted
  29015. * by {@link Color#set}.
  29016. */
  29017. constructor( parameters ) {
  29018. super();
  29019. /**
  29020. * This flag can be used for type testing.
  29021. *
  29022. * @type {boolean}
  29023. * @readonly
  29024. * @default true
  29025. */
  29026. this.isMeshNormalMaterial = true;
  29027. this.type = 'MeshNormalMaterial';
  29028. /**
  29029. * The texture to create a bump map. The black and white values map to the
  29030. * perceived depth in relation to the lights. Bump doesn't actually affect
  29031. * the geometry of the object, only the lighting. If a normal map is defined
  29032. * this will be ignored.
  29033. *
  29034. * @type {?Texture}
  29035. * @default null
  29036. */
  29037. this.bumpMap = null;
  29038. /**
  29039. * How much the bump map affects the material. Typical range is `[0,1]`.
  29040. *
  29041. * @type {number}
  29042. * @default 1
  29043. */
  29044. this.bumpScale = 1;
  29045. /**
  29046. * The texture to create a normal map. The RGB values affect the surface
  29047. * normal for each pixel fragment and change the way the color is lit. Normal
  29048. * maps do not change the actual shape of the surface, only the lighting. In
  29049. * case the material has a normal map authored using the left handed
  29050. * convention, the `y` component of `normalScale` should be negated to compensate
  29051. * for the different handedness.
  29052. *
  29053. * @type {?Texture}
  29054. * @default null
  29055. */
  29056. this.normalMap = null;
  29057. /**
  29058. * The type of normal map.
  29059. *
  29060. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29061. * @default TangentSpaceNormalMap
  29062. */
  29063. this.normalMapType = TangentSpaceNormalMap;
  29064. /**
  29065. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29066. *
  29067. * @type {Vector2}
  29068. * @default (1,1)
  29069. */
  29070. this.normalScale = new Vector2( 1, 1 );
  29071. /**
  29072. * The displacement map affects the position of the mesh's vertices. Unlike
  29073. * other maps which only affect the light and shade of the material the
  29074. * displaced vertices can cast shadows, block other objects, and otherwise
  29075. * act as real geometry. The displacement texture is an image where the value
  29076. * of each pixel (white being the highest) is mapped against, and
  29077. * repositions, the vertices of the mesh.
  29078. *
  29079. * @type {?Texture}
  29080. * @default null
  29081. */
  29082. this.displacementMap = null;
  29083. /**
  29084. * How much the displacement map affects the mesh (where black is no
  29085. * displacement, and white is maximum displacement). Without a displacement
  29086. * map set, this value is not applied.
  29087. *
  29088. * @type {number}
  29089. * @default 0
  29090. */
  29091. this.displacementScale = 1;
  29092. /**
  29093. * The offset of the displacement map's values on the mesh's vertices.
  29094. * The bias is added to the scaled sample of the displacement map.
  29095. * Without a displacement map set, this value is not applied.
  29096. *
  29097. * @type {number}
  29098. * @default 0
  29099. */
  29100. this.displacementBias = 0;
  29101. /**
  29102. * Renders the geometry as a wireframe.
  29103. *
  29104. * @type {boolean}
  29105. * @default false
  29106. */
  29107. this.wireframe = false;
  29108. /**
  29109. * Controls the thickness of the wireframe.
  29110. *
  29111. * WebGL and WebGPU ignore this property and always render
  29112. * 1 pixel wide lines.
  29113. *
  29114. * @type {number}
  29115. * @default 1
  29116. */
  29117. this.wireframeLinewidth = 1;
  29118. /**
  29119. * Whether the material is rendered with flat shading or not.
  29120. *
  29121. * @type {boolean}
  29122. * @default false
  29123. */
  29124. this.flatShading = false;
  29125. this.setValues( parameters );
  29126. }
  29127. copy( source ) {
  29128. super.copy( source );
  29129. this.bumpMap = source.bumpMap;
  29130. this.bumpScale = source.bumpScale;
  29131. this.normalMap = source.normalMap;
  29132. this.normalMapType = source.normalMapType;
  29133. this.normalScale.copy( source.normalScale );
  29134. this.displacementMap = source.displacementMap;
  29135. this.displacementScale = source.displacementScale;
  29136. this.displacementBias = source.displacementBias;
  29137. this.wireframe = source.wireframe;
  29138. this.wireframeLinewidth = source.wireframeLinewidth;
  29139. this.flatShading = source.flatShading;
  29140. return this;
  29141. }
  29142. }
  29143. /**
  29144. * A material for non-shiny surfaces, without specular highlights.
  29145. *
  29146. * The material uses a non-physically based [Lambertian]{@link https://en.wikipedia.org/wiki/Lambertian_reflectance}
  29147. * model for calculating reflectance. This can simulate some surfaces (such
  29148. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29149. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29150. * shading.
  29151. *
  29152. * Due to the simplicity of the reflectance and illumination models,
  29153. * performance will be greater when using this material over the
  29154. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29155. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29156. *
  29157. * @augments Material
  29158. */
  29159. class MeshLambertMaterial extends Material {
  29160. /**
  29161. * Constructs a new mesh lambert material.
  29162. *
  29163. * @param {Object} [parameters] - An object with one or more properties
  29164. * defining the material's appearance. Any property of the material
  29165. * (including any property from inherited materials) can be passed
  29166. * in here. Color values can be passed any type of value accepted
  29167. * by {@link Color#set}.
  29168. */
  29169. constructor( parameters ) {
  29170. super();
  29171. /**
  29172. * This flag can be used for type testing.
  29173. *
  29174. * @type {boolean}
  29175. * @readonly
  29176. * @default true
  29177. */
  29178. this.isMeshLambertMaterial = true;
  29179. this.type = 'MeshLambertMaterial';
  29180. /**
  29181. * Color of the material.
  29182. *
  29183. * @type {Color}
  29184. * @default (1,1,1)
  29185. */
  29186. this.color = new Color( 0xffffff ); // diffuse
  29187. /**
  29188. * The color map. May optionally include an alpha channel, typically combined
  29189. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29190. * color is modulated by the diffuse `color`.
  29191. *
  29192. * @type {?Texture}
  29193. * @default null
  29194. */
  29195. this.map = null;
  29196. /**
  29197. * The light map. Requires a second set of UVs.
  29198. *
  29199. * @type {?Texture}
  29200. * @default null
  29201. */
  29202. this.lightMap = null;
  29203. /**
  29204. * Intensity of the baked light.
  29205. *
  29206. * @type {number}
  29207. * @default 1
  29208. */
  29209. this.lightMapIntensity = 1.0;
  29210. /**
  29211. * The red channel of this texture is used as the ambient occlusion map.
  29212. * Requires a second set of UVs.
  29213. *
  29214. * @type {?Texture}
  29215. * @default null
  29216. */
  29217. this.aoMap = null;
  29218. /**
  29219. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29220. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29221. * red channel is also `1`, ambient light is fully occluded on a surface.
  29222. *
  29223. * @type {number}
  29224. * @default 1
  29225. */
  29226. this.aoMapIntensity = 1.0;
  29227. /**
  29228. * Emissive (light) color of the material, essentially a solid color
  29229. * unaffected by other lighting.
  29230. *
  29231. * @type {Color}
  29232. * @default (0,0,0)
  29233. */
  29234. this.emissive = new Color( 0x000000 );
  29235. /**
  29236. * Intensity of the emissive light. Modulates the emissive color.
  29237. *
  29238. * @type {number}
  29239. * @default 1
  29240. */
  29241. this.emissiveIntensity = 1.0;
  29242. /**
  29243. * Set emissive (glow) map. The emissive map color is modulated by the
  29244. * emissive color and the emissive intensity. If you have an emissive map,
  29245. * be sure to set the emissive color to something other than black.
  29246. *
  29247. * @type {?Texture}
  29248. * @default null
  29249. */
  29250. this.emissiveMap = null;
  29251. /**
  29252. * The texture to create a bump map. The black and white values map to the
  29253. * perceived depth in relation to the lights. Bump doesn't actually affect
  29254. * the geometry of the object, only the lighting. If a normal map is defined
  29255. * this will be ignored.
  29256. *
  29257. * @type {?Texture}
  29258. * @default null
  29259. */
  29260. this.bumpMap = null;
  29261. /**
  29262. * How much the bump map affects the material. Typical range is `[0,1]`.
  29263. *
  29264. * @type {number}
  29265. * @default 1
  29266. */
  29267. this.bumpScale = 1;
  29268. /**
  29269. * The texture to create a normal map. The RGB values affect the surface
  29270. * normal for each pixel fragment and change the way the color is lit. Normal
  29271. * maps do not change the actual shape of the surface, only the lighting. In
  29272. * case the material has a normal map authored using the left handed
  29273. * convention, the `y` component of `normalScale` should be negated to compensate
  29274. * for the different handedness.
  29275. *
  29276. * @type {?Texture}
  29277. * @default null
  29278. */
  29279. this.normalMap = null;
  29280. /**
  29281. * The type of normal map.
  29282. *
  29283. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29284. * @default TangentSpaceNormalMap
  29285. */
  29286. this.normalMapType = TangentSpaceNormalMap;
  29287. /**
  29288. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29289. *
  29290. * @type {Vector2}
  29291. * @default (1,1)
  29292. */
  29293. this.normalScale = new Vector2( 1, 1 );
  29294. /**
  29295. * The displacement map affects the position of the mesh's vertices. Unlike
  29296. * other maps which only affect the light and shade of the material the
  29297. * displaced vertices can cast shadows, block other objects, and otherwise
  29298. * act as real geometry. The displacement texture is an image where the value
  29299. * of each pixel (white being the highest) is mapped against, and
  29300. * repositions, the vertices of the mesh.
  29301. *
  29302. * @type {?Texture}
  29303. * @default null
  29304. */
  29305. this.displacementMap = null;
  29306. /**
  29307. * How much the displacement map affects the mesh (where black is no
  29308. * displacement, and white is maximum displacement). Without a displacement
  29309. * map set, this value is not applied.
  29310. *
  29311. * @type {number}
  29312. * @default 0
  29313. */
  29314. this.displacementScale = 1;
  29315. /**
  29316. * The offset of the displacement map's values on the mesh's vertices.
  29317. * The bias is added to the scaled sample of the displacement map.
  29318. * Without a displacement map set, this value is not applied.
  29319. *
  29320. * @type {number}
  29321. * @default 0
  29322. */
  29323. this.displacementBias = 0;
  29324. /**
  29325. * Specular map used by the material.
  29326. *
  29327. * @type {?Texture}
  29328. * @default null
  29329. */
  29330. this.specularMap = null;
  29331. /**
  29332. * The alpha map is a grayscale texture that controls the opacity across the
  29333. * surface (black: fully transparent; white: fully opaque).
  29334. *
  29335. * Only the color of the texture is used, ignoring the alpha channel if one
  29336. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29337. * when sampling this texture due to the extra bit of precision provided for
  29338. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29339. * luminance/alpha textures will also still work as expected.
  29340. *
  29341. * @type {?Texture}
  29342. * @default null
  29343. */
  29344. this.alphaMap = null;
  29345. /**
  29346. * The environment map.
  29347. *
  29348. * @type {?Texture}
  29349. * @default null
  29350. */
  29351. this.envMap = null;
  29352. /**
  29353. * The rotation of the environment map in radians.
  29354. *
  29355. * @type {Euler}
  29356. * @default (0,0,0)
  29357. */
  29358. this.envMapRotation = new Euler();
  29359. /**
  29360. * How to combine the result of the surface's color with the environment map, if any.
  29361. *
  29362. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29363. * blend between the two colors.
  29364. *
  29365. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29366. * @default MultiplyOperation
  29367. */
  29368. this.combine = MultiplyOperation;
  29369. /**
  29370. * How much the environment map affects the surface.
  29371. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29372. *
  29373. * @type {number}
  29374. * @default 1
  29375. */
  29376. this.reflectivity = 1;
  29377. /**
  29378. * The index of refraction (IOR) of air (approximately 1) divided by the
  29379. * index of refraction of the material. It is used with environment mapping
  29380. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29381. * The refraction ratio should not exceed `1`.
  29382. *
  29383. * @type {number}
  29384. * @default 0.98
  29385. */
  29386. this.refractionRatio = 0.98;
  29387. /**
  29388. * Renders the geometry as a wireframe.
  29389. *
  29390. * @type {boolean}
  29391. * @default false
  29392. */
  29393. this.wireframe = false;
  29394. /**
  29395. * Controls the thickness of the wireframe.
  29396. *
  29397. * Can only be used with {@link SVGRenderer}.
  29398. *
  29399. * @type {number}
  29400. * @default 1
  29401. */
  29402. this.wireframeLinewidth = 1;
  29403. /**
  29404. * Defines appearance of wireframe ends.
  29405. *
  29406. * Can only be used with {@link SVGRenderer}.
  29407. *
  29408. * @type {('round'|'bevel'|'miter')}
  29409. * @default 'round'
  29410. */
  29411. this.wireframeLinecap = 'round';
  29412. /**
  29413. * Defines appearance of wireframe joints.
  29414. *
  29415. * Can only be used with {@link SVGRenderer}.
  29416. *
  29417. * @type {('round'|'bevel'|'miter')}
  29418. * @default 'round'
  29419. */
  29420. this.wireframeLinejoin = 'round';
  29421. /**
  29422. * Whether the material is rendered with flat shading or not.
  29423. *
  29424. * @type {boolean}
  29425. * @default false
  29426. */
  29427. this.flatShading = false;
  29428. /**
  29429. * Whether the material is affected by fog or not.
  29430. *
  29431. * @type {boolean}
  29432. * @default true
  29433. */
  29434. this.fog = true;
  29435. this.setValues( parameters );
  29436. }
  29437. copy( source ) {
  29438. super.copy( source );
  29439. this.color.copy( source.color );
  29440. this.map = source.map;
  29441. this.lightMap = source.lightMap;
  29442. this.lightMapIntensity = source.lightMapIntensity;
  29443. this.aoMap = source.aoMap;
  29444. this.aoMapIntensity = source.aoMapIntensity;
  29445. this.emissive.copy( source.emissive );
  29446. this.emissiveMap = source.emissiveMap;
  29447. this.emissiveIntensity = source.emissiveIntensity;
  29448. this.bumpMap = source.bumpMap;
  29449. this.bumpScale = source.bumpScale;
  29450. this.normalMap = source.normalMap;
  29451. this.normalMapType = source.normalMapType;
  29452. this.normalScale.copy( source.normalScale );
  29453. this.displacementMap = source.displacementMap;
  29454. this.displacementScale = source.displacementScale;
  29455. this.displacementBias = source.displacementBias;
  29456. this.specularMap = source.specularMap;
  29457. this.alphaMap = source.alphaMap;
  29458. this.envMap = source.envMap;
  29459. this.envMapRotation.copy( source.envMapRotation );
  29460. this.combine = source.combine;
  29461. this.reflectivity = source.reflectivity;
  29462. this.refractionRatio = source.refractionRatio;
  29463. this.wireframe = source.wireframe;
  29464. this.wireframeLinewidth = source.wireframeLinewidth;
  29465. this.wireframeLinecap = source.wireframeLinecap;
  29466. this.wireframeLinejoin = source.wireframeLinejoin;
  29467. this.flatShading = source.flatShading;
  29468. this.fog = source.fog;
  29469. return this;
  29470. }
  29471. }
  29472. /**
  29473. * A material for drawing geometry by depth. Depth is based off of the camera
  29474. * near and far plane. White is nearest, black is farthest.
  29475. *
  29476. * @augments Material
  29477. */
  29478. class MeshDepthMaterial extends Material {
  29479. /**
  29480. * Constructs a new mesh depth material.
  29481. *
  29482. * @param {Object} [parameters] - An object with one or more properties
  29483. * defining the material's appearance. Any property of the material
  29484. * (including any property from inherited materials) can be passed
  29485. * in here. Color values can be passed any type of value accepted
  29486. * by {@link Color#set}.
  29487. */
  29488. constructor( parameters ) {
  29489. super();
  29490. /**
  29491. * This flag can be used for type testing.
  29492. *
  29493. * @type {boolean}
  29494. * @readonly
  29495. * @default true
  29496. */
  29497. this.isMeshDepthMaterial = true;
  29498. this.type = 'MeshDepthMaterial';
  29499. /**
  29500. * Type for depth packing.
  29501. *
  29502. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  29503. * @default BasicDepthPacking
  29504. */
  29505. this.depthPacking = BasicDepthPacking;
  29506. /**
  29507. * The color map. May optionally include an alpha channel, typically combined
  29508. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29509. *
  29510. * @type {?Texture}
  29511. * @default null
  29512. */
  29513. this.map = null;
  29514. /**
  29515. * The alpha map is a grayscale texture that controls the opacity across the
  29516. * surface (black: fully transparent; white: fully opaque).
  29517. *
  29518. * Only the color of the texture is used, ignoring the alpha channel if one
  29519. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29520. * when sampling this texture due to the extra bit of precision provided for
  29521. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29522. * luminance/alpha textures will also still work as expected.
  29523. *
  29524. * @type {?Texture}
  29525. * @default null
  29526. */
  29527. this.alphaMap = null;
  29528. /**
  29529. * The displacement map affects the position of the mesh's vertices. Unlike
  29530. * other maps which only affect the light and shade of the material the
  29531. * displaced vertices can cast shadows, block other objects, and otherwise
  29532. * act as real geometry. The displacement texture is an image where the value
  29533. * of each pixel (white being the highest) is mapped against, and
  29534. * repositions, the vertices of the mesh.
  29535. *
  29536. * @type {?Texture}
  29537. * @default null
  29538. */
  29539. this.displacementMap = null;
  29540. /**
  29541. * How much the displacement map affects the mesh (where black is no
  29542. * displacement, and white is maximum displacement). Without a displacement
  29543. * map set, this value is not applied.
  29544. *
  29545. * @type {number}
  29546. * @default 0
  29547. */
  29548. this.displacementScale = 1;
  29549. /**
  29550. * The offset of the displacement map's values on the mesh's vertices.
  29551. * The bias is added to the scaled sample of the displacement map.
  29552. * Without a displacement map set, this value is not applied.
  29553. *
  29554. * @type {number}
  29555. * @default 0
  29556. */
  29557. this.displacementBias = 0;
  29558. /**
  29559. * Renders the geometry as a wireframe.
  29560. *
  29561. * @type {boolean}
  29562. * @default false
  29563. */
  29564. this.wireframe = false;
  29565. /**
  29566. * Controls the thickness of the wireframe.
  29567. *
  29568. * WebGL and WebGPU ignore this property and always render
  29569. * 1 pixel wide lines.
  29570. *
  29571. * @type {number}
  29572. * @default 1
  29573. */
  29574. this.wireframeLinewidth = 1;
  29575. this.setValues( parameters );
  29576. }
  29577. copy( source ) {
  29578. super.copy( source );
  29579. this.depthPacking = source.depthPacking;
  29580. this.map = source.map;
  29581. this.alphaMap = source.alphaMap;
  29582. this.displacementMap = source.displacementMap;
  29583. this.displacementScale = source.displacementScale;
  29584. this.displacementBias = source.displacementBias;
  29585. this.wireframe = source.wireframe;
  29586. this.wireframeLinewidth = source.wireframeLinewidth;
  29587. return this;
  29588. }
  29589. }
  29590. /**
  29591. * A material used internally for implementing shadow mapping with
  29592. * point lights.
  29593. *
  29594. * Can also be used to customize the shadow casting of an object by assigning
  29595. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  29596. * The following examples demonstrates this approach in order to ensure
  29597. * transparent parts of objects do no cast shadows.
  29598. *
  29599. * @augments Material
  29600. */
  29601. class MeshDistanceMaterial extends Material {
  29602. /**
  29603. * Constructs a new mesh distance material.
  29604. *
  29605. * @param {Object} [parameters] - An object with one or more properties
  29606. * defining the material's appearance. Any property of the material
  29607. * (including any property from inherited materials) can be passed
  29608. * in here. Color values can be passed any type of value accepted
  29609. * by {@link Color#set}.
  29610. */
  29611. constructor( parameters ) {
  29612. super();
  29613. /**
  29614. * This flag can be used for type testing.
  29615. *
  29616. * @type {boolean}
  29617. * @readonly
  29618. * @default true
  29619. */
  29620. this.isMeshDistanceMaterial = true;
  29621. this.type = 'MeshDistanceMaterial';
  29622. /**
  29623. * The color map. May optionally include an alpha channel, typically combined
  29624. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29625. *
  29626. * @type {?Texture}
  29627. * @default null
  29628. */
  29629. this.map = null;
  29630. /**
  29631. * The alpha map is a grayscale texture that controls the opacity across the
  29632. * surface (black: fully transparent; white: fully opaque).
  29633. *
  29634. * Only the color of the texture is used, ignoring the alpha channel if one
  29635. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29636. * when sampling this texture due to the extra bit of precision provided for
  29637. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29638. * luminance/alpha textures will also still work as expected.
  29639. *
  29640. * @type {?Texture}
  29641. * @default null
  29642. */
  29643. this.alphaMap = null;
  29644. /**
  29645. * The displacement map affects the position of the mesh's vertices. Unlike
  29646. * other maps which only affect the light and shade of the material the
  29647. * displaced vertices can cast shadows, block other objects, and otherwise
  29648. * act as real geometry. The displacement texture is an image where the value
  29649. * of each pixel (white being the highest) is mapped against, and
  29650. * repositions, the vertices of the mesh.
  29651. *
  29652. * @type {?Texture}
  29653. * @default null
  29654. */
  29655. this.displacementMap = null;
  29656. /**
  29657. * How much the displacement map affects the mesh (where black is no
  29658. * displacement, and white is maximum displacement). Without a displacement
  29659. * map set, this value is not applied.
  29660. *
  29661. * @type {number}
  29662. * @default 0
  29663. */
  29664. this.displacementScale = 1;
  29665. /**
  29666. * The offset of the displacement map's values on the mesh's vertices.
  29667. * The bias is added to the scaled sample of the displacement map.
  29668. * Without a displacement map set, this value is not applied.
  29669. *
  29670. * @type {number}
  29671. * @default 0
  29672. */
  29673. this.displacementBias = 0;
  29674. this.setValues( parameters );
  29675. }
  29676. copy( source ) {
  29677. super.copy( source );
  29678. this.map = source.map;
  29679. this.alphaMap = source.alphaMap;
  29680. this.displacementMap = source.displacementMap;
  29681. this.displacementScale = source.displacementScale;
  29682. this.displacementBias = source.displacementBias;
  29683. return this;
  29684. }
  29685. }
  29686. /**
  29687. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  29688. * material color and shading.
  29689. *
  29690. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  29691. * baked lighting. It will cast a shadow onto an object that receives shadows
  29692. * (and shadow clipping works), but it will not self-shadow or receive
  29693. * shadows.
  29694. *
  29695. * @augments Material
  29696. */
  29697. class MeshMatcapMaterial extends Material {
  29698. /**
  29699. * Constructs a new mesh matcap material.
  29700. *
  29701. * @param {Object} [parameters] - An object with one or more properties
  29702. * defining the material's appearance. Any property of the material
  29703. * (including any property from inherited materials) can be passed
  29704. * in here. Color values can be passed any type of value accepted
  29705. * by {@link Color#set}.
  29706. */
  29707. constructor( parameters ) {
  29708. super();
  29709. /**
  29710. * This flag can be used for type testing.
  29711. *
  29712. * @type {boolean}
  29713. * @readonly
  29714. * @default true
  29715. */
  29716. this.isMeshMatcapMaterial = true;
  29717. this.defines = { 'MATCAP': '' };
  29718. this.type = 'MeshMatcapMaterial';
  29719. /**
  29720. * Color of the material.
  29721. *
  29722. * @type {Color}
  29723. * @default (1,1,1)
  29724. */
  29725. this.color = new Color( 0xffffff ); // diffuse
  29726. /**
  29727. * The matcap map.
  29728. *
  29729. * @type {?Texture}
  29730. * @default null
  29731. */
  29732. this.matcap = null;
  29733. /**
  29734. * The color map. May optionally include an alpha channel, typically combined
  29735. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29736. * color is modulated by the diffuse `color`.
  29737. *
  29738. * @type {?Texture}
  29739. * @default null
  29740. */
  29741. this.map = null;
  29742. /**
  29743. * The texture to create a bump map. The black and white values map to the
  29744. * perceived depth in relation to the lights. Bump doesn't actually affect
  29745. * the geometry of the object, only the lighting. If a normal map is defined
  29746. * this will be ignored.
  29747. *
  29748. * @type {?Texture}
  29749. * @default null
  29750. */
  29751. this.bumpMap = null;
  29752. /**
  29753. * How much the bump map affects the material. Typical range is `[0,1]`.
  29754. *
  29755. * @type {number}
  29756. * @default 1
  29757. */
  29758. this.bumpScale = 1;
  29759. /**
  29760. * The texture to create a normal map. The RGB values affect the surface
  29761. * normal for each pixel fragment and change the way the color is lit. Normal
  29762. * maps do not change the actual shape of the surface, only the lighting. In
  29763. * case the material has a normal map authored using the left handed
  29764. * convention, the `y` component of `normalScale` should be negated to compensate
  29765. * for the different handedness.
  29766. *
  29767. * @type {?Texture}
  29768. * @default null
  29769. */
  29770. this.normalMap = null;
  29771. /**
  29772. * The type of normal map.
  29773. *
  29774. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29775. * @default TangentSpaceNormalMap
  29776. */
  29777. this.normalMapType = TangentSpaceNormalMap;
  29778. /**
  29779. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29780. *
  29781. * @type {Vector2}
  29782. * @default (1,1)
  29783. */
  29784. this.normalScale = new Vector2( 1, 1 );
  29785. /**
  29786. * The displacement map affects the position of the mesh's vertices. Unlike
  29787. * other maps which only affect the light and shade of the material the
  29788. * displaced vertices can cast shadows, block other objects, and otherwise
  29789. * act as real geometry. The displacement texture is an image where the value
  29790. * of each pixel (white being the highest) is mapped against, and
  29791. * repositions, the vertices of the mesh.
  29792. *
  29793. * @type {?Texture}
  29794. * @default null
  29795. */
  29796. this.displacementMap = null;
  29797. /**
  29798. * How much the displacement map affects the mesh (where black is no
  29799. * displacement, and white is maximum displacement). Without a displacement
  29800. * map set, this value is not applied.
  29801. *
  29802. * @type {number}
  29803. * @default 0
  29804. */
  29805. this.displacementScale = 1;
  29806. /**
  29807. * The offset of the displacement map's values on the mesh's vertices.
  29808. * The bias is added to the scaled sample of the displacement map.
  29809. * Without a displacement map set, this value is not applied.
  29810. *
  29811. * @type {number}
  29812. * @default 0
  29813. */
  29814. this.displacementBias = 0;
  29815. /**
  29816. * The alpha map is a grayscale texture that controls the opacity across the
  29817. * surface (black: fully transparent; white: fully opaque).
  29818. *
  29819. * Only the color of the texture is used, ignoring the alpha channel if one
  29820. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29821. * when sampling this texture due to the extra bit of precision provided for
  29822. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29823. * luminance/alpha textures will also still work as expected.
  29824. *
  29825. * @type {?Texture}
  29826. * @default null
  29827. */
  29828. this.alphaMap = null;
  29829. /**
  29830. * Whether the material is rendered with flat shading or not.
  29831. *
  29832. * @type {boolean}
  29833. * @default false
  29834. */
  29835. this.flatShading = false;
  29836. /**
  29837. * Whether the material is affected by fog or not.
  29838. *
  29839. * @type {boolean}
  29840. * @default true
  29841. */
  29842. this.fog = true;
  29843. this.setValues( parameters );
  29844. }
  29845. copy( source ) {
  29846. super.copy( source );
  29847. this.defines = { 'MATCAP': '' };
  29848. this.color.copy( source.color );
  29849. this.matcap = source.matcap;
  29850. this.map = source.map;
  29851. this.bumpMap = source.bumpMap;
  29852. this.bumpScale = source.bumpScale;
  29853. this.normalMap = source.normalMap;
  29854. this.normalMapType = source.normalMapType;
  29855. this.normalScale.copy( source.normalScale );
  29856. this.displacementMap = source.displacementMap;
  29857. this.displacementScale = source.displacementScale;
  29858. this.displacementBias = source.displacementBias;
  29859. this.alphaMap = source.alphaMap;
  29860. this.flatShading = source.flatShading;
  29861. this.fog = source.fog;
  29862. return this;
  29863. }
  29864. }
  29865. /**
  29866. * A material for rendering line primitives.
  29867. *
  29868. * Materials define the appearance of renderable 3D objects.
  29869. *
  29870. * ```js
  29871. * const material = new THREE.LineDashedMaterial( {
  29872. * color: 0xffffff,
  29873. * scale: 1,
  29874. * dashSize: 3,
  29875. * gapSize: 1,
  29876. * } );
  29877. * ```
  29878. *
  29879. * @augments LineBasicMaterial
  29880. */
  29881. class LineDashedMaterial extends LineBasicMaterial {
  29882. /**
  29883. * Constructs a new line dashed material.
  29884. *
  29885. * @param {Object} [parameters] - An object with one or more properties
  29886. * defining the material's appearance. Any property of the material
  29887. * (including any property from inherited materials) can be passed
  29888. * in here. Color values can be passed any type of value accepted
  29889. * by {@link Color#set}.
  29890. */
  29891. constructor( parameters ) {
  29892. super();
  29893. /**
  29894. * This flag can be used for type testing.
  29895. *
  29896. * @type {boolean}
  29897. * @readonly
  29898. * @default true
  29899. */
  29900. this.isLineDashedMaterial = true;
  29901. this.type = 'LineDashedMaterial';
  29902. /**
  29903. * The scale of the dashed part of a line.
  29904. *
  29905. * @type {number}
  29906. * @default 1
  29907. */
  29908. this.scale = 1;
  29909. /**
  29910. * The size of the dash. This is both the gap with the stroke.
  29911. *
  29912. * @type {number}
  29913. * @default 3
  29914. */
  29915. this.dashSize = 3;
  29916. /**
  29917. * The size of the gap.
  29918. *
  29919. * @type {number}
  29920. * @default 1
  29921. */
  29922. this.gapSize = 1;
  29923. this.setValues( parameters );
  29924. }
  29925. copy( source ) {
  29926. super.copy( source );
  29927. this.scale = source.scale;
  29928. this.dashSize = source.dashSize;
  29929. this.gapSize = source.gapSize;
  29930. return this;
  29931. }
  29932. }
  29933. /**
  29934. * Converts an array to a specific type.
  29935. *
  29936. * @param {TypedArray|Array} array - The array to convert.
  29937. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  29938. * @return {TypedArray} The converted array.
  29939. */
  29940. function convertArray( array, type ) {
  29941. if ( ! array || array.constructor === type ) return array;
  29942. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  29943. return new type( array ); // create typed array
  29944. }
  29945. return Array.prototype.slice.call( array ); // create Array
  29946. }
  29947. /**
  29948. * Returns `true` if the given object is a typed array.
  29949. *
  29950. * @param {any} object - The object to check.
  29951. * @return {boolean} Whether the given object is a typed array.
  29952. */
  29953. function isTypedArray( object ) {
  29954. return ArrayBuffer.isView( object ) && ! ( object instanceof DataView );
  29955. }
  29956. /**
  29957. * Returns an array by which times and values can be sorted.
  29958. *
  29959. * @param {Array<number>} times - The keyframe time values.
  29960. * @return {Array<number>} The array.
  29961. */
  29962. function getKeyframeOrder( times ) {
  29963. function compareTime( i, j ) {
  29964. return times[ i ] - times[ j ];
  29965. }
  29966. const n = times.length;
  29967. const result = new Array( n );
  29968. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  29969. result.sort( compareTime );
  29970. return result;
  29971. }
  29972. /**
  29973. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  29974. *
  29975. * @param {Array<number>} values - The values to sort.
  29976. * @param {number} stride - The stride.
  29977. * @param {Array<number>} order - The sort order.
  29978. * @return {Array<number>} The sorted values.
  29979. */
  29980. function sortedArray( values, stride, order ) {
  29981. const nValues = values.length;
  29982. const result = new values.constructor( nValues );
  29983. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  29984. const srcOffset = order[ i ] * stride;
  29985. for ( let j = 0; j !== stride; ++ j ) {
  29986. result[ dstOffset ++ ] = values[ srcOffset + j ];
  29987. }
  29988. }
  29989. return result;
  29990. }
  29991. /**
  29992. * Used for parsing AOS keyframe formats.
  29993. *
  29994. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  29995. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  29996. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  29997. * @param {string} valuePropertyName - The name of the property to use.
  29998. */
  29999. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30000. let i = 1, key = jsonKeys[ 0 ];
  30001. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  30002. key = jsonKeys[ i ++ ];
  30003. }
  30004. if ( key === undefined ) return; // no data
  30005. let value = key[ valuePropertyName ];
  30006. if ( value === undefined ) return; // no data
  30007. if ( Array.isArray( value ) ) {
  30008. do {
  30009. value = key[ valuePropertyName ];
  30010. if ( value !== undefined ) {
  30011. times.push( key.time );
  30012. values.push( ...value ); // push all elements
  30013. }
  30014. key = jsonKeys[ i ++ ];
  30015. } while ( key !== undefined );
  30016. } else if ( value.toArray !== undefined ) {
  30017. // ...assume THREE.Math-ish
  30018. do {
  30019. value = key[ valuePropertyName ];
  30020. if ( value !== undefined ) {
  30021. times.push( key.time );
  30022. value.toArray( values, values.length );
  30023. }
  30024. key = jsonKeys[ i ++ ];
  30025. } while ( key !== undefined );
  30026. } else {
  30027. // otherwise push as-is
  30028. do {
  30029. value = key[ valuePropertyName ];
  30030. if ( value !== undefined ) {
  30031. times.push( key.time );
  30032. values.push( value );
  30033. }
  30034. key = jsonKeys[ i ++ ];
  30035. } while ( key !== undefined );
  30036. }
  30037. }
  30038. /**
  30039. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30040. *
  30041. * @param {AnimationClip} sourceClip - The values to sort.
  30042. * @param {string} name - The name of the clip.
  30043. * @param {number} startFrame - The start frame.
  30044. * @param {number} endFrame - The end frame.
  30045. * @param {number} [fps=30] - The FPS.
  30046. * @return {AnimationClip} The new sub clip.
  30047. */
  30048. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30049. const clip = sourceClip.clone();
  30050. clip.name = name;
  30051. const tracks = [];
  30052. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30053. const track = clip.tracks[ i ];
  30054. const valueSize = track.getValueSize();
  30055. const times = [];
  30056. const values = [];
  30057. for ( let j = 0; j < track.times.length; ++ j ) {
  30058. const frame = track.times[ j ] * fps;
  30059. if ( frame < startFrame || frame >= endFrame ) continue;
  30060. times.push( track.times[ j ] );
  30061. for ( let k = 0; k < valueSize; ++ k ) {
  30062. values.push( track.values[ j * valueSize + k ] );
  30063. }
  30064. }
  30065. if ( times.length === 0 ) continue;
  30066. track.times = convertArray( times, track.times.constructor );
  30067. track.values = convertArray( values, track.values.constructor );
  30068. tracks.push( track );
  30069. }
  30070. clip.tracks = tracks;
  30071. // find minimum .times value across all tracks in the trimmed clip
  30072. let minStartTime = Infinity;
  30073. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30074. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  30075. minStartTime = clip.tracks[ i ].times[ 0 ];
  30076. }
  30077. }
  30078. // shift all tracks such that clip begins at t=0
  30079. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30080. clip.tracks[ i ].shift( -1 * minStartTime );
  30081. }
  30082. clip.resetDuration();
  30083. return clip;
  30084. }
  30085. /**
  30086. * Converts the keyframes of the given animation clip to an additive format.
  30087. *
  30088. * @param {AnimationClip} targetClip - The clip to make additive.
  30089. * @param {number} [referenceFrame=0] - The reference frame.
  30090. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30091. * @param {number} [fps=30] - The FPS.
  30092. * @return {AnimationClip} The updated clip which is now additive.
  30093. */
  30094. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30095. if ( fps <= 0 ) fps = 30;
  30096. const numTracks = referenceClip.tracks.length;
  30097. const referenceTime = referenceFrame / fps;
  30098. // Make each track's values relative to the values at the reference frame
  30099. for ( let i = 0; i < numTracks; ++ i ) {
  30100. const referenceTrack = referenceClip.tracks[ i ];
  30101. const referenceTrackType = referenceTrack.ValueTypeName;
  30102. // Skip this track if it's non-numeric
  30103. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  30104. // Find the track in the target clip whose name and type matches the reference track
  30105. const targetTrack = targetClip.tracks.find( function ( track ) {
  30106. return track.name === referenceTrack.name
  30107. && track.ValueTypeName === referenceTrackType;
  30108. } );
  30109. if ( targetTrack === undefined ) continue;
  30110. let referenceOffset = 0;
  30111. const referenceValueSize = referenceTrack.getValueSize();
  30112. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30113. referenceOffset = referenceValueSize / 3;
  30114. }
  30115. let targetOffset = 0;
  30116. const targetValueSize = targetTrack.getValueSize();
  30117. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30118. targetOffset = targetValueSize / 3;
  30119. }
  30120. const lastIndex = referenceTrack.times.length - 1;
  30121. let referenceValue;
  30122. // Find the value to subtract out of the track
  30123. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  30124. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  30125. const startIndex = referenceOffset;
  30126. const endIndex = referenceValueSize - referenceOffset;
  30127. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30128. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30129. // Reference frame is after the last keyframe, so just use the last keyframe
  30130. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30131. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30132. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30133. } else {
  30134. // Interpolate to the reference value
  30135. const interpolant = referenceTrack.createInterpolant();
  30136. const startIndex = referenceOffset;
  30137. const endIndex = referenceValueSize - referenceOffset;
  30138. interpolant.evaluate( referenceTime );
  30139. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30140. }
  30141. // Conjugate the quaternion
  30142. if ( referenceTrackType === 'quaternion' ) {
  30143. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30144. referenceQuat.toArray( referenceValue );
  30145. }
  30146. // Subtract the reference value from all of the track values
  30147. const numTimes = targetTrack.times.length;
  30148. for ( let j = 0; j < numTimes; ++ j ) {
  30149. const valueStart = j * targetValueSize + targetOffset;
  30150. if ( referenceTrackType === 'quaternion' ) {
  30151. // Multiply the conjugate for quaternion track types
  30152. Quaternion.multiplyQuaternionsFlat(
  30153. targetTrack.values,
  30154. valueStart,
  30155. referenceValue,
  30156. 0,
  30157. targetTrack.values,
  30158. valueStart
  30159. );
  30160. } else {
  30161. const valueEnd = targetValueSize - targetOffset * 2;
  30162. // Subtract each value for all other numeric track types
  30163. for ( let k = 0; k < valueEnd; ++ k ) {
  30164. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30165. }
  30166. }
  30167. }
  30168. }
  30169. targetClip.blendMode = AdditiveAnimationBlendMode;
  30170. return targetClip;
  30171. }
  30172. /**
  30173. * A class with various methods to assist with animations.
  30174. *
  30175. * @hideconstructor
  30176. */
  30177. class AnimationUtils {
  30178. /**
  30179. * Converts an array to a specific type
  30180. *
  30181. * @static
  30182. * @param {TypedArray|Array} array - The array to convert.
  30183. * @param {TypedArray.constructor} type - The constructor of a type array.
  30184. * @return {TypedArray} The converted array
  30185. */
  30186. static convertArray( array, type ) {
  30187. return convertArray( array, type );
  30188. }
  30189. /**
  30190. * Returns `true` if the given object is a typed array.
  30191. *
  30192. * @static
  30193. * @param {any} object - The object to check.
  30194. * @return {boolean} Whether the given object is a typed array.
  30195. */
  30196. static isTypedArray( object ) {
  30197. return isTypedArray( object );
  30198. }
  30199. /**
  30200. * Returns an array by which times and values can be sorted.
  30201. *
  30202. * @static
  30203. * @param {Array<number>} times - The keyframe time values.
  30204. * @return {Array<number>} The array.
  30205. */
  30206. static getKeyframeOrder( times ) {
  30207. return getKeyframeOrder( times );
  30208. }
  30209. /**
  30210. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30211. *
  30212. * @static
  30213. * @param {Array<number>} values - The values to sort.
  30214. * @param {number} stride - The stride.
  30215. * @param {Array<number>} order - The sort order.
  30216. * @return {Array<number>} The sorted values.
  30217. */
  30218. static sortedArray( values, stride, order ) {
  30219. return sortedArray( values, stride, order );
  30220. }
  30221. /**
  30222. * Used for parsing AOS keyframe formats.
  30223. *
  30224. * @static
  30225. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30226. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30227. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30228. * @param {string} valuePropertyName - The name of the property to use.
  30229. */
  30230. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30231. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30232. }
  30233. /**
  30234. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30235. *
  30236. * @static
  30237. * @param {AnimationClip} sourceClip - The values to sort.
  30238. * @param {string} name - The name of the clip.
  30239. * @param {number} startFrame - The start frame.
  30240. * @param {number} endFrame - The end frame.
  30241. * @param {number} [fps=30] - The FPS.
  30242. * @return {AnimationClip} The new sub clip.
  30243. */
  30244. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30245. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30246. }
  30247. /**
  30248. * Converts the keyframes of the given animation clip to an additive format.
  30249. *
  30250. * @static
  30251. * @param {AnimationClip} targetClip - The clip to make additive.
  30252. * @param {number} [referenceFrame=0] - The reference frame.
  30253. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30254. * @param {number} [fps=30] - The FPS.
  30255. * @return {AnimationClip} The updated clip which is now additive.
  30256. */
  30257. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30258. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30259. }
  30260. }
  30261. /**
  30262. * Abstract base class of interpolants over parametric samples.
  30263. *
  30264. * The parameter domain is one dimensional, typically the time or a path
  30265. * along a curve defined by the data.
  30266. *
  30267. * The sample values can have any dimensionality and derived classes may
  30268. * apply special interpretations to the data.
  30269. *
  30270. * This class provides the interval seek in a Template Method, deferring
  30271. * the actual interpolation to derived classes.
  30272. *
  30273. * Time complexity is O(1) for linear access crossing at most two points
  30274. * and O(log N) for random access, where N is the number of positions.
  30275. *
  30276. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30277. *
  30278. * @abstract
  30279. */
  30280. class Interpolant {
  30281. /**
  30282. * Constructs a new interpolant.
  30283. *
  30284. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30285. * @param {TypedArray} sampleValues - The sample values.
  30286. * @param {number} sampleSize - The sample size
  30287. * @param {TypedArray} [resultBuffer] - The result buffer.
  30288. */
  30289. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30290. /**
  30291. * The parameter positions.
  30292. *
  30293. * @type {TypedArray}
  30294. */
  30295. this.parameterPositions = parameterPositions;
  30296. /**
  30297. * A cache index.
  30298. *
  30299. * @private
  30300. * @type {number}
  30301. * @default 0
  30302. */
  30303. this._cachedIndex = 0;
  30304. /**
  30305. * The result buffer.
  30306. *
  30307. * @type {TypedArray}
  30308. */
  30309. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30310. /**
  30311. * The sample values.
  30312. *
  30313. * @type {TypedArray}
  30314. */
  30315. this.sampleValues = sampleValues;
  30316. /**
  30317. * The value size.
  30318. *
  30319. * @type {TypedArray}
  30320. */
  30321. this.valueSize = sampleSize;
  30322. /**
  30323. * The interpolation settings.
  30324. *
  30325. * @type {?Object}
  30326. * @default null
  30327. */
  30328. this.settings = null;
  30329. /**
  30330. * The default settings object.
  30331. *
  30332. * @type {Object}
  30333. */
  30334. this.DefaultSettings_ = {};
  30335. }
  30336. /**
  30337. * Evaluate the interpolant at position `t`.
  30338. *
  30339. * @param {number} t - The interpolation factor.
  30340. * @return {TypedArray} The result buffer.
  30341. */
  30342. evaluate( t ) {
  30343. const pp = this.parameterPositions;
  30344. let i1 = this._cachedIndex,
  30345. t1 = pp[ i1 ],
  30346. t0 = pp[ i1 - 1 ];
  30347. validate_interval: {
  30348. seek: {
  30349. let right;
  30350. linear_scan: {
  30351. //- See http://jsperf.com/comparison-to-undefined/3
  30352. //- slower code:
  30353. //-
  30354. //- if ( t >= t1 || t1 === undefined ) {
  30355. forward_scan: if ( ! ( t < t1 ) ) {
  30356. for ( let giveUpAt = i1 + 2; ; ) {
  30357. if ( t1 === undefined ) {
  30358. if ( t < t0 ) break forward_scan;
  30359. // after end
  30360. i1 = pp.length;
  30361. this._cachedIndex = i1;
  30362. return this.copySampleValue_( i1 - 1 );
  30363. }
  30364. if ( i1 === giveUpAt ) break; // this loop
  30365. t0 = t1;
  30366. t1 = pp[ ++ i1 ];
  30367. if ( t < t1 ) {
  30368. // we have arrived at the sought interval
  30369. break seek;
  30370. }
  30371. }
  30372. // prepare binary search on the right side of the index
  30373. right = pp.length;
  30374. break linear_scan;
  30375. }
  30376. //- slower code:
  30377. //- if ( t < t0 || t0 === undefined ) {
  30378. if ( ! ( t >= t0 ) ) {
  30379. // looping?
  30380. const t1global = pp[ 1 ];
  30381. if ( t < t1global ) {
  30382. i1 = 2; // + 1, using the scan for the details
  30383. t0 = t1global;
  30384. }
  30385. // linear reverse scan
  30386. for ( let giveUpAt = i1 - 2; ; ) {
  30387. if ( t0 === undefined ) {
  30388. // before start
  30389. this._cachedIndex = 0;
  30390. return this.copySampleValue_( 0 );
  30391. }
  30392. if ( i1 === giveUpAt ) break; // this loop
  30393. t1 = t0;
  30394. t0 = pp[ -- i1 - 1 ];
  30395. if ( t >= t0 ) {
  30396. // we have arrived at the sought interval
  30397. break seek;
  30398. }
  30399. }
  30400. // prepare binary search on the left side of the index
  30401. right = i1;
  30402. i1 = 0;
  30403. break linear_scan;
  30404. }
  30405. // the interval is valid
  30406. break validate_interval;
  30407. } // linear scan
  30408. // binary search
  30409. while ( i1 < right ) {
  30410. const mid = ( i1 + right ) >>> 1;
  30411. if ( t < pp[ mid ] ) {
  30412. right = mid;
  30413. } else {
  30414. i1 = mid + 1;
  30415. }
  30416. }
  30417. t1 = pp[ i1 ];
  30418. t0 = pp[ i1 - 1 ];
  30419. // check boundary cases, again
  30420. if ( t0 === undefined ) {
  30421. this._cachedIndex = 0;
  30422. return this.copySampleValue_( 0 );
  30423. }
  30424. if ( t1 === undefined ) {
  30425. i1 = pp.length;
  30426. this._cachedIndex = i1;
  30427. return this.copySampleValue_( i1 - 1 );
  30428. }
  30429. } // seek
  30430. this._cachedIndex = i1;
  30431. this.intervalChanged_( i1, t0, t1 );
  30432. } // validate_interval
  30433. return this.interpolate_( i1, t0, t, t1 );
  30434. }
  30435. /**
  30436. * Returns the interpolation settings.
  30437. *
  30438. * @return {Object} The interpolation settings.
  30439. */
  30440. getSettings_() {
  30441. return this.settings || this.DefaultSettings_;
  30442. }
  30443. /**
  30444. * Copies a sample value to the result buffer.
  30445. *
  30446. * @param {number} index - An index into the sample value buffer.
  30447. * @return {TypedArray} The result buffer.
  30448. */
  30449. copySampleValue_( index ) {
  30450. // copies a sample value to the result buffer
  30451. const result = this.resultBuffer,
  30452. values = this.sampleValues,
  30453. stride = this.valueSize,
  30454. offset = index * stride;
  30455. for ( let i = 0; i !== stride; ++ i ) {
  30456. result[ i ] = values[ offset + i ];
  30457. }
  30458. return result;
  30459. }
  30460. /**
  30461. * Copies a sample value to the result buffer.
  30462. *
  30463. * @abstract
  30464. * @param {number} i1 - An index into the sample value buffer.
  30465. * @param {number} t0 - The previous interpolation factor.
  30466. * @param {number} t - The current interpolation factor.
  30467. * @param {number} t1 - The next interpolation factor.
  30468. * @return {TypedArray} The result buffer.
  30469. */
  30470. interpolate_( /* i1, t0, t, t1 */ ) {
  30471. throw new Error( 'call to abstract method' );
  30472. // implementations shall return this.resultBuffer
  30473. }
  30474. /**
  30475. * Optional method that is executed when the interval has changed.
  30476. *
  30477. * @param {number} i1 - An index into the sample value buffer.
  30478. * @param {number} t0 - The previous interpolation factor.
  30479. * @param {number} t - The current interpolation factor.
  30480. */
  30481. intervalChanged_( /* i1, t0, t1 */ ) {
  30482. // empty
  30483. }
  30484. }
  30485. /**
  30486. * Fast and simple cubic spline interpolant.
  30487. *
  30488. * It was derived from a Hermitian construction setting the first derivative
  30489. * at each sample position to the linear slope between neighboring positions
  30490. * over their parameter interval.
  30491. *
  30492. * @augments Interpolant
  30493. */
  30494. class CubicInterpolant extends Interpolant {
  30495. /**
  30496. * Constructs a new cubic interpolant.
  30497. *
  30498. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30499. * @param {TypedArray} sampleValues - The sample values.
  30500. * @param {number} sampleSize - The sample size
  30501. * @param {TypedArray} [resultBuffer] - The result buffer.
  30502. */
  30503. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30504. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30505. this._weightPrev = -0;
  30506. this._offsetPrev = -0;
  30507. this._weightNext = -0;
  30508. this._offsetNext = -0;
  30509. this.DefaultSettings_ = {
  30510. endingStart: ZeroCurvatureEnding,
  30511. endingEnd: ZeroCurvatureEnding
  30512. };
  30513. }
  30514. intervalChanged_( i1, t0, t1 ) {
  30515. const pp = this.parameterPositions;
  30516. let iPrev = i1 - 2,
  30517. iNext = i1 + 1,
  30518. tPrev = pp[ iPrev ],
  30519. tNext = pp[ iNext ];
  30520. if ( tPrev === undefined ) {
  30521. switch ( this.getSettings_().endingStart ) {
  30522. case ZeroSlopeEnding:
  30523. // f'(t0) = 0
  30524. iPrev = i1;
  30525. tPrev = 2 * t0 - t1;
  30526. break;
  30527. case WrapAroundEnding:
  30528. // use the other end of the curve
  30529. iPrev = pp.length - 2;
  30530. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  30531. break;
  30532. default: // ZeroCurvatureEnding
  30533. // f''(t0) = 0 a.k.a. Natural Spline
  30534. iPrev = i1;
  30535. tPrev = t1;
  30536. }
  30537. }
  30538. if ( tNext === undefined ) {
  30539. switch ( this.getSettings_().endingEnd ) {
  30540. case ZeroSlopeEnding:
  30541. // f'(tN) = 0
  30542. iNext = i1;
  30543. tNext = 2 * t1 - t0;
  30544. break;
  30545. case WrapAroundEnding:
  30546. // use the other end of the curve
  30547. iNext = 1;
  30548. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  30549. break;
  30550. default: // ZeroCurvatureEnding
  30551. // f''(tN) = 0, a.k.a. Natural Spline
  30552. iNext = i1 - 1;
  30553. tNext = t0;
  30554. }
  30555. }
  30556. const halfDt = ( t1 - t0 ) * 0.5,
  30557. stride = this.valueSize;
  30558. this._weightPrev = halfDt / ( t0 - tPrev );
  30559. this._weightNext = halfDt / ( tNext - t1 );
  30560. this._offsetPrev = iPrev * stride;
  30561. this._offsetNext = iNext * stride;
  30562. }
  30563. interpolate_( i1, t0, t, t1 ) {
  30564. const result = this.resultBuffer,
  30565. values = this.sampleValues,
  30566. stride = this.valueSize,
  30567. o1 = i1 * stride, o0 = o1 - stride,
  30568. oP = this._offsetPrev, oN = this._offsetNext,
  30569. wP = this._weightPrev, wN = this._weightNext,
  30570. p = ( t - t0 ) / ( t1 - t0 ),
  30571. pp = p * p,
  30572. ppp = pp * p;
  30573. // evaluate polynomials
  30574. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  30575. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  30576. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  30577. const sN = wN * ppp - wN * pp;
  30578. // combine data linearly
  30579. for ( let i = 0; i !== stride; ++ i ) {
  30580. result[ i ] =
  30581. sP * values[ oP + i ] +
  30582. s0 * values[ o0 + i ] +
  30583. s1 * values[ o1 + i ] +
  30584. sN * values[ oN + i ];
  30585. }
  30586. return result;
  30587. }
  30588. }
  30589. /**
  30590. * A basic linear interpolant.
  30591. *
  30592. * @augments Interpolant
  30593. */
  30594. class LinearInterpolant extends Interpolant {
  30595. /**
  30596. * Constructs a new linear interpolant.
  30597. *
  30598. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30599. * @param {TypedArray} sampleValues - The sample values.
  30600. * @param {number} sampleSize - The sample size
  30601. * @param {TypedArray} [resultBuffer] - The result buffer.
  30602. */
  30603. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30604. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30605. }
  30606. interpolate_( i1, t0, t, t1 ) {
  30607. const result = this.resultBuffer,
  30608. values = this.sampleValues,
  30609. stride = this.valueSize,
  30610. offset1 = i1 * stride,
  30611. offset0 = offset1 - stride,
  30612. weight1 = ( t - t0 ) / ( t1 - t0 ),
  30613. weight0 = 1 - weight1;
  30614. for ( let i = 0; i !== stride; ++ i ) {
  30615. result[ i ] =
  30616. values[ offset0 + i ] * weight0 +
  30617. values[ offset1 + i ] * weight1;
  30618. }
  30619. return result;
  30620. }
  30621. }
  30622. /**
  30623. * Interpolant that evaluates to the sample value at the position preceding
  30624. * the parameter.
  30625. *
  30626. * @augments Interpolant
  30627. */
  30628. class DiscreteInterpolant extends Interpolant {
  30629. /**
  30630. * Constructs a new discrete interpolant.
  30631. *
  30632. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30633. * @param {TypedArray} sampleValues - The sample values.
  30634. * @param {number} sampleSize - The sample size
  30635. * @param {TypedArray} [resultBuffer] - The result buffer.
  30636. */
  30637. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30638. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30639. }
  30640. interpolate_( i1 /*, t0, t, t1 */ ) {
  30641. return this.copySampleValue_( i1 - 1 );
  30642. }
  30643. }
  30644. /**
  30645. * Represents s a timed sequence of keyframes, which are composed of lists of
  30646. * times and related values, and which are used to animate a specific property
  30647. * of an object.
  30648. */
  30649. class KeyframeTrack {
  30650. /**
  30651. * Constructs a new keyframe track.
  30652. *
  30653. * @param {string} name - The keyframe track's name.
  30654. * @param {Array<number>} times - A list of keyframe times.
  30655. * @param {Array<number|string|boolean>} values - A list of keyframe values.
  30656. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30657. */
  30658. constructor( name, times, values, interpolation ) {
  30659. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  30660. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  30661. /**
  30662. * The track's name can refer to morph targets or bones or
  30663. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  30664. * for the forms of strings that can be parsed for property binding.
  30665. *
  30666. * @type {string}
  30667. */
  30668. this.name = name;
  30669. /**
  30670. * The keyframe times.
  30671. *
  30672. * @type {Float32Array}
  30673. */
  30674. this.times = convertArray( times, this.TimeBufferType );
  30675. /**
  30676. * The keyframe values.
  30677. *
  30678. * @type {Float32Array}
  30679. */
  30680. this.values = convertArray( values, this.ValueBufferType );
  30681. this.setInterpolation( interpolation || this.DefaultInterpolation );
  30682. }
  30683. /**
  30684. * Converts the keyframe track to JSON.
  30685. *
  30686. * @static
  30687. * @param {KeyframeTrack} track - The keyframe track to serialize.
  30688. * @return {Object} The serialized keyframe track as JSON.
  30689. */
  30690. static toJSON( track ) {
  30691. const trackType = track.constructor;
  30692. let json;
  30693. // derived classes can define a static toJSON method
  30694. if ( trackType.toJSON !== this.toJSON ) {
  30695. json = trackType.toJSON( track );
  30696. } else {
  30697. // by default, we assume the data can be serialized as-is
  30698. json = {
  30699. 'name': track.name,
  30700. 'times': convertArray( track.times, Array ),
  30701. 'values': convertArray( track.values, Array )
  30702. };
  30703. const interpolation = track.getInterpolation();
  30704. if ( interpolation !== track.DefaultInterpolation ) {
  30705. json.interpolation = interpolation;
  30706. }
  30707. }
  30708. json.type = track.ValueTypeName; // mandatory
  30709. return json;
  30710. }
  30711. /**
  30712. * Factory method for creating a new discrete interpolant.
  30713. *
  30714. * @static
  30715. * @param {TypedArray} [result] - The result buffer.
  30716. * @return {DiscreteInterpolant} The new interpolant.
  30717. */
  30718. InterpolantFactoryMethodDiscrete( result ) {
  30719. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  30720. }
  30721. /**
  30722. * Factory method for creating a new linear interpolant.
  30723. *
  30724. * @static
  30725. * @param {TypedArray} [result] - The result buffer.
  30726. * @return {LinearInterpolant} The new interpolant.
  30727. */
  30728. InterpolantFactoryMethodLinear( result ) {
  30729. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  30730. }
  30731. /**
  30732. * Factory method for creating a new smooth interpolant.
  30733. *
  30734. * @static
  30735. * @param {TypedArray} [result] - The result buffer.
  30736. * @return {CubicInterpolant} The new interpolant.
  30737. */
  30738. InterpolantFactoryMethodSmooth( result ) {
  30739. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  30740. }
  30741. /**
  30742. * Defines the interpolation factor method for this keyframe track.
  30743. *
  30744. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} interpolation - The interpolation type.
  30745. * @return {KeyframeTrack} A reference to this keyframe track.
  30746. */
  30747. setInterpolation( interpolation ) {
  30748. let factoryMethod;
  30749. switch ( interpolation ) {
  30750. case InterpolateDiscrete:
  30751. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  30752. break;
  30753. case InterpolateLinear:
  30754. factoryMethod = this.InterpolantFactoryMethodLinear;
  30755. break;
  30756. case InterpolateSmooth:
  30757. factoryMethod = this.InterpolantFactoryMethodSmooth;
  30758. break;
  30759. }
  30760. if ( factoryMethod === undefined ) {
  30761. const message = 'unsupported interpolation for ' +
  30762. this.ValueTypeName + ' keyframe track named ' + this.name;
  30763. if ( this.createInterpolant === undefined ) {
  30764. // fall back to default, unless the default itself is messed up
  30765. if ( interpolation !== this.DefaultInterpolation ) {
  30766. this.setInterpolation( this.DefaultInterpolation );
  30767. } else {
  30768. throw new Error( message ); // fatal, in this case
  30769. }
  30770. }
  30771. console.warn( 'THREE.KeyframeTrack:', message );
  30772. return this;
  30773. }
  30774. this.createInterpolant = factoryMethod;
  30775. return this;
  30776. }
  30777. /**
  30778. * Returns the current interpolation type.
  30779. *
  30780. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} The interpolation type.
  30781. */
  30782. getInterpolation() {
  30783. switch ( this.createInterpolant ) {
  30784. case this.InterpolantFactoryMethodDiscrete:
  30785. return InterpolateDiscrete;
  30786. case this.InterpolantFactoryMethodLinear:
  30787. return InterpolateLinear;
  30788. case this.InterpolantFactoryMethodSmooth:
  30789. return InterpolateSmooth;
  30790. }
  30791. }
  30792. /**
  30793. * Returns the value size.
  30794. *
  30795. * @return {number} The value size.
  30796. */
  30797. getValueSize() {
  30798. return this.values.length / this.times.length;
  30799. }
  30800. /**
  30801. * Moves all keyframes either forward or backward in time.
  30802. *
  30803. * @param {number} timeOffset - The offset to move the time values.
  30804. * @return {KeyframeTrack} A reference to this keyframe track.
  30805. */
  30806. shift( timeOffset ) {
  30807. if ( timeOffset !== 0.0 ) {
  30808. const times = this.times;
  30809. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30810. times[ i ] += timeOffset;
  30811. }
  30812. }
  30813. return this;
  30814. }
  30815. /**
  30816. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  30817. *
  30818. * @param {number} timeScale - The time scale.
  30819. * @return {KeyframeTrack} A reference to this keyframe track.
  30820. */
  30821. scale( timeScale ) {
  30822. if ( timeScale !== 1.0 ) {
  30823. const times = this.times;
  30824. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30825. times[ i ] *= timeScale;
  30826. }
  30827. }
  30828. return this;
  30829. }
  30830. /**
  30831. * Removes keyframes before and after animation without changing any values within the defined time range.
  30832. *
  30833. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  30834. * keys this will change their values
  30835. *
  30836. * @param {number} startTime - The start time.
  30837. * @param {number} endTime - The end time.
  30838. * @return {KeyframeTrack} A reference to this keyframe track.
  30839. */
  30840. trim( startTime, endTime ) {
  30841. const times = this.times,
  30842. nKeys = times.length;
  30843. let from = 0,
  30844. to = nKeys - 1;
  30845. while ( from !== nKeys && times[ from ] < startTime ) {
  30846. ++ from;
  30847. }
  30848. while ( to !== -1 && times[ to ] > endTime ) {
  30849. -- to;
  30850. }
  30851. ++ to; // inclusive -> exclusive bound
  30852. if ( from !== 0 || to !== nKeys ) {
  30853. // empty tracks are forbidden, so keep at least one keyframe
  30854. if ( from >= to ) {
  30855. to = Math.max( to, 1 );
  30856. from = to - 1;
  30857. }
  30858. const stride = this.getValueSize();
  30859. this.times = times.slice( from, to );
  30860. this.values = this.values.slice( from * stride, to * stride );
  30861. }
  30862. return this;
  30863. }
  30864. /**
  30865. * Performs minimal validation on the keyframe track. Returns `true` if the values
  30866. * are valid.
  30867. *
  30868. * @return {boolean} Whether the keyframes are valid or not.
  30869. */
  30870. validate() {
  30871. let valid = true;
  30872. const valueSize = this.getValueSize();
  30873. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  30874. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  30875. valid = false;
  30876. }
  30877. const times = this.times,
  30878. values = this.values,
  30879. nKeys = times.length;
  30880. if ( nKeys === 0 ) {
  30881. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  30882. valid = false;
  30883. }
  30884. let prevTime = null;
  30885. for ( let i = 0; i !== nKeys; i ++ ) {
  30886. const currTime = times[ i ];
  30887. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  30888. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  30889. valid = false;
  30890. break;
  30891. }
  30892. if ( prevTime !== null && prevTime > currTime ) {
  30893. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  30894. valid = false;
  30895. break;
  30896. }
  30897. prevTime = currTime;
  30898. }
  30899. if ( values !== undefined ) {
  30900. if ( isTypedArray( values ) ) {
  30901. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  30902. const value = values[ i ];
  30903. if ( isNaN( value ) ) {
  30904. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  30905. valid = false;
  30906. break;
  30907. }
  30908. }
  30909. }
  30910. }
  30911. return valid;
  30912. }
  30913. /**
  30914. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  30915. * common in morph target sequences).
  30916. *
  30917. * @return {AnimationClip} A reference to this animation clip.
  30918. */
  30919. optimize() {
  30920. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  30921. // times or values may be shared with other tracks, so overwriting is unsafe
  30922. const times = this.times.slice(),
  30923. values = this.values.slice(),
  30924. stride = this.getValueSize(),
  30925. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  30926. lastIndex = times.length - 1;
  30927. let writeIndex = 1;
  30928. for ( let i = 1; i < lastIndex; ++ i ) {
  30929. let keep = false;
  30930. const time = times[ i ];
  30931. const timeNext = times[ i + 1 ];
  30932. // remove adjacent keyframes scheduled at the same time
  30933. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  30934. if ( ! smoothInterpolation ) {
  30935. // remove unnecessary keyframes same as their neighbors
  30936. const offset = i * stride,
  30937. offsetP = offset - stride,
  30938. offsetN = offset + stride;
  30939. for ( let j = 0; j !== stride; ++ j ) {
  30940. const value = values[ offset + j ];
  30941. if ( value !== values[ offsetP + j ] ||
  30942. value !== values[ offsetN + j ] ) {
  30943. keep = true;
  30944. break;
  30945. }
  30946. }
  30947. } else {
  30948. keep = true;
  30949. }
  30950. }
  30951. // in-place compaction
  30952. if ( keep ) {
  30953. if ( i !== writeIndex ) {
  30954. times[ writeIndex ] = times[ i ];
  30955. const readOffset = i * stride,
  30956. writeOffset = writeIndex * stride;
  30957. for ( let j = 0; j !== stride; ++ j ) {
  30958. values[ writeOffset + j ] = values[ readOffset + j ];
  30959. }
  30960. }
  30961. ++ writeIndex;
  30962. }
  30963. }
  30964. // flush last keyframe (compaction looks ahead)
  30965. if ( lastIndex > 0 ) {
  30966. times[ writeIndex ] = times[ lastIndex ];
  30967. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  30968. values[ writeOffset + j ] = values[ readOffset + j ];
  30969. }
  30970. ++ writeIndex;
  30971. }
  30972. if ( writeIndex !== times.length ) {
  30973. this.times = times.slice( 0, writeIndex );
  30974. this.values = values.slice( 0, writeIndex * stride );
  30975. } else {
  30976. this.times = times;
  30977. this.values = values;
  30978. }
  30979. return this;
  30980. }
  30981. /**
  30982. * Returns a new keyframe track with copied values from this instance.
  30983. *
  30984. * @return {KeyframeTrack} A clone of this instance.
  30985. */
  30986. clone() {
  30987. const times = this.times.slice();
  30988. const values = this.values.slice();
  30989. const TypedKeyframeTrack = this.constructor;
  30990. const track = new TypedKeyframeTrack( this.name, times, values );
  30991. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  30992. track.createInterpolant = this.createInterpolant;
  30993. return track;
  30994. }
  30995. }
  30996. /**
  30997. * The value type name.
  30998. *
  30999. * @type {String}
  31000. * @default ''
  31001. */
  31002. KeyframeTrack.prototype.ValueTypeName = '';
  31003. /**
  31004. * The time buffer type of this keyframe track.
  31005. *
  31006. * @type {TypedArray|Array}
  31007. * @default Float32Array.constructor
  31008. */
  31009. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  31010. /**
  31011. * The value buffer type of this keyframe track.
  31012. *
  31013. * @type {TypedArray|Array}
  31014. * @default Float32Array.constructor
  31015. */
  31016. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  31017. /**
  31018. * The default interpolation type of this keyframe track.
  31019. *
  31020. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31021. * @default InterpolateLinear
  31022. */
  31023. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  31024. /**
  31025. * A track for boolean keyframe values.
  31026. *
  31027. * @augments KeyframeTrack
  31028. */
  31029. class BooleanKeyframeTrack extends KeyframeTrack {
  31030. /**
  31031. * Constructs a new boolean keyframe track.
  31032. *
  31033. * This keyframe track type has no `interpolation` parameter because the
  31034. * interpolation is always discrete.
  31035. *
  31036. * @param {string} name - The keyframe track's name.
  31037. * @param {Array<number>} times - A list of keyframe times.
  31038. * @param {Array<boolean>} values - A list of keyframe values.
  31039. */
  31040. constructor( name, times, values ) {
  31041. super( name, times, values );
  31042. }
  31043. }
  31044. /**
  31045. * The value type name.
  31046. *
  31047. * @type {String}
  31048. * @default 'bool'
  31049. */
  31050. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  31051. /**
  31052. * The value buffer type of this keyframe track.
  31053. *
  31054. * @type {TypedArray|Array}
  31055. * @default Array.constructor
  31056. */
  31057. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  31058. /**
  31059. * The default interpolation type of this keyframe track.
  31060. *
  31061. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31062. * @default InterpolateDiscrete
  31063. */
  31064. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31065. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31066. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31067. /**
  31068. * A track for color keyframe values.
  31069. *
  31070. * @augments KeyframeTrack
  31071. */
  31072. class ColorKeyframeTrack extends KeyframeTrack {
  31073. /**
  31074. * Constructs a new color keyframe track.
  31075. *
  31076. * @param {string} name - The keyframe track's name.
  31077. * @param {Array<number>} times - A list of keyframe times.
  31078. * @param {Array<number>} values - A list of keyframe values.
  31079. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31080. */
  31081. constructor( name, times, values, interpolation ) {
  31082. super( name, times, values, interpolation );
  31083. }
  31084. }
  31085. /**
  31086. * The value type name.
  31087. *
  31088. * @type {String}
  31089. * @default 'color'
  31090. */
  31091. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31092. /**
  31093. * A track for numeric keyframe values.
  31094. *
  31095. * @augments KeyframeTrack
  31096. */
  31097. class NumberKeyframeTrack extends KeyframeTrack {
  31098. /**
  31099. * Constructs a new number keyframe track.
  31100. *
  31101. * @param {string} name - The keyframe track's name.
  31102. * @param {Array<number>} times - A list of keyframe times.
  31103. * @param {Array<number>} values - A list of keyframe values.
  31104. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31105. */
  31106. constructor( name, times, values, interpolation ) {
  31107. super( name, times, values, interpolation );
  31108. }
  31109. }
  31110. /**
  31111. * The value type name.
  31112. *
  31113. * @type {String}
  31114. * @default 'number'
  31115. */
  31116. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31117. /**
  31118. * Spherical linear unit quaternion interpolant.
  31119. *
  31120. * @augments Interpolant
  31121. */
  31122. class QuaternionLinearInterpolant extends Interpolant {
  31123. /**
  31124. * Constructs a new SLERP interpolant.
  31125. *
  31126. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31127. * @param {TypedArray} sampleValues - The sample values.
  31128. * @param {number} sampleSize - The sample size
  31129. * @param {TypedArray} [resultBuffer] - The result buffer.
  31130. */
  31131. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31132. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31133. }
  31134. interpolate_( i1, t0, t, t1 ) {
  31135. const result = this.resultBuffer,
  31136. values = this.sampleValues,
  31137. stride = this.valueSize,
  31138. alpha = ( t - t0 ) / ( t1 - t0 );
  31139. let offset = i1 * stride;
  31140. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31141. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31142. }
  31143. return result;
  31144. }
  31145. }
  31146. /**
  31147. * A track for Quaternion keyframe values.
  31148. *
  31149. * @augments KeyframeTrack
  31150. */
  31151. class QuaternionKeyframeTrack extends KeyframeTrack {
  31152. /**
  31153. * Constructs a new Quaternion keyframe track.
  31154. *
  31155. * @param {string} name - The keyframe track's name.
  31156. * @param {Array<number>} times - A list of keyframe times.
  31157. * @param {Array<number>} values - A list of keyframe values.
  31158. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31159. */
  31160. constructor( name, times, values, interpolation ) {
  31161. super( name, times, values, interpolation );
  31162. }
  31163. /**
  31164. * Overwritten so the method returns Quaternion based interpolant.
  31165. *
  31166. * @static
  31167. * @param {TypedArray} [result] - The result buffer.
  31168. * @return {QuaternionLinearInterpolant} The new interpolant.
  31169. */
  31170. InterpolantFactoryMethodLinear( result ) {
  31171. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31172. }
  31173. }
  31174. /**
  31175. * The value type name.
  31176. *
  31177. * @type {String}
  31178. * @default 'quaternion'
  31179. */
  31180. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31181. // ValueBufferType is inherited
  31182. // DefaultInterpolation is inherited;
  31183. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31184. /**
  31185. * A track for string keyframe values.
  31186. *
  31187. * @augments KeyframeTrack
  31188. */
  31189. class StringKeyframeTrack extends KeyframeTrack {
  31190. /**
  31191. * Constructs a new string keyframe track.
  31192. *
  31193. * This keyframe track type has no `interpolation` parameter because the
  31194. * interpolation is always discrete.
  31195. *
  31196. * @param {string} name - The keyframe track's name.
  31197. * @param {Array<number>} times - A list of keyframe times.
  31198. * @param {Array<string>} values - A list of keyframe values.
  31199. */
  31200. constructor( name, times, values ) {
  31201. super( name, times, values );
  31202. }
  31203. }
  31204. /**
  31205. * The value type name.
  31206. *
  31207. * @type {String}
  31208. * @default 'string'
  31209. */
  31210. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31211. /**
  31212. * The value buffer type of this keyframe track.
  31213. *
  31214. * @type {TypedArray|Array}
  31215. * @default Array.constructor
  31216. */
  31217. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31218. /**
  31219. * The default interpolation type of this keyframe track.
  31220. *
  31221. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31222. * @default InterpolateDiscrete
  31223. */
  31224. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31225. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31226. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31227. /**
  31228. * A track for vector keyframe values.
  31229. *
  31230. * @augments KeyframeTrack
  31231. */
  31232. class VectorKeyframeTrack extends KeyframeTrack {
  31233. /**
  31234. * Constructs a new vector keyframe track.
  31235. *
  31236. * @param {string} name - The keyframe track's name.
  31237. * @param {Array<number>} times - A list of keyframe times.
  31238. * @param {Array<number>} values - A list of keyframe values.
  31239. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31240. */
  31241. constructor( name, times, values, interpolation ) {
  31242. super( name, times, values, interpolation );
  31243. }
  31244. }
  31245. /**
  31246. * The value type name.
  31247. *
  31248. * @type {String}
  31249. * @default 'vector'
  31250. */
  31251. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31252. /**
  31253. * A reusable set of keyframe tracks which represent an animation.
  31254. */
  31255. class AnimationClip {
  31256. /**
  31257. * Constructs a new animation clip.
  31258. *
  31259. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31260. * use the static interface of this class for creating clips. In most cases though, animation clips
  31261. * will automatically be created by loaders when importing animated 3D assets.
  31262. *
  31263. * @param {string} [name=''] - The clip's name.
  31264. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31265. * the duration will be calculated from the passed keyframes.
  31266. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31267. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31268. * is blended/combined when two or more animations are simultaneously played.
  31269. */
  31270. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31271. /**
  31272. * The clip's name.
  31273. *
  31274. * @type {string}
  31275. */
  31276. this.name = name;
  31277. /**
  31278. * An array of keyframe tracks.
  31279. *
  31280. * @type {Array<KeyframeTrack>}
  31281. */
  31282. this.tracks = tracks;
  31283. /**
  31284. * The clip's duration in seconds.
  31285. *
  31286. * @type {number}
  31287. */
  31288. this.duration = duration;
  31289. /**
  31290. * Defines how the animation is blended/combined when two or more animations
  31291. * are simultaneously played.
  31292. *
  31293. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31294. */
  31295. this.blendMode = blendMode;
  31296. /**
  31297. * The UUID of the animation clip.
  31298. *
  31299. * @type {string}
  31300. * @readonly
  31301. */
  31302. this.uuid = generateUUID();
  31303. // this means it should figure out its duration by scanning the tracks
  31304. if ( this.duration < 0 ) {
  31305. this.resetDuration();
  31306. }
  31307. }
  31308. /**
  31309. * Factory method for creating an animation clip from the given JSON.
  31310. *
  31311. * @static
  31312. * @param {Object} json - The serialized animation clip.
  31313. * @return {AnimationClip} The new animation clip.
  31314. */
  31315. static parse( json ) {
  31316. const tracks = [],
  31317. jsonTracks = json.tracks,
  31318. frameTime = 1.0 / ( json.fps || 1.0 );
  31319. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31320. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31321. }
  31322. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31323. clip.uuid = json.uuid;
  31324. return clip;
  31325. }
  31326. /**
  31327. * Serializes the given animation clip into JSON.
  31328. *
  31329. * @static
  31330. * @param {AnimationClip} clip - The animation clip to serialize.
  31331. * @return {Object} The JSON object.
  31332. */
  31333. static toJSON( clip ) {
  31334. const tracks = [],
  31335. clipTracks = clip.tracks;
  31336. const json = {
  31337. 'name': clip.name,
  31338. 'duration': clip.duration,
  31339. 'tracks': tracks,
  31340. 'uuid': clip.uuid,
  31341. 'blendMode': clip.blendMode
  31342. };
  31343. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31344. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31345. }
  31346. return json;
  31347. }
  31348. /**
  31349. * Returns a new animation clip from the passed morph targets array of a
  31350. * geometry, taking a name and the number of frames per second.
  31351. *
  31352. * Note: The fps parameter is required, but the animation speed can be
  31353. * overridden via {@link AnimationAction#setDuration}.
  31354. *
  31355. * @static
  31356. * @param {string} name - The name of the animation clip.
  31357. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31358. * @param {number} fps - The Frames-Per-Second value.
  31359. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31360. * @return {AnimationClip} The new animation clip.
  31361. */
  31362. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  31363. const numMorphTargets = morphTargetSequence.length;
  31364. const tracks = [];
  31365. for ( let i = 0; i < numMorphTargets; i ++ ) {
  31366. let times = [];
  31367. let values = [];
  31368. times.push(
  31369. ( i + numMorphTargets - 1 ) % numMorphTargets,
  31370. i,
  31371. ( i + 1 ) % numMorphTargets );
  31372. values.push( 0, 1, 0 );
  31373. const order = getKeyframeOrder( times );
  31374. times = sortedArray( times, 1, order );
  31375. values = sortedArray( values, 1, order );
  31376. // if there is a key at the first frame, duplicate it as the
  31377. // last frame as well for perfect loop.
  31378. if ( ! noLoop && times[ 0 ] === 0 ) {
  31379. times.push( numMorphTargets );
  31380. values.push( values[ 0 ] );
  31381. }
  31382. tracks.push(
  31383. new NumberKeyframeTrack(
  31384. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  31385. times, values
  31386. ).scale( 1.0 / fps ) );
  31387. }
  31388. return new this( name, -1, tracks );
  31389. }
  31390. /**
  31391. * Searches for an animation clip by name, taking as its first parameter
  31392. * either an array of clips, or a mesh or geometry that contains an
  31393. * array named "animations" property.
  31394. *
  31395. * @static
  31396. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  31397. * @param {string} name - The name to search for.
  31398. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  31399. */
  31400. static findByName( objectOrClipArray, name ) {
  31401. let clipArray = objectOrClipArray;
  31402. if ( ! Array.isArray( objectOrClipArray ) ) {
  31403. const o = objectOrClipArray;
  31404. clipArray = o.geometry && o.geometry.animations || o.animations;
  31405. }
  31406. for ( let i = 0; i < clipArray.length; i ++ ) {
  31407. if ( clipArray[ i ].name === name ) {
  31408. return clipArray[ i ];
  31409. }
  31410. }
  31411. return null;
  31412. }
  31413. /**
  31414. * Returns an array of new AnimationClips created from the morph target
  31415. * sequences of a geometry, trying to sort morph target names into
  31416. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  31417. *
  31418. * See {@link MD2Loader#parse} as an example for how the method should be used.
  31419. *
  31420. * @static
  31421. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  31422. * @param {number} fps - The Frames-Per-Second value.
  31423. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31424. * @return {Array<AnimationClip>} An array of new animation clips.
  31425. */
  31426. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  31427. const animationToMorphTargets = {};
  31428. // tested with https://regex101.com/ on trick sequences
  31429. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  31430. const pattern = /^([\w-]*?)([\d]+)$/;
  31431. // sort morph target names into animation groups based
  31432. // patterns like Walk_001, Walk_002, Run_001, Run_002
  31433. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  31434. const morphTarget = morphTargets[ i ];
  31435. const parts = morphTarget.name.match( pattern );
  31436. if ( parts && parts.length > 1 ) {
  31437. const name = parts[ 1 ];
  31438. let animationMorphTargets = animationToMorphTargets[ name ];
  31439. if ( ! animationMorphTargets ) {
  31440. animationToMorphTargets[ name ] = animationMorphTargets = [];
  31441. }
  31442. animationMorphTargets.push( morphTarget );
  31443. }
  31444. }
  31445. const clips = [];
  31446. for ( const name in animationToMorphTargets ) {
  31447. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  31448. }
  31449. return clips;
  31450. }
  31451. /**
  31452. * Parses the `animation.hierarchy` format and returns a new animation clip.
  31453. *
  31454. * @static
  31455. * @deprecated since r175.
  31456. * @param {Object} animation - A serialized animation clip as JSON.
  31457. * @param {Array<Bones>} bones - An array of bones.
  31458. * @return {?AnimationClip} The new animation clip.
  31459. */
  31460. static parseAnimation( animation, bones ) {
  31461. console.warn( 'THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  31462. if ( ! animation ) {
  31463. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  31464. return null;
  31465. }
  31466. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  31467. // only return track if there are actually keys.
  31468. if ( animationKeys.length !== 0 ) {
  31469. const times = [];
  31470. const values = [];
  31471. flattenJSON( animationKeys, times, values, propertyName );
  31472. // empty keys are filtered out, so check again
  31473. if ( times.length !== 0 ) {
  31474. destTracks.push( new trackType( trackName, times, values ) );
  31475. }
  31476. }
  31477. };
  31478. const tracks = [];
  31479. const clipName = animation.name || 'default';
  31480. const fps = animation.fps || 30;
  31481. const blendMode = animation.blendMode;
  31482. // automatic length determination in AnimationClip.
  31483. let duration = animation.length || -1;
  31484. const hierarchyTracks = animation.hierarchy || [];
  31485. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  31486. const animationKeys = hierarchyTracks[ h ].keys;
  31487. // skip empty tracks
  31488. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  31489. // process morph targets
  31490. if ( animationKeys[ 0 ].morphTargets ) {
  31491. // figure out all morph targets used in this track
  31492. const morphTargetNames = {};
  31493. let k;
  31494. for ( k = 0; k < animationKeys.length; k ++ ) {
  31495. if ( animationKeys[ k ].morphTargets ) {
  31496. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  31497. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  31498. }
  31499. }
  31500. }
  31501. // create a track for each morph target with all zero
  31502. // morphTargetInfluences except for the keys in which
  31503. // the morphTarget is named.
  31504. for ( const morphTargetName in morphTargetNames ) {
  31505. const times = [];
  31506. const values = [];
  31507. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  31508. const animationKey = animationKeys[ k ];
  31509. times.push( animationKey.time );
  31510. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  31511. }
  31512. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  31513. }
  31514. duration = morphTargetNames.length * fps;
  31515. } else {
  31516. // ...assume skeletal animation
  31517. const boneName = '.bones[' + bones[ h ].name + ']';
  31518. addNonemptyTrack(
  31519. VectorKeyframeTrack, boneName + '.position',
  31520. animationKeys, 'pos', tracks );
  31521. addNonemptyTrack(
  31522. QuaternionKeyframeTrack, boneName + '.quaternion',
  31523. animationKeys, 'rot', tracks );
  31524. addNonemptyTrack(
  31525. VectorKeyframeTrack, boneName + '.scale',
  31526. animationKeys, 'scl', tracks );
  31527. }
  31528. }
  31529. if ( tracks.length === 0 ) {
  31530. return null;
  31531. }
  31532. const clip = new this( clipName, duration, tracks, blendMode );
  31533. return clip;
  31534. }
  31535. /**
  31536. * Sets the duration of this clip to the duration of its longest keyframe track.
  31537. *
  31538. * @return {AnimationClip} A reference to this animation clip.
  31539. */
  31540. resetDuration() {
  31541. const tracks = this.tracks;
  31542. let duration = 0;
  31543. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  31544. const track = this.tracks[ i ];
  31545. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  31546. }
  31547. this.duration = duration;
  31548. return this;
  31549. }
  31550. /**
  31551. * Trims all tracks to the clip's duration.
  31552. *
  31553. * @return {AnimationClip} A reference to this animation clip.
  31554. */
  31555. trim() {
  31556. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31557. this.tracks[ i ].trim( 0, this.duration );
  31558. }
  31559. return this;
  31560. }
  31561. /**
  31562. * Performs minimal validation on each track in the clip. Returns `true` if all
  31563. * tracks are valid.
  31564. *
  31565. * @return {boolean} Whether the clip's keyframes are valid or not.
  31566. */
  31567. validate() {
  31568. let valid = true;
  31569. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31570. valid = valid && this.tracks[ i ].validate();
  31571. }
  31572. return valid;
  31573. }
  31574. /**
  31575. * Optimizes each track by removing equivalent sequential keys (which are
  31576. * common in morph target sequences).
  31577. *
  31578. * @return {AnimationClip} A reference to this animation clip.
  31579. */
  31580. optimize() {
  31581. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31582. this.tracks[ i ].optimize();
  31583. }
  31584. return this;
  31585. }
  31586. /**
  31587. * Returns a new animation clip with copied values from this instance.
  31588. *
  31589. * @return {AnimationClip} A clone of this instance.
  31590. */
  31591. clone() {
  31592. const tracks = [];
  31593. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31594. tracks.push( this.tracks[ i ].clone() );
  31595. }
  31596. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  31597. }
  31598. /**
  31599. * Serializes this animation clip into JSON.
  31600. *
  31601. * @return {Object} The JSON object.
  31602. */
  31603. toJSON() {
  31604. return this.constructor.toJSON( this );
  31605. }
  31606. }
  31607. function getTrackTypeForValueTypeName( typeName ) {
  31608. switch ( typeName.toLowerCase() ) {
  31609. case 'scalar':
  31610. case 'double':
  31611. case 'float':
  31612. case 'number':
  31613. case 'integer':
  31614. return NumberKeyframeTrack;
  31615. case 'vector':
  31616. case 'vector2':
  31617. case 'vector3':
  31618. case 'vector4':
  31619. return VectorKeyframeTrack;
  31620. case 'color':
  31621. return ColorKeyframeTrack;
  31622. case 'quaternion':
  31623. return QuaternionKeyframeTrack;
  31624. case 'bool':
  31625. case 'boolean':
  31626. return BooleanKeyframeTrack;
  31627. case 'string':
  31628. return StringKeyframeTrack;
  31629. }
  31630. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  31631. }
  31632. function parseKeyframeTrack( json ) {
  31633. if ( json.type === undefined ) {
  31634. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  31635. }
  31636. const trackType = getTrackTypeForValueTypeName( json.type );
  31637. if ( json.times === undefined ) {
  31638. const times = [], values = [];
  31639. flattenJSON( json.keys, times, values, 'value' );
  31640. json.times = times;
  31641. json.values = values;
  31642. }
  31643. // derived classes can define a static parse method
  31644. if ( trackType.parse !== undefined ) {
  31645. return trackType.parse( json );
  31646. } else {
  31647. // by default, we assume a constructor compatible with the base
  31648. return new trackType( json.name, json.times, json.values, json.interpolation );
  31649. }
  31650. }
  31651. /**
  31652. * @class
  31653. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  31654. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  31655. * @hideconstructor
  31656. */
  31657. const Cache = {
  31658. /**
  31659. * Whether caching is enabled or not.
  31660. *
  31661. * @static
  31662. * @type {boolean}
  31663. * @default false
  31664. */
  31665. enabled: false,
  31666. /**
  31667. * A dictionary that holds cached files.
  31668. *
  31669. * @static
  31670. * @type {Object<string,Object>}
  31671. */
  31672. files: {},
  31673. /**
  31674. * Adds a cache entry with a key to reference the file. If this key already
  31675. * holds a file, it is overwritten.
  31676. *
  31677. * @static
  31678. * @param {string} key - The key to reference the cached file.
  31679. * @param {Object} file - The file to be cached.
  31680. */
  31681. add: function ( key, file ) {
  31682. if ( this.enabled === false ) return;
  31683. // console.log( 'THREE.Cache', 'Adding key:', key );
  31684. this.files[ key ] = file;
  31685. },
  31686. /**
  31687. * Gets the cached value for the given key.
  31688. *
  31689. * @static
  31690. * @param {string} key - The key to reference the cached file.
  31691. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  31692. */
  31693. get: function ( key ) {
  31694. if ( this.enabled === false ) return;
  31695. // console.log( 'THREE.Cache', 'Checking key:', key );
  31696. return this.files[ key ];
  31697. },
  31698. /**
  31699. * Removes the cached file associated with the given key.
  31700. *
  31701. * @static
  31702. * @param {string} key - The key to reference the cached file.
  31703. */
  31704. remove: function ( key ) {
  31705. delete this.files[ key ];
  31706. },
  31707. /**
  31708. * Remove all values from the cache.
  31709. *
  31710. * @static
  31711. */
  31712. clear: function () {
  31713. this.files = {};
  31714. }
  31715. };
  31716. /**
  31717. * Handles and keeps track of loaded and pending data. A default global
  31718. * instance of this class is created and used by loaders if not supplied
  31719. * manually.
  31720. *
  31721. * In general that should be sufficient, however there are times when it can
  31722. * be useful to have separate loaders - for example if you want to show
  31723. * separate loading bars for objects and textures.
  31724. *
  31725. * ```js
  31726. * const manager = new THREE.LoadingManager();
  31727. * manager.onLoad = () => console.log( 'Loading complete!' );
  31728. *
  31729. * const loader1 = new OBJLoader( manager );
  31730. * const loader2 = new ColladaLoader( manager );
  31731. * ```
  31732. */
  31733. class LoadingManager {
  31734. /**
  31735. * Constructs a new loading manager.
  31736. *
  31737. * @param {Function} [onLoad] - Executes when all items have been loaded.
  31738. * @param {Function} [onProgress] - Executes when single items have been loaded.
  31739. * @param {Function} [onError] - Executes when an error occurs.
  31740. */
  31741. constructor( onLoad, onProgress, onError ) {
  31742. const scope = this;
  31743. let isLoading = false;
  31744. let itemsLoaded = 0;
  31745. let itemsTotal = 0;
  31746. let urlModifier = undefined;
  31747. const handlers = [];
  31748. // Refer to #5689 for the reason why we don't set .onStart
  31749. // in the constructor
  31750. /**
  31751. * Executes when an item starts loading.
  31752. *
  31753. * @type {Function|undefined}
  31754. * @default undefined
  31755. */
  31756. this.onStart = undefined;
  31757. /**
  31758. * Executes when all items have been loaded.
  31759. *
  31760. * @type {Function|undefined}
  31761. * @default undefined
  31762. */
  31763. this.onLoad = onLoad;
  31764. /**
  31765. * Executes when single items have been loaded.
  31766. *
  31767. * @type {Function|undefined}
  31768. * @default undefined
  31769. */
  31770. this.onProgress = onProgress;
  31771. /**
  31772. * Executes when an error occurs.
  31773. *
  31774. * @type {Function|undefined}
  31775. * @default undefined
  31776. */
  31777. this.onError = onError;
  31778. /**
  31779. * Used for aborting ongoing requests in loaders using this manager.
  31780. *
  31781. * @type {AbortController}
  31782. */
  31783. this.abortController = new AbortController();
  31784. /**
  31785. * This should be called by any loader using the manager when the loader
  31786. * starts loading an item.
  31787. *
  31788. * @param {string} url - The URL to load.
  31789. */
  31790. this.itemStart = function ( url ) {
  31791. itemsTotal ++;
  31792. if ( isLoading === false ) {
  31793. if ( scope.onStart !== undefined ) {
  31794. scope.onStart( url, itemsLoaded, itemsTotal );
  31795. }
  31796. }
  31797. isLoading = true;
  31798. };
  31799. /**
  31800. * This should be called by any loader using the manager when the loader
  31801. * ended loading an item.
  31802. *
  31803. * @param {string} url - The URL of the loaded item.
  31804. */
  31805. this.itemEnd = function ( url ) {
  31806. itemsLoaded ++;
  31807. if ( scope.onProgress !== undefined ) {
  31808. scope.onProgress( url, itemsLoaded, itemsTotal );
  31809. }
  31810. if ( itemsLoaded === itemsTotal ) {
  31811. isLoading = false;
  31812. if ( scope.onLoad !== undefined ) {
  31813. scope.onLoad();
  31814. }
  31815. }
  31816. };
  31817. /**
  31818. * This should be called by any loader using the manager when the loader
  31819. * encounters an error when loading an item.
  31820. *
  31821. * @param {string} url - The URL of the item that produces an error.
  31822. */
  31823. this.itemError = function ( url ) {
  31824. if ( scope.onError !== undefined ) {
  31825. scope.onError( url );
  31826. }
  31827. };
  31828. /**
  31829. * Given a URL, uses the URL modifier callback (if any) and returns a
  31830. * resolved URL. If no URL modifier is set, returns the original URL.
  31831. *
  31832. * @param {string} url - The URL to load.
  31833. * @return {string} The resolved URL.
  31834. */
  31835. this.resolveURL = function ( url ) {
  31836. if ( urlModifier ) {
  31837. return urlModifier( url );
  31838. }
  31839. return url;
  31840. };
  31841. /**
  31842. * If provided, the callback will be passed each resource URL before a
  31843. * request is sent. The callback may return the original URL, or a new URL to
  31844. * override loading behavior. This behavior can be used to load assets from
  31845. * .ZIP files, drag-and-drop APIs, and Data URIs.
  31846. *
  31847. * ```js
  31848. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  31849. *
  31850. * const manager = new THREE.LoadingManager();
  31851. *
  31852. * // Initialize loading manager with URL callback.
  31853. * const objectURLs = [];
  31854. * manager.setURLModifier( ( url ) => {
  31855. *
  31856. * url = URL.createObjectURL( blobs[ url ] );
  31857. * objectURLs.push( url );
  31858. * return url;
  31859. *
  31860. * } );
  31861. *
  31862. * // Load as usual, then revoke the blob URLs.
  31863. * const loader = new GLTFLoader( manager );
  31864. * loader.load( 'fish.gltf', (gltf) => {
  31865. *
  31866. * scene.add( gltf.scene );
  31867. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  31868. *
  31869. * } );
  31870. * ```
  31871. *
  31872. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  31873. * @return {LoadingManager} A reference to this loading manager.
  31874. */
  31875. this.setURLModifier = function ( transform ) {
  31876. urlModifier = transform;
  31877. return this;
  31878. };
  31879. /**
  31880. * Registers a loader with the given regular expression. Can be used to
  31881. * define what loader should be used in order to load specific files. A
  31882. * typical use case is to overwrite the default loader for textures.
  31883. *
  31884. * ```js
  31885. * // add handler for TGA textures
  31886. * manager.addHandler( /\.tga$/i, new TGALoader() );
  31887. * ```
  31888. *
  31889. * @param {string} regex - A regular expression.
  31890. * @param {Loader} loader - A loader that should handle matched cases.
  31891. * @return {LoadingManager} A reference to this loading manager.
  31892. */
  31893. this.addHandler = function ( regex, loader ) {
  31894. handlers.push( regex, loader );
  31895. return this;
  31896. };
  31897. /**
  31898. * Removes the loader for the given regular expression.
  31899. *
  31900. * @param {string} regex - A regular expression.
  31901. * @return {LoadingManager} A reference to this loading manager.
  31902. */
  31903. this.removeHandler = function ( regex ) {
  31904. const index = handlers.indexOf( regex );
  31905. if ( index !== -1 ) {
  31906. handlers.splice( index, 2 );
  31907. }
  31908. return this;
  31909. };
  31910. /**
  31911. * Can be used to retrieve the registered loader for the given file path.
  31912. *
  31913. * @param {string} file - The file path.
  31914. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  31915. */
  31916. this.getHandler = function ( file ) {
  31917. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  31918. const regex = handlers[ i ];
  31919. const loader = handlers[ i + 1 ];
  31920. if ( regex.global ) regex.lastIndex = 0; // see #17920
  31921. if ( regex.test( file ) ) {
  31922. return loader;
  31923. }
  31924. }
  31925. return null;
  31926. };
  31927. /**
  31928. * Can be used to abort ongoing loading requests in loaders using this manager.
  31929. * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()`
  31930. * is supported in the browser.
  31931. *
  31932. * @return {LoadingManager} A reference to this loading manager.
  31933. */
  31934. this.abort = function () {
  31935. this.abortController.abort();
  31936. this.abortController = new AbortController();
  31937. return this;
  31938. };
  31939. }
  31940. }
  31941. /**
  31942. * The global default loading manager.
  31943. *
  31944. * @constant
  31945. * @type {LoadingManager}
  31946. */
  31947. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  31948. /**
  31949. * Abstract base class for loaders.
  31950. *
  31951. * @abstract
  31952. */
  31953. class Loader {
  31954. /**
  31955. * Constructs a new loader.
  31956. *
  31957. * @param {LoadingManager} [manager] - The loading manager.
  31958. */
  31959. constructor( manager ) {
  31960. /**
  31961. * The loading manager.
  31962. *
  31963. * @type {LoadingManager}
  31964. * @default DefaultLoadingManager
  31965. */
  31966. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  31967. /**
  31968. * The crossOrigin string to implement CORS for loading the url from a
  31969. * different domain that allows CORS.
  31970. *
  31971. * @type {string}
  31972. * @default 'anonymous'
  31973. */
  31974. this.crossOrigin = 'anonymous';
  31975. /**
  31976. * Whether the XMLHttpRequest uses credentials.
  31977. *
  31978. * @type {boolean}
  31979. * @default false
  31980. */
  31981. this.withCredentials = false;
  31982. /**
  31983. * The base path from which the asset will be loaded.
  31984. *
  31985. * @type {string}
  31986. */
  31987. this.path = '';
  31988. /**
  31989. * The base path from which additional resources like textures will be loaded.
  31990. *
  31991. * @type {string}
  31992. */
  31993. this.resourcePath = '';
  31994. /**
  31995. * The [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  31996. * used in HTTP request.
  31997. *
  31998. * @type {Object<string, any>}
  31999. */
  32000. this.requestHeader = {};
  32001. }
  32002. /**
  32003. * This method needs to be implemented by all concrete loaders. It holds the
  32004. * logic for loading assets from the backend.
  32005. *
  32006. * @abstract
  32007. * @param {string} url - The path/URL of the file to be loaded.
  32008. * @param {Function} onLoad - Executed when the loading process has been finished.
  32009. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32010. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32011. */
  32012. load( /* url, onLoad, onProgress, onError */ ) {}
  32013. /**
  32014. * A async version of {@link Loader#load}.
  32015. *
  32016. * @param {string} url - The path/URL of the file to be loaded.
  32017. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32018. * @return {Promise} A Promise that resolves when the asset has been loaded.
  32019. */
  32020. loadAsync( url, onProgress ) {
  32021. const scope = this;
  32022. return new Promise( function ( resolve, reject ) {
  32023. scope.load( url, resolve, onProgress, reject );
  32024. } );
  32025. }
  32026. /**
  32027. * This method needs to be implemented by all concrete loaders. It holds the
  32028. * logic for parsing the asset into three.js entities.
  32029. *
  32030. * @abstract
  32031. * @param {any} data - The data to parse.
  32032. */
  32033. parse( /* data */ ) {}
  32034. /**
  32035. * Sets the `crossOrigin` String to implement CORS for loading the URL
  32036. * from a different domain that allows CORS.
  32037. *
  32038. * @param {string} crossOrigin - The `crossOrigin` value.
  32039. * @return {Loader} A reference to this instance.
  32040. */
  32041. setCrossOrigin( crossOrigin ) {
  32042. this.crossOrigin = crossOrigin;
  32043. return this;
  32044. }
  32045. /**
  32046. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  32047. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials}.
  32048. *
  32049. * Note: This setting has no effect if you are loading files locally or from the same domain.
  32050. *
  32051. * @param {boolean} value - The `withCredentials` value.
  32052. * @return {Loader} A reference to this instance.
  32053. */
  32054. setWithCredentials( value ) {
  32055. this.withCredentials = value;
  32056. return this;
  32057. }
  32058. /**
  32059. * Sets the base path for the asset.
  32060. *
  32061. * @param {string} path - The base path.
  32062. * @return {Loader} A reference to this instance.
  32063. */
  32064. setPath( path ) {
  32065. this.path = path;
  32066. return this;
  32067. }
  32068. /**
  32069. * Sets the base path for dependent resources like textures.
  32070. *
  32071. * @param {string} resourcePath - The resource path.
  32072. * @return {Loader} A reference to this instance.
  32073. */
  32074. setResourcePath( resourcePath ) {
  32075. this.resourcePath = resourcePath;
  32076. return this;
  32077. }
  32078. /**
  32079. * Sets the given request header.
  32080. *
  32081. * @param {Object} requestHeader - A [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  32082. * for configuring the HTTP request.
  32083. * @return {Loader} A reference to this instance.
  32084. */
  32085. setRequestHeader( requestHeader ) {
  32086. this.requestHeader = requestHeader;
  32087. return this;
  32088. }
  32089. /**
  32090. * This method can be implemented in loaders for aborting ongoing requests.
  32091. *
  32092. * @abstract
  32093. * @return {Loader} A reference to this instance.
  32094. */
  32095. abort() {
  32096. return this;
  32097. }
  32098. }
  32099. /**
  32100. * Callback for onProgress in loaders.
  32101. *
  32102. * @callback onProgressCallback
  32103. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32104. */
  32105. /**
  32106. * Callback for onError in loaders.
  32107. *
  32108. * @callback onErrorCallback
  32109. * @param {Error} error - The error which occurred during the loading process.
  32110. */
  32111. /**
  32112. * The default material name that is used by loaders
  32113. * when creating materials for loaded 3D objects.
  32114. *
  32115. * Note: Not all loaders might honor this setting.
  32116. *
  32117. * @static
  32118. * @type {string}
  32119. * @default '__DEFAULT'
  32120. */
  32121. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32122. const loading = {};
  32123. class HttpError extends Error {
  32124. constructor( message, response ) {
  32125. super( message );
  32126. this.response = response;
  32127. }
  32128. }
  32129. /**
  32130. * A low level class for loading resources with the Fetch API, used internally by
  32131. * most loaders. It can also be used directly to load any file type that does
  32132. * not have a loader.
  32133. *
  32134. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32135. * once to your application.
  32136. *
  32137. * ```js
  32138. * const loader = new THREE.FileLoader();
  32139. * const data = await loader.loadAsync( 'example.txt' );
  32140. * ```
  32141. *
  32142. * @augments Loader
  32143. */
  32144. class FileLoader extends Loader {
  32145. /**
  32146. * Constructs a new file loader.
  32147. *
  32148. * @param {LoadingManager} [manager] - The loading manager.
  32149. */
  32150. constructor( manager ) {
  32151. super( manager );
  32152. /**
  32153. * The expected mime type. Valid values can be found
  32154. * [here]{@link hhttps://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype}
  32155. *
  32156. * @type {string}
  32157. */
  32158. this.mimeType = '';
  32159. /**
  32160. * The expected response type.
  32161. *
  32162. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32163. * @default ''
  32164. */
  32165. this.responseType = '';
  32166. /**
  32167. * Used for aborting requests.
  32168. *
  32169. * @private
  32170. * @type {AbortController}
  32171. */
  32172. this._abortController = new AbortController();
  32173. }
  32174. /**
  32175. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32176. *
  32177. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32178. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32179. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32180. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32181. * @return {any|undefined} The cached resource if available.
  32182. */
  32183. load( url, onLoad, onProgress, onError ) {
  32184. if ( url === undefined ) url = '';
  32185. if ( this.path !== undefined ) url = this.path + url;
  32186. url = this.manager.resolveURL( url );
  32187. const cached = Cache.get( `file:${url}` );
  32188. if ( cached !== undefined ) {
  32189. this.manager.itemStart( url );
  32190. setTimeout( () => {
  32191. if ( onLoad ) onLoad( cached );
  32192. this.manager.itemEnd( url );
  32193. }, 0 );
  32194. return cached;
  32195. }
  32196. // Check if request is duplicate
  32197. if ( loading[ url ] !== undefined ) {
  32198. loading[ url ].push( {
  32199. onLoad: onLoad,
  32200. onProgress: onProgress,
  32201. onError: onError
  32202. } );
  32203. return;
  32204. }
  32205. // Initialise array for duplicate requests
  32206. loading[ url ] = [];
  32207. loading[ url ].push( {
  32208. onLoad: onLoad,
  32209. onProgress: onProgress,
  32210. onError: onError,
  32211. } );
  32212. // create request
  32213. const req = new Request( url, {
  32214. headers: new Headers( this.requestHeader ),
  32215. credentials: this.withCredentials ? 'include' : 'same-origin',
  32216. signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal
  32217. } );
  32218. // record states ( avoid data race )
  32219. const mimeType = this.mimeType;
  32220. const responseType = this.responseType;
  32221. // start the fetch
  32222. fetch( req )
  32223. .then( response => {
  32224. if ( response.status === 200 || response.status === 0 ) {
  32225. // Some browsers return HTTP Status 0 when using non-http protocol
  32226. // e.g. 'file://' or 'data://'. Handle as success.
  32227. if ( response.status === 0 ) {
  32228. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  32229. }
  32230. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32231. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32232. return response;
  32233. }
  32234. const callbacks = loading[ url ];
  32235. const reader = response.body.getReader();
  32236. // Nginx needs X-File-Size check
  32237. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32238. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32239. const total = contentLength ? parseInt( contentLength ) : 0;
  32240. const lengthComputable = total !== 0;
  32241. let loaded = 0;
  32242. // periodically read data into the new stream tracking while download progress
  32243. const stream = new ReadableStream( {
  32244. start( controller ) {
  32245. readData();
  32246. function readData() {
  32247. reader.read().then( ( { done, value } ) => {
  32248. if ( done ) {
  32249. controller.close();
  32250. } else {
  32251. loaded += value.byteLength;
  32252. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32253. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32254. const callback = callbacks[ i ];
  32255. if ( callback.onProgress ) callback.onProgress( event );
  32256. }
  32257. controller.enqueue( value );
  32258. readData();
  32259. }
  32260. }, ( e ) => {
  32261. controller.error( e );
  32262. } );
  32263. }
  32264. }
  32265. } );
  32266. return new Response( stream );
  32267. } else {
  32268. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32269. }
  32270. } )
  32271. .then( response => {
  32272. switch ( responseType ) {
  32273. case 'arraybuffer':
  32274. return response.arrayBuffer();
  32275. case 'blob':
  32276. return response.blob();
  32277. case 'document':
  32278. return response.text()
  32279. .then( text => {
  32280. const parser = new DOMParser();
  32281. return parser.parseFromString( text, mimeType );
  32282. } );
  32283. case 'json':
  32284. return response.json();
  32285. default:
  32286. if ( mimeType === '' ) {
  32287. return response.text();
  32288. } else {
  32289. // sniff encoding
  32290. const re = /charset="?([^;"\s]*)"?/i;
  32291. const exec = re.exec( mimeType );
  32292. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32293. const decoder = new TextDecoder( label );
  32294. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32295. }
  32296. }
  32297. } )
  32298. .then( data => {
  32299. // Add to cache only on HTTP success, so that we do not cache
  32300. // error response bodies as proper responses to requests.
  32301. Cache.add( `file:${url}`, data );
  32302. const callbacks = loading[ url ];
  32303. delete loading[ url ];
  32304. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32305. const callback = callbacks[ i ];
  32306. if ( callback.onLoad ) callback.onLoad( data );
  32307. }
  32308. } )
  32309. .catch( err => {
  32310. // Abort errors and other errors are handled the same
  32311. const callbacks = loading[ url ];
  32312. if ( callbacks === undefined ) {
  32313. // When onLoad was called and url was deleted in `loading`
  32314. this.manager.itemError( url );
  32315. throw err;
  32316. }
  32317. delete loading[ url ];
  32318. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32319. const callback = callbacks[ i ];
  32320. if ( callback.onError ) callback.onError( err );
  32321. }
  32322. this.manager.itemError( url );
  32323. } )
  32324. .finally( () => {
  32325. this.manager.itemEnd( url );
  32326. } );
  32327. this.manager.itemStart( url );
  32328. }
  32329. /**
  32330. * Sets the expected response type.
  32331. *
  32332. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32333. * @return {FileLoader} A reference to this file loader.
  32334. */
  32335. setResponseType( value ) {
  32336. this.responseType = value;
  32337. return this;
  32338. }
  32339. /**
  32340. * Sets the expected mime type of the loaded file.
  32341. *
  32342. * @param {string} value - The mime type.
  32343. * @return {FileLoader} A reference to this file loader.
  32344. */
  32345. setMimeType( value ) {
  32346. this.mimeType = value;
  32347. return this;
  32348. }
  32349. /**
  32350. * Aborts ongoing fetch requests.
  32351. *
  32352. * @return {FileLoader} A reference to this instance.
  32353. */
  32354. abort() {
  32355. this._abortController.abort();
  32356. this._abortController = new AbortController();
  32357. return this;
  32358. }
  32359. }
  32360. /**
  32361. * Class for loading animation clips in the JSON format. The files are internally
  32362. * loaded via {@link FileLoader}.
  32363. *
  32364. * ```js
  32365. * const loader = new THREE.AnimationLoader();
  32366. * const animations = await loader.loadAsync( 'animations/animation.js' );
  32367. * ```
  32368. *
  32369. * @augments Loader
  32370. */
  32371. class AnimationLoader extends Loader {
  32372. /**
  32373. * Constructs a new animation loader.
  32374. *
  32375. * @param {LoadingManager} [manager] - The loading manager.
  32376. */
  32377. constructor( manager ) {
  32378. super( manager );
  32379. }
  32380. /**
  32381. * Starts loading from the given URL and pass the loaded animations as an array
  32382. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  32383. *
  32384. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32385. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  32386. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32387. * @param {onErrorCallback} onError - Executed when errors occur.
  32388. */
  32389. load( url, onLoad, onProgress, onError ) {
  32390. const scope = this;
  32391. const loader = new FileLoader( this.manager );
  32392. loader.setPath( this.path );
  32393. loader.setRequestHeader( this.requestHeader );
  32394. loader.setWithCredentials( this.withCredentials );
  32395. loader.load( url, function ( text ) {
  32396. try {
  32397. onLoad( scope.parse( JSON.parse( text ) ) );
  32398. } catch ( e ) {
  32399. if ( onError ) {
  32400. onError( e );
  32401. } else {
  32402. console.error( e );
  32403. }
  32404. scope.manager.itemError( url );
  32405. }
  32406. }, onProgress, onError );
  32407. }
  32408. /**
  32409. * Parses the given JSON object and returns an array of animation clips.
  32410. *
  32411. * @param {Object} json - The serialized animation clips.
  32412. * @return {Array<AnimationClip>} The parsed animation clips.
  32413. */
  32414. parse( json ) {
  32415. const animations = [];
  32416. for ( let i = 0; i < json.length; i ++ ) {
  32417. const clip = AnimationClip.parse( json[ i ] );
  32418. animations.push( clip );
  32419. }
  32420. return animations;
  32421. }
  32422. }
  32423. /**
  32424. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  32425. * Textures are internally loaded via {@link FileLoader}.
  32426. *
  32427. * Derived classes have to implement the `parse()` method which holds the parsing
  32428. * for the respective format.
  32429. *
  32430. * @abstract
  32431. * @augments Loader
  32432. */
  32433. class CompressedTextureLoader extends Loader {
  32434. /**
  32435. * Constructs a new compressed texture loader.
  32436. *
  32437. * @param {LoadingManager} [manager] - The loading manager.
  32438. */
  32439. constructor( manager ) {
  32440. super( manager );
  32441. }
  32442. /**
  32443. * Starts loading from the given URL and passes the loaded compressed texture
  32444. * to the `onLoad()` callback. The method also returns a new texture object which can
  32445. * directly be used for material creation. If you do it this way, the texture
  32446. * may pop up in your scene once the respective loading process is finished.
  32447. *
  32448. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32449. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  32450. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32451. * @param {onErrorCallback} onError - Executed when errors occur.
  32452. * @return {CompressedTexture} The compressed texture.
  32453. */
  32454. load( url, onLoad, onProgress, onError ) {
  32455. const scope = this;
  32456. const images = [];
  32457. const texture = new CompressedTexture();
  32458. const loader = new FileLoader( this.manager );
  32459. loader.setPath( this.path );
  32460. loader.setResponseType( 'arraybuffer' );
  32461. loader.setRequestHeader( this.requestHeader );
  32462. loader.setWithCredentials( scope.withCredentials );
  32463. let loaded = 0;
  32464. function loadTexture( i ) {
  32465. loader.load( url[ i ], function ( buffer ) {
  32466. const texDatas = scope.parse( buffer, true );
  32467. images[ i ] = {
  32468. width: texDatas.width,
  32469. height: texDatas.height,
  32470. format: texDatas.format,
  32471. mipmaps: texDatas.mipmaps
  32472. };
  32473. loaded += 1;
  32474. if ( loaded === 6 ) {
  32475. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  32476. texture.image = images;
  32477. texture.format = texDatas.format;
  32478. texture.needsUpdate = true;
  32479. if ( onLoad ) onLoad( texture );
  32480. }
  32481. }, onProgress, onError );
  32482. }
  32483. if ( Array.isArray( url ) ) {
  32484. for ( let i = 0, il = url.length; i < il; ++ i ) {
  32485. loadTexture( i );
  32486. }
  32487. } else {
  32488. // compressed cubemap texture stored in a single DDS file
  32489. loader.load( url, function ( buffer ) {
  32490. const texDatas = scope.parse( buffer, true );
  32491. if ( texDatas.isCubemap ) {
  32492. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  32493. for ( let f = 0; f < faces; f ++ ) {
  32494. images[ f ] = { mipmaps: [] };
  32495. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  32496. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  32497. images[ f ].format = texDatas.format;
  32498. images[ f ].width = texDatas.width;
  32499. images[ f ].height = texDatas.height;
  32500. }
  32501. }
  32502. texture.image = images;
  32503. } else {
  32504. texture.image.width = texDatas.width;
  32505. texture.image.height = texDatas.height;
  32506. texture.mipmaps = texDatas.mipmaps;
  32507. }
  32508. if ( texDatas.mipmapCount === 1 ) {
  32509. texture.minFilter = LinearFilter;
  32510. }
  32511. texture.format = texDatas.format;
  32512. texture.needsUpdate = true;
  32513. if ( onLoad ) onLoad( texture );
  32514. }, onProgress, onError );
  32515. }
  32516. return texture;
  32517. }
  32518. }
  32519. const _loading = new WeakMap();
  32520. /**
  32521. * A loader for loading images. The class loads images with the HTML `Image` API.
  32522. *
  32523. * ```js
  32524. * const loader = new THREE.ImageLoader();
  32525. * const image = await loader.loadAsync( 'image.png' );
  32526. * ```
  32527. * Please note that `ImageLoader` has dropped support for progress
  32528. * events in `r84`. For an `ImageLoader` that supports progress events, see
  32529. * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639}.
  32530. *
  32531. * @augments Loader
  32532. */
  32533. class ImageLoader extends Loader {
  32534. /**
  32535. * Constructs a new image loader.
  32536. *
  32537. * @param {LoadingManager} [manager] - The loading manager.
  32538. */
  32539. constructor( manager ) {
  32540. super( manager );
  32541. }
  32542. /**
  32543. * Starts loading from the given URL and passes the loaded image
  32544. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  32545. * directly be used for texture creation. If you do it this way, the texture
  32546. * may pop up in your scene once the respective loading process is finished.
  32547. *
  32548. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32549. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  32550. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32551. * @param {onErrorCallback} onError - Executed when errors occur.
  32552. * @return {Image} The image.
  32553. */
  32554. load( url, onLoad, onProgress, onError ) {
  32555. if ( this.path !== undefined ) url = this.path + url;
  32556. url = this.manager.resolveURL( url );
  32557. const scope = this;
  32558. const cached = Cache.get( `image:${url}` );
  32559. if ( cached !== undefined ) {
  32560. if ( cached.complete === true ) {
  32561. scope.manager.itemStart( url );
  32562. setTimeout( function () {
  32563. if ( onLoad ) onLoad( cached );
  32564. scope.manager.itemEnd( url );
  32565. }, 0 );
  32566. } else {
  32567. let arr = _loading.get( cached );
  32568. if ( arr === undefined ) {
  32569. arr = [];
  32570. _loading.set( cached, arr );
  32571. }
  32572. arr.push( { onLoad, onError } );
  32573. }
  32574. return cached;
  32575. }
  32576. const image = createElementNS( 'img' );
  32577. function onImageLoad() {
  32578. removeEventListeners();
  32579. if ( onLoad ) onLoad( this );
  32580. //
  32581. const callbacks = _loading.get( this ) || [];
  32582. for ( let i = 0; i < callbacks.length; i ++ ) {
  32583. const callback = callbacks[ i ];
  32584. if ( callback.onLoad ) callback.onLoad( this );
  32585. }
  32586. _loading.delete( this );
  32587. scope.manager.itemEnd( url );
  32588. }
  32589. function onImageError( event ) {
  32590. removeEventListeners();
  32591. if ( onError ) onError( event );
  32592. Cache.remove( `image:${url}` );
  32593. //
  32594. const callbacks = _loading.get( this ) || [];
  32595. for ( let i = 0; i < callbacks.length; i ++ ) {
  32596. const callback = callbacks[ i ];
  32597. if ( callback.onError ) callback.onError( event );
  32598. }
  32599. _loading.delete( this );
  32600. scope.manager.itemError( url );
  32601. scope.manager.itemEnd( url );
  32602. }
  32603. function removeEventListeners() {
  32604. image.removeEventListener( 'load', onImageLoad, false );
  32605. image.removeEventListener( 'error', onImageError, false );
  32606. }
  32607. image.addEventListener( 'load', onImageLoad, false );
  32608. image.addEventListener( 'error', onImageError, false );
  32609. if ( url.slice( 0, 5 ) !== 'data:' ) {
  32610. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  32611. }
  32612. Cache.add( `image:${url}`, image );
  32613. scope.manager.itemStart( url );
  32614. image.src = url;
  32615. return image;
  32616. }
  32617. }
  32618. /**
  32619. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  32620. *
  32621. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  32622. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  32623. * like vertical and horizontal cross, column and row layouts are not supported.
  32624. *
  32625. * Note that, by convention, cube maps are specified in a coordinate system
  32626. * in which positive-x is to the right when looking up the positive-z axis --
  32627. * in other words, using a left-handed coordinate system. Since three.js uses
  32628. * a right-handed coordinate system, environment maps used in three.js will
  32629. * have pos-x and neg-x swapped.
  32630. *
  32631. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  32632. * is set to `SRGBColorSpace` by default.
  32633. *
  32634. * ```js
  32635. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  32636. * const cubeTexture = await loader.loadAsync( [
  32637. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  32638. * ] );
  32639. * scene.background = cubeTexture;
  32640. * ```
  32641. *
  32642. * @augments Loader
  32643. */
  32644. class CubeTextureLoader extends Loader {
  32645. /**
  32646. * Constructs a new cube texture loader.
  32647. *
  32648. * @param {LoadingManager} [manager] - The loading manager.
  32649. */
  32650. constructor( manager ) {
  32651. super( manager );
  32652. }
  32653. /**
  32654. * Starts loading from the given URL and pass the fully loaded cube texture
  32655. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  32656. * directly be used for material creation. If you do it this way, the cube texture
  32657. * may pop up in your scene once the respective loading process is finished.
  32658. *
  32659. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  32660. * cube texture. The urls should be specified in the following order: pos-x,
  32661. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  32662. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  32663. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32664. * @param {onErrorCallback} onError - Executed when errors occur.
  32665. * @return {CubeTexture} The cube texture.
  32666. */
  32667. load( urls, onLoad, onProgress, onError ) {
  32668. const texture = new CubeTexture();
  32669. texture.colorSpace = SRGBColorSpace;
  32670. const loader = new ImageLoader( this.manager );
  32671. loader.setCrossOrigin( this.crossOrigin );
  32672. loader.setPath( this.path );
  32673. let loaded = 0;
  32674. function loadTexture( i ) {
  32675. loader.load( urls[ i ], function ( image ) {
  32676. texture.images[ i ] = image;
  32677. loaded ++;
  32678. if ( loaded === 6 ) {
  32679. texture.needsUpdate = true;
  32680. if ( onLoad ) onLoad( texture );
  32681. }
  32682. }, undefined, onError );
  32683. }
  32684. for ( let i = 0; i < urls.length; ++ i ) {
  32685. loadTexture( i );
  32686. }
  32687. return texture;
  32688. }
  32689. }
  32690. /**
  32691. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  32692. * Textures are internally loaded via {@link FileLoader}.
  32693. *
  32694. * Derived classes have to implement the `parse()` method which holds the parsing
  32695. * for the respective format.
  32696. *
  32697. * @abstract
  32698. * @augments Loader
  32699. */
  32700. class DataTextureLoader extends Loader {
  32701. /**
  32702. * Constructs a new data 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 passes the loaded data texture
  32711. * to the `onLoad()` callback. The method also returns a new texture object which can
  32712. * directly be used for material creation. If you do it this way, the texture
  32713. * may pop up in your scene once the respective loading process is finished.
  32714. *
  32715. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32716. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  32717. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32718. * @param {onErrorCallback} onError - Executed when errors occur.
  32719. * @return {DataTexture} The data texture.
  32720. */
  32721. load( url, onLoad, onProgress, onError ) {
  32722. const scope = this;
  32723. const texture = new DataTexture();
  32724. const loader = new FileLoader( this.manager );
  32725. loader.setResponseType( 'arraybuffer' );
  32726. loader.setRequestHeader( this.requestHeader );
  32727. loader.setPath( this.path );
  32728. loader.setWithCredentials( scope.withCredentials );
  32729. loader.load( url, function ( buffer ) {
  32730. let texData;
  32731. try {
  32732. texData = scope.parse( buffer );
  32733. } catch ( error ) {
  32734. if ( onError !== undefined ) {
  32735. onError( error );
  32736. } else {
  32737. console.error( error );
  32738. return;
  32739. }
  32740. }
  32741. if ( texData.image !== undefined ) {
  32742. texture.image = texData.image;
  32743. } else if ( texData.data !== undefined ) {
  32744. texture.image.width = texData.width;
  32745. texture.image.height = texData.height;
  32746. texture.image.data = texData.data;
  32747. }
  32748. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  32749. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  32750. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  32751. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  32752. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  32753. if ( texData.colorSpace !== undefined ) {
  32754. texture.colorSpace = texData.colorSpace;
  32755. }
  32756. if ( texData.flipY !== undefined ) {
  32757. texture.flipY = texData.flipY;
  32758. }
  32759. if ( texData.format !== undefined ) {
  32760. texture.format = texData.format;
  32761. }
  32762. if ( texData.type !== undefined ) {
  32763. texture.type = texData.type;
  32764. }
  32765. if ( texData.mipmaps !== undefined ) {
  32766. texture.mipmaps = texData.mipmaps;
  32767. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  32768. }
  32769. if ( texData.mipmapCount === 1 ) {
  32770. texture.minFilter = LinearFilter;
  32771. }
  32772. if ( texData.generateMipmaps !== undefined ) {
  32773. texture.generateMipmaps = texData.generateMipmaps;
  32774. }
  32775. texture.needsUpdate = true;
  32776. if ( onLoad ) onLoad( texture, texData );
  32777. }, onProgress, onError );
  32778. return texture;
  32779. }
  32780. }
  32781. /**
  32782. * Class for loading textures. Images are internally
  32783. * loaded via {@link ImageLoader}.
  32784. *
  32785. * ```js
  32786. * const loader = new THREE.TextureLoader();
  32787. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  32788. *
  32789. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  32790. * ```
  32791. * Please note that `TextureLoader` has dropped support for progress
  32792. * events in `r84`. For a `TextureLoader` that supports progress events, see
  32793. * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145}.
  32794. *
  32795. * @augments Loader
  32796. */
  32797. class TextureLoader extends Loader {
  32798. /**
  32799. * Constructs a new texture loader.
  32800. *
  32801. * @param {LoadingManager} [manager] - The loading manager.
  32802. */
  32803. constructor( manager ) {
  32804. super( manager );
  32805. }
  32806. /**
  32807. * Starts loading from the given URL and pass the fully loaded texture
  32808. * to the `onLoad()` callback. The method also returns a new texture object which can
  32809. * directly be used for material creation. If you do it this way, the texture
  32810. * may pop up in your scene once the respective loading process is finished.
  32811. *
  32812. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32813. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  32814. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32815. * @param {onErrorCallback} onError - Executed when errors occur.
  32816. * @return {Texture} The texture.
  32817. */
  32818. load( url, onLoad, onProgress, onError ) {
  32819. const texture = new Texture();
  32820. const loader = new ImageLoader( this.manager );
  32821. loader.setCrossOrigin( this.crossOrigin );
  32822. loader.setPath( this.path );
  32823. loader.load( url, function ( image ) {
  32824. texture.image = image;
  32825. texture.needsUpdate = true;
  32826. if ( onLoad !== undefined ) {
  32827. onLoad( texture );
  32828. }
  32829. }, onProgress, onError );
  32830. return texture;
  32831. }
  32832. }
  32833. /**
  32834. * Abstract base class for lights - all other light types inherit the
  32835. * properties and methods described here.
  32836. *
  32837. * @abstract
  32838. * @augments Object3D
  32839. */
  32840. class Light extends Object3D {
  32841. /**
  32842. * Constructs a new light.
  32843. *
  32844. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  32845. * @param {number} [intensity=1] - The light's strength/intensity.
  32846. */
  32847. constructor( color, intensity = 1 ) {
  32848. super();
  32849. /**
  32850. * This flag can be used for type testing.
  32851. *
  32852. * @type {boolean}
  32853. * @readonly
  32854. * @default true
  32855. */
  32856. this.isLight = true;
  32857. this.type = 'Light';
  32858. /**
  32859. * The light's color.
  32860. *
  32861. * @type {Color}
  32862. */
  32863. this.color = new Color( color );
  32864. /**
  32865. * The light's intensity.
  32866. *
  32867. * @type {number}
  32868. * @default 1
  32869. */
  32870. this.intensity = intensity;
  32871. }
  32872. /**
  32873. * Frees the GPU-related resources allocated by this instance. Call this
  32874. * method whenever this instance is no longer used in your app.
  32875. */
  32876. dispose() {
  32877. // Empty here in base class; some subclasses override.
  32878. }
  32879. copy( source, recursive ) {
  32880. super.copy( source, recursive );
  32881. this.color.copy( source.color );
  32882. this.intensity = source.intensity;
  32883. return this;
  32884. }
  32885. toJSON( meta ) {
  32886. const data = super.toJSON( meta );
  32887. data.object.color = this.color.getHex();
  32888. data.object.intensity = this.intensity;
  32889. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  32890. if ( this.distance !== undefined ) data.object.distance = this.distance;
  32891. if ( this.angle !== undefined ) data.object.angle = this.angle;
  32892. if ( this.decay !== undefined ) data.object.decay = this.decay;
  32893. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  32894. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  32895. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  32896. return data;
  32897. }
  32898. }
  32899. /**
  32900. * A light source positioned directly above the scene, with color fading from
  32901. * the sky color to the ground color.
  32902. *
  32903. * This light cannot be used to cast shadows.
  32904. *
  32905. * ```js
  32906. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  32907. * scene.add( light );
  32908. * ```
  32909. *
  32910. * @augments Light
  32911. */
  32912. class HemisphereLight extends Light {
  32913. /**
  32914. * Constructs a new hemisphere light.
  32915. *
  32916. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  32917. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  32918. * @param {number} [intensity=1] - The light's strength/intensity.
  32919. */
  32920. constructor( skyColor, groundColor, intensity ) {
  32921. super( skyColor, intensity );
  32922. /**
  32923. * This flag can be used for type testing.
  32924. *
  32925. * @type {boolean}
  32926. * @readonly
  32927. * @default true
  32928. */
  32929. this.isHemisphereLight = true;
  32930. this.type = 'HemisphereLight';
  32931. this.position.copy( Object3D.DEFAULT_UP );
  32932. this.updateMatrix();
  32933. /**
  32934. * The light's ground color.
  32935. *
  32936. * @type {Color}
  32937. */
  32938. this.groundColor = new Color( groundColor );
  32939. }
  32940. copy( source, recursive ) {
  32941. super.copy( source, recursive );
  32942. this.groundColor.copy( source.groundColor );
  32943. return this;
  32944. }
  32945. }
  32946. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  32947. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  32948. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  32949. /**
  32950. * Abstract base class for light shadow classes. These classes
  32951. * represent the shadow configuration for different light types.
  32952. *
  32953. * @abstract
  32954. */
  32955. class LightShadow {
  32956. /**
  32957. * Constructs a new light shadow.
  32958. *
  32959. * @param {Camera} camera - The light's view of the world.
  32960. */
  32961. constructor( camera ) {
  32962. /**
  32963. * The light's view of the world.
  32964. *
  32965. * @type {Camera}
  32966. */
  32967. this.camera = camera;
  32968. /**
  32969. * The intensity of the shadow. The default is `1`.
  32970. * Valid values are in the range `[0, 1]`.
  32971. *
  32972. * @type {number}
  32973. * @default 1
  32974. */
  32975. this.intensity = 1;
  32976. /**
  32977. * Shadow map bias, how much to add or subtract from the normalized depth
  32978. * when deciding whether a surface is in shadow.
  32979. *
  32980. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  32981. * may help reduce artifacts in shadows.
  32982. *
  32983. * @type {number}
  32984. * @default 0
  32985. */
  32986. this.bias = 0;
  32987. /**
  32988. * Defines how much the position used to query the shadow map is offset along
  32989. * the object normal. The default is `0`. Increasing this value can be used to
  32990. * reduce shadow acne especially in large scenes where light shines onto
  32991. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  32992. *
  32993. * @type {number}
  32994. * @default 0
  32995. */
  32996. this.normalBias = 0;
  32997. /**
  32998. * Setting this to values greater than 1 will blur the edges of the shadow.
  32999. * High values will cause unwanted banding effects in the shadows - a greater
  33000. * map size will allow for a higher value to be used here before these effects
  33001. * become visible.
  33002. *
  33003. * The property has no effect when the shadow map type is `PCFSoftShadowMap` and
  33004. * and it is recommended to increase softness by decreasing the shadow map size instead.
  33005. *
  33006. * The property has no effect when the shadow map type is `BasicShadowMap`.
  33007. *
  33008. * @type {number}
  33009. * @default 1
  33010. */
  33011. this.radius = 1;
  33012. /**
  33013. * The amount of samples to use when blurring a VSM shadow map.
  33014. *
  33015. * @type {number}
  33016. * @default 8
  33017. */
  33018. this.blurSamples = 8;
  33019. /**
  33020. * Defines the width and height of the shadow map. Higher values give better quality
  33021. * shadows at the cost of computation time. Values must be powers of two.
  33022. *
  33023. * @type {Vector2}
  33024. * @default (512,512)
  33025. */
  33026. this.mapSize = new Vector2( 512, 512 );
  33027. /**
  33028. * The type of shadow texture. The default is `UnsignedByteType`.
  33029. *
  33030. * @type {number}
  33031. * @default UnsignedByteType
  33032. */
  33033. this.mapType = UnsignedByteType;
  33034. /**
  33035. * The depth map generated using the internal camera; a location beyond a
  33036. * pixel's depth is in shadow. Computed internally during rendering.
  33037. *
  33038. * @type {?RenderTarget}
  33039. * @default null
  33040. */
  33041. this.map = null;
  33042. /**
  33043. * The distribution map generated using the internal camera; an occlusion is
  33044. * calculated based on the distribution of depths. Computed internally during
  33045. * rendering.
  33046. *
  33047. * @type {?RenderTarget}
  33048. * @default null
  33049. */
  33050. this.mapPass = null;
  33051. /**
  33052. * Model to shadow camera space, to compute location and depth in shadow map.
  33053. * This is computed internally during rendering.
  33054. *
  33055. * @type {Matrix4}
  33056. */
  33057. this.matrix = new Matrix4();
  33058. /**
  33059. * Enables automatic updates of the light's shadow. If you do not require dynamic
  33060. * lighting / shadows, you may set this to `false`.
  33061. *
  33062. * @type {boolean}
  33063. * @default true
  33064. */
  33065. this.autoUpdate = true;
  33066. /**
  33067. * When set to `true`, shadow maps will be updated in the next `render` call.
  33068. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  33069. * set this property to `true` and then make a render call to update the light's shadow.
  33070. *
  33071. * @type {boolean}
  33072. * @default false
  33073. */
  33074. this.needsUpdate = false;
  33075. this._frustum = new Frustum();
  33076. this._frameExtents = new Vector2( 1, 1 );
  33077. this._viewportCount = 1;
  33078. this._viewports = [
  33079. new Vector4( 0, 0, 1, 1 )
  33080. ];
  33081. }
  33082. /**
  33083. * Used internally by the renderer to get the number of viewports that need
  33084. * to be rendered for this shadow.
  33085. *
  33086. * @return {number} The viewport count.
  33087. */
  33088. getViewportCount() {
  33089. return this._viewportCount;
  33090. }
  33091. /**
  33092. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  33093. *
  33094. * @return {Frustum} The shadow camera frustum.
  33095. */
  33096. getFrustum() {
  33097. return this._frustum;
  33098. }
  33099. /**
  33100. * Update the matrices for the camera and shadow, used internally by the renderer.
  33101. *
  33102. * @param {Light} light - The light for which the shadow is being rendered.
  33103. */
  33104. updateMatrices( light ) {
  33105. const shadowCamera = this.camera;
  33106. const shadowMatrix = this.matrix;
  33107. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  33108. shadowCamera.position.copy( _lightPositionWorld$1 );
  33109. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  33110. shadowCamera.lookAt( _lookTarget$1 );
  33111. shadowCamera.updateMatrixWorld();
  33112. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  33113. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1, shadowCamera.coordinateSystem, shadowCamera.reversedDepth );
  33114. if ( shadowCamera.reversedDepth ) {
  33115. shadowMatrix.set(
  33116. 0.5, 0.0, 0.0, 0.5,
  33117. 0.0, 0.5, 0.0, 0.5,
  33118. 0.0, 0.0, 1.0, 0.0,
  33119. 0.0, 0.0, 0.0, 1.0
  33120. );
  33121. } else {
  33122. shadowMatrix.set(
  33123. 0.5, 0.0, 0.0, 0.5,
  33124. 0.0, 0.5, 0.0, 0.5,
  33125. 0.0, 0.0, 0.5, 0.5,
  33126. 0.0, 0.0, 0.0, 1.0
  33127. );
  33128. }
  33129. shadowMatrix.multiply( _projScreenMatrix$1 );
  33130. }
  33131. /**
  33132. * Returns a viewport definition for the given viewport index.
  33133. *
  33134. * @param {number} viewportIndex - The viewport index.
  33135. * @return {Vector4} The viewport.
  33136. */
  33137. getViewport( viewportIndex ) {
  33138. return this._viewports[ viewportIndex ];
  33139. }
  33140. /**
  33141. * Returns the frame extends.
  33142. *
  33143. * @return {Vector2} The frame extends.
  33144. */
  33145. getFrameExtents() {
  33146. return this._frameExtents;
  33147. }
  33148. /**
  33149. * Frees the GPU-related resources allocated by this instance. Call this
  33150. * method whenever this instance is no longer used in your app.
  33151. */
  33152. dispose() {
  33153. if ( this.map ) {
  33154. this.map.dispose();
  33155. }
  33156. if ( this.mapPass ) {
  33157. this.mapPass.dispose();
  33158. }
  33159. }
  33160. /**
  33161. * Copies the values of the given light shadow instance to this instance.
  33162. *
  33163. * @param {LightShadow} source - The light shadow to copy.
  33164. * @return {LightShadow} A reference to this light shadow instance.
  33165. */
  33166. copy( source ) {
  33167. this.camera = source.camera.clone();
  33168. this.intensity = source.intensity;
  33169. this.bias = source.bias;
  33170. this.radius = source.radius;
  33171. this.autoUpdate = source.autoUpdate;
  33172. this.needsUpdate = source.needsUpdate;
  33173. this.normalBias = source.normalBias;
  33174. this.blurSamples = source.blurSamples;
  33175. this.mapSize.copy( source.mapSize );
  33176. return this;
  33177. }
  33178. /**
  33179. * Returns a new light shadow instance with copied values from this instance.
  33180. *
  33181. * @return {LightShadow} A clone of this instance.
  33182. */
  33183. clone() {
  33184. return new this.constructor().copy( this );
  33185. }
  33186. /**
  33187. * Serializes the light shadow into JSON.
  33188. *
  33189. * @return {Object} A JSON object representing the serialized light shadow.
  33190. * @see {@link ObjectLoader#parse}
  33191. */
  33192. toJSON() {
  33193. const object = {};
  33194. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33195. if ( this.bias !== 0 ) object.bias = this.bias;
  33196. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33197. if ( this.radius !== 1 ) object.radius = this.radius;
  33198. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33199. object.camera = this.camera.toJSON( false ).object;
  33200. delete object.camera.matrix;
  33201. return object;
  33202. }
  33203. }
  33204. /**
  33205. * Represents the shadow configuration of directional lights.
  33206. *
  33207. * @augments LightShadow
  33208. */
  33209. class SpotLightShadow extends LightShadow {
  33210. /**
  33211. * Constructs a new spot light shadow.
  33212. */
  33213. constructor() {
  33214. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  33215. /**
  33216. * This flag can be used for type testing.
  33217. *
  33218. * @type {boolean}
  33219. * @readonly
  33220. * @default true
  33221. */
  33222. this.isSpotLightShadow = true;
  33223. /**
  33224. * Used to focus the shadow camera. The camera's field of view is set as a
  33225. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  33226. *
  33227. * @type {number}
  33228. * @default 1
  33229. */
  33230. this.focus = 1;
  33231. /**
  33232. * Texture aspect ratio.
  33233. *
  33234. * @type {number}
  33235. * @default 1
  33236. */
  33237. this.aspect = 1;
  33238. }
  33239. updateMatrices( light ) {
  33240. const camera = this.camera;
  33241. const fov = RAD2DEG * 2 * light.angle * this.focus;
  33242. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  33243. const far = light.distance || camera.far;
  33244. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  33245. camera.fov = fov;
  33246. camera.aspect = aspect;
  33247. camera.far = far;
  33248. camera.updateProjectionMatrix();
  33249. }
  33250. super.updateMatrices( light );
  33251. }
  33252. copy( source ) {
  33253. super.copy( source );
  33254. this.focus = source.focus;
  33255. return this;
  33256. }
  33257. }
  33258. /**
  33259. * This light gets emitted from a single point in one direction, along a cone
  33260. * that increases in size the further from the light it gets.
  33261. *
  33262. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  33263. *
  33264. * ```js
  33265. * // white spotlight shining from the side, modulated by a texture
  33266. * const spotLight = new THREE.SpotLight( 0xffffff );
  33267. * spotLight.position.set( 100, 1000, 100 );
  33268. * spotLight.map = new THREE.TextureLoader().load( url );
  33269. *
  33270. * spotLight.castShadow = true;
  33271. * spotLight.shadow.mapSize.width = 1024;
  33272. * spotLight.shadow.mapSize.height = 1024;
  33273. * spotLight.shadow.camera.near = 500;
  33274. * spotLight.shadow.camera.far = 4000;
  33275. * spotLight.shadow.camera.fov = 30;s
  33276. * ```
  33277. *
  33278. * @augments Light
  33279. */
  33280. class SpotLight extends Light {
  33281. /**
  33282. * Constructs a new spot light.
  33283. *
  33284. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33285. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33286. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33287. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33288. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  33289. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33290. */
  33291. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  33292. super( color, intensity );
  33293. /**
  33294. * This flag can be used for type testing.
  33295. *
  33296. * @type {boolean}
  33297. * @readonly
  33298. * @default true
  33299. */
  33300. this.isSpotLight = true;
  33301. this.type = 'SpotLight';
  33302. this.position.copy( Object3D.DEFAULT_UP );
  33303. this.updateMatrix();
  33304. /**
  33305. * The spot light points from its position to the
  33306. * target's position.
  33307. *
  33308. * For the target's position to be changed to anything other
  33309. * than the default, it must be added to the scene.
  33310. *
  33311. * It is also possible to set the target to be another 3D object
  33312. * in the scene. The light will now track the target object.
  33313. *
  33314. * @type {Object3D}
  33315. */
  33316. this.target = new Object3D();
  33317. /**
  33318. * Maximum range of the light. `0` means no limit.
  33319. *
  33320. * @type {number}
  33321. * @default 0
  33322. */
  33323. this.distance = distance;
  33324. /**
  33325. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33326. *
  33327. * @type {number}
  33328. * @default Math.PI/3
  33329. */
  33330. this.angle = angle;
  33331. /**
  33332. * Percent of the spotlight cone that is attenuated due to penumbra.
  33333. * Value range is `[0,1]`.
  33334. *
  33335. * @type {number}
  33336. * @default 0
  33337. */
  33338. this.penumbra = penumbra;
  33339. /**
  33340. * The amount the light dims along the distance of the light. In context of
  33341. * physically-correct rendering the default value should not be changed.
  33342. *
  33343. * @type {number}
  33344. * @default 2
  33345. */
  33346. this.decay = decay;
  33347. /**
  33348. * A texture used to modulate the color of the light. The spot light
  33349. * color is mixed with the RGB value of this texture, with a ratio
  33350. * corresponding to its alpha value. The cookie-like masking effect is
  33351. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  33352. *
  33353. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  33354. *
  33355. * @type {?Texture}
  33356. * @default null
  33357. */
  33358. this.map = null;
  33359. /**
  33360. * This property holds the light's shadow configuration.
  33361. *
  33362. * @type {SpotLightShadow}
  33363. */
  33364. this.shadow = new SpotLightShadow();
  33365. }
  33366. /**
  33367. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33368. * Changing the power will also change the light's intensity.
  33369. *
  33370. * @type {number}
  33371. */
  33372. get power() {
  33373. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33374. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  33375. return this.intensity * Math.PI;
  33376. }
  33377. set power( power ) {
  33378. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33379. this.intensity = power / Math.PI;
  33380. }
  33381. dispose() {
  33382. this.shadow.dispose();
  33383. }
  33384. copy( source, recursive ) {
  33385. super.copy( source, recursive );
  33386. this.distance = source.distance;
  33387. this.angle = source.angle;
  33388. this.penumbra = source.penumbra;
  33389. this.decay = source.decay;
  33390. this.target = source.target.clone();
  33391. this.shadow = source.shadow.clone();
  33392. return this;
  33393. }
  33394. }
  33395. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  33396. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  33397. const _lookTarget = /*@__PURE__*/ new Vector3();
  33398. /**
  33399. * Represents the shadow configuration of point lights.
  33400. *
  33401. * @augments LightShadow
  33402. */
  33403. class PointLightShadow extends LightShadow {
  33404. /**
  33405. * Constructs a new point light shadow.
  33406. */
  33407. constructor() {
  33408. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  33409. /**
  33410. * This flag can be used for type testing.
  33411. *
  33412. * @type {boolean}
  33413. * @readonly
  33414. * @default true
  33415. */
  33416. this.isPointLightShadow = true;
  33417. this._frameExtents = new Vector2( 4, 2 );
  33418. this._viewportCount = 6;
  33419. this._viewports = [
  33420. // These viewports map a cube-map onto a 2D texture with the
  33421. // following orientation:
  33422. //
  33423. // xzXZ
  33424. // y Y
  33425. //
  33426. // X - Positive x direction
  33427. // x - Negative x direction
  33428. // Y - Positive y direction
  33429. // y - Negative y direction
  33430. // Z - Positive z direction
  33431. // z - Negative z direction
  33432. // positive X
  33433. new Vector4( 2, 1, 1, 1 ),
  33434. // negative X
  33435. new Vector4( 0, 1, 1, 1 ),
  33436. // positive Z
  33437. new Vector4( 3, 1, 1, 1 ),
  33438. // negative Z
  33439. new Vector4( 1, 1, 1, 1 ),
  33440. // positive Y
  33441. new Vector4( 3, 0, 1, 1 ),
  33442. // negative Y
  33443. new Vector4( 1, 0, 1, 1 )
  33444. ];
  33445. this._cubeDirections = [
  33446. new Vector3( 1, 0, 0 ), new Vector3( -1, 0, 0 ), new Vector3( 0, 0, 1 ),
  33447. new Vector3( 0, 0, -1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, -1, 0 )
  33448. ];
  33449. this._cubeUps = [
  33450. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  33451. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, -1 )
  33452. ];
  33453. }
  33454. /**
  33455. * Update the matrices for the camera and shadow, used internally by the renderer.
  33456. *
  33457. * @param {Light} light - The light for which the shadow is being rendered.
  33458. * @param {number} [viewportIndex=0] - The viewport index.
  33459. */
  33460. updateMatrices( light, viewportIndex = 0 ) {
  33461. const camera = this.camera;
  33462. const shadowMatrix = this.matrix;
  33463. const far = light.distance || camera.far;
  33464. if ( far !== camera.far ) {
  33465. camera.far = far;
  33466. camera.updateProjectionMatrix();
  33467. }
  33468. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  33469. camera.position.copy( _lightPositionWorld );
  33470. _lookTarget.copy( camera.position );
  33471. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  33472. camera.up.copy( this._cubeUps[ viewportIndex ] );
  33473. camera.lookAt( _lookTarget );
  33474. camera.updateMatrixWorld();
  33475. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  33476. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  33477. this._frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  33478. }
  33479. }
  33480. /**
  33481. * A light that gets emitted from a single point in all directions. A common
  33482. * use case for this is to replicate the light emitted from a bare
  33483. * lightbulb.
  33484. *
  33485. * This light can cast shadows - see the {@link PointLightShadow} for details.
  33486. *
  33487. * ```js
  33488. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  33489. * light.position.set( 50, 50, 50 );
  33490. * scene.add( light );
  33491. * ```
  33492. *
  33493. * @augments Light
  33494. */
  33495. class PointLight extends Light {
  33496. /**
  33497. * Constructs a new point light.
  33498. *
  33499. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33500. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33501. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33502. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33503. */
  33504. constructor( color, intensity, distance = 0, decay = 2 ) {
  33505. super( color, intensity );
  33506. /**
  33507. * This flag can be used for type testing.
  33508. *
  33509. * @type {boolean}
  33510. * @readonly
  33511. * @default true
  33512. */
  33513. this.isPointLight = true;
  33514. this.type = 'PointLight';
  33515. /**
  33516. * When distance is zero, light will attenuate according to inverse-square
  33517. * law to infinite distance. When distance is non-zero, light will attenuate
  33518. * according to inverse-square law until near the distance cutoff, where it
  33519. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  33520. * physically correct.
  33521. *
  33522. * @type {number}
  33523. * @default 0
  33524. */
  33525. this.distance = distance;
  33526. /**
  33527. * The amount the light dims along the distance of the light. In context of
  33528. * physically-correct rendering the default value should not be changed.
  33529. *
  33530. * @type {number}
  33531. * @default 2
  33532. */
  33533. this.decay = decay;
  33534. /**
  33535. * This property holds the light's shadow configuration.
  33536. *
  33537. * @type {PointLightShadow}
  33538. */
  33539. this.shadow = new PointLightShadow();
  33540. }
  33541. /**
  33542. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33543. * Changing the power will also change the light's intensity.
  33544. *
  33545. * @type {number}
  33546. */
  33547. get power() {
  33548. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33549. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  33550. return this.intensity * 4 * Math.PI;
  33551. }
  33552. set power( power ) {
  33553. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33554. this.intensity = power / ( 4 * Math.PI );
  33555. }
  33556. dispose() {
  33557. this.shadow.dispose();
  33558. }
  33559. copy( source, recursive ) {
  33560. super.copy( source, recursive );
  33561. this.distance = source.distance;
  33562. this.decay = source.decay;
  33563. this.shadow = source.shadow.clone();
  33564. return this;
  33565. }
  33566. }
  33567. /**
  33568. * Camera that uses [orthographic projection]{@link https://en.wikipedia.org/wiki/Orthographic_projection}.
  33569. *
  33570. * In this projection mode, an object's size in the rendered image stays
  33571. * constant regardless of its distance from the camera. This can be useful
  33572. * for rendering 2D scenes and UI elements, amongst other things.
  33573. *
  33574. * ```js
  33575. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  33576. * scene.add( camera );
  33577. * ```
  33578. *
  33579. * @augments Camera
  33580. */
  33581. class OrthographicCamera extends Camera {
  33582. /**
  33583. * Constructs a new orthographic camera.
  33584. *
  33585. * @param {number} [left=-1] - The left plane of the camera's frustum.
  33586. * @param {number} [right=1] - The right plane of the camera's frustum.
  33587. * @param {number} [top=1] - The top plane of the camera's frustum.
  33588. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  33589. * @param {number} [near=0.1] - The camera's near plane.
  33590. * @param {number} [far=2000] - The camera's far plane.
  33591. */
  33592. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  33593. super();
  33594. /**
  33595. * This flag can be used for type testing.
  33596. *
  33597. * @type {boolean}
  33598. * @readonly
  33599. * @default true
  33600. */
  33601. this.isOrthographicCamera = true;
  33602. this.type = 'OrthographicCamera';
  33603. /**
  33604. * The zoom factor of the camera.
  33605. *
  33606. * @type {number}
  33607. * @default 1
  33608. */
  33609. this.zoom = 1;
  33610. /**
  33611. * Represents the frustum window specification. This property should not be edited
  33612. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  33613. *
  33614. * @type {?Object}
  33615. * @default null
  33616. */
  33617. this.view = null;
  33618. /**
  33619. * The left plane of the camera's frustum.
  33620. *
  33621. * @type {number}
  33622. * @default -1
  33623. */
  33624. this.left = left;
  33625. /**
  33626. * The right plane of the camera's frustum.
  33627. *
  33628. * @type {number}
  33629. * @default 1
  33630. */
  33631. this.right = right;
  33632. /**
  33633. * The top plane of the camera's frustum.
  33634. *
  33635. * @type {number}
  33636. * @default 1
  33637. */
  33638. this.top = top;
  33639. /**
  33640. * The bottom plane of the camera's frustum.
  33641. *
  33642. * @type {number}
  33643. * @default -1
  33644. */
  33645. this.bottom = bottom;
  33646. /**
  33647. * The camera's near plane. The valid range is greater than `0`
  33648. * and less than the current value of {@link OrthographicCamera#far}.
  33649. *
  33650. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  33651. * valid value for an orthographic camera's near plane.
  33652. *
  33653. * @type {number}
  33654. * @default 0.1
  33655. */
  33656. this.near = near;
  33657. /**
  33658. * The camera's far plane. Must be greater than the
  33659. * current value of {@link OrthographicCamera#near}.
  33660. *
  33661. * @type {number}
  33662. * @default 2000
  33663. */
  33664. this.far = far;
  33665. this.updateProjectionMatrix();
  33666. }
  33667. copy( source, recursive ) {
  33668. super.copy( source, recursive );
  33669. this.left = source.left;
  33670. this.right = source.right;
  33671. this.top = source.top;
  33672. this.bottom = source.bottom;
  33673. this.near = source.near;
  33674. this.far = source.far;
  33675. this.zoom = source.zoom;
  33676. this.view = source.view === null ? null : Object.assign( {}, source.view );
  33677. return this;
  33678. }
  33679. /**
  33680. * Sets an offset in a larger frustum. This is useful for multi-window or
  33681. * multi-monitor/multi-machine setups.
  33682. *
  33683. * @param {number} fullWidth - The full width of multiview setup.
  33684. * @param {number} fullHeight - The full height of multiview setup.
  33685. * @param {number} x - The horizontal offset of the subcamera.
  33686. * @param {number} y - The vertical offset of the subcamera.
  33687. * @param {number} width - The width of subcamera.
  33688. * @param {number} height - The height of subcamera.
  33689. * @see {@link PerspectiveCamera#setViewOffset}
  33690. */
  33691. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  33692. if ( this.view === null ) {
  33693. this.view = {
  33694. enabled: true,
  33695. fullWidth: 1,
  33696. fullHeight: 1,
  33697. offsetX: 0,
  33698. offsetY: 0,
  33699. width: 1,
  33700. height: 1
  33701. };
  33702. }
  33703. this.view.enabled = true;
  33704. this.view.fullWidth = fullWidth;
  33705. this.view.fullHeight = fullHeight;
  33706. this.view.offsetX = x;
  33707. this.view.offsetY = y;
  33708. this.view.width = width;
  33709. this.view.height = height;
  33710. this.updateProjectionMatrix();
  33711. }
  33712. /**
  33713. * Removes the view offset from the projection matrix.
  33714. */
  33715. clearViewOffset() {
  33716. if ( this.view !== null ) {
  33717. this.view.enabled = false;
  33718. }
  33719. this.updateProjectionMatrix();
  33720. }
  33721. /**
  33722. * Updates the camera's projection matrix. Must be called after any change of
  33723. * camera properties.
  33724. */
  33725. updateProjectionMatrix() {
  33726. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  33727. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  33728. const cx = ( this.right + this.left ) / 2;
  33729. const cy = ( this.top + this.bottom ) / 2;
  33730. let left = cx - dx;
  33731. let right = cx + dx;
  33732. let top = cy + dy;
  33733. let bottom = cy - dy;
  33734. if ( this.view !== null && this.view.enabled ) {
  33735. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  33736. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  33737. left += scaleW * this.view.offsetX;
  33738. right = left + scaleW * this.view.width;
  33739. top -= scaleH * this.view.offsetY;
  33740. bottom = top - scaleH * this.view.height;
  33741. }
  33742. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth );
  33743. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  33744. }
  33745. toJSON( meta ) {
  33746. const data = super.toJSON( meta );
  33747. data.object.zoom = this.zoom;
  33748. data.object.left = this.left;
  33749. data.object.right = this.right;
  33750. data.object.top = this.top;
  33751. data.object.bottom = this.bottom;
  33752. data.object.near = this.near;
  33753. data.object.far = this.far;
  33754. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  33755. return data;
  33756. }
  33757. }
  33758. /**
  33759. * Represents the shadow configuration of directional lights.
  33760. *
  33761. * @augments LightShadow
  33762. */
  33763. class DirectionalLightShadow extends LightShadow {
  33764. /**
  33765. * Constructs a new directional light shadow.
  33766. */
  33767. constructor() {
  33768. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  33769. /**
  33770. * This flag can be used for type testing.
  33771. *
  33772. * @type {boolean}
  33773. * @readonly
  33774. * @default true
  33775. */
  33776. this.isDirectionalLightShadow = true;
  33777. }
  33778. }
  33779. /**
  33780. * A light that gets emitted in a specific direction. This light will behave
  33781. * as though it is infinitely far away and the rays produced from it are all
  33782. * parallel. The common use case for this is to simulate daylight; the sun is
  33783. * far enough away that its position can be considered to be infinite, and
  33784. * all light rays coming from it are parallel.
  33785. *
  33786. * A common point of confusion for directional lights is that setting the
  33787. * rotation has no effect. This is because three.js's DirectionalLight is the
  33788. * equivalent to what is often called a 'Target Direct Light' in other
  33789. * applications.
  33790. *
  33791. * This means that its direction is calculated as pointing from the light's
  33792. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  33793. * (as opposed to a 'Free Direct Light' that just has a rotation
  33794. * component).
  33795. *
  33796. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  33797. *
  33798. * ```js
  33799. * // White directional light at half intensity shining from the top.
  33800. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  33801. * scene.add( directionalLight );
  33802. * ```
  33803. *
  33804. * @augments Light
  33805. */
  33806. class DirectionalLight extends Light {
  33807. /**
  33808. * Constructs a new directional light.
  33809. *
  33810. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33811. * @param {number} [intensity=1] - The light's strength/intensity.
  33812. */
  33813. constructor( color, intensity ) {
  33814. super( color, intensity );
  33815. /**
  33816. * This flag can be used for type testing.
  33817. *
  33818. * @type {boolean}
  33819. * @readonly
  33820. * @default true
  33821. */
  33822. this.isDirectionalLight = true;
  33823. this.type = 'DirectionalLight';
  33824. this.position.copy( Object3D.DEFAULT_UP );
  33825. this.updateMatrix();
  33826. /**
  33827. * The directional light points from its position to the
  33828. * target's position.
  33829. *
  33830. * For the target's position to be changed to anything other
  33831. * than the default, it must be added to the scene.
  33832. *
  33833. * It is also possible to set the target to be another 3D object
  33834. * in the scene. The light will now track the target object.
  33835. *
  33836. * @type {Object3D}
  33837. */
  33838. this.target = new Object3D();
  33839. /**
  33840. * This property holds the light's shadow configuration.
  33841. *
  33842. * @type {DirectionalLightShadow}
  33843. */
  33844. this.shadow = new DirectionalLightShadow();
  33845. }
  33846. dispose() {
  33847. this.shadow.dispose();
  33848. }
  33849. copy( source ) {
  33850. super.copy( source );
  33851. this.target = source.target.clone();
  33852. this.shadow = source.shadow.clone();
  33853. return this;
  33854. }
  33855. }
  33856. /**
  33857. * This light globally illuminates all objects in the scene equally.
  33858. *
  33859. * It cannot be used to cast shadows as it does not have a direction.
  33860. *
  33861. * ```js
  33862. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  33863. * scene.add( light );
  33864. * ```
  33865. *
  33866. * @augments Light
  33867. */
  33868. class AmbientLight extends Light {
  33869. /**
  33870. * Constructs a new ambient light.
  33871. *
  33872. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33873. * @param {number} [intensity=1] - The light's strength/intensity.
  33874. */
  33875. constructor( color, intensity ) {
  33876. super( color, intensity );
  33877. /**
  33878. * This flag can be used for type testing.
  33879. *
  33880. * @type {boolean}
  33881. * @readonly
  33882. * @default true
  33883. */
  33884. this.isAmbientLight = true;
  33885. this.type = 'AmbientLight';
  33886. }
  33887. }
  33888. /**
  33889. * This class emits light uniformly across the face a rectangular plane.
  33890. * This light type can be used to simulate light sources such as bright
  33891. * windows or strip lighting.
  33892. *
  33893. * Important Notes:
  33894. *
  33895. * - There is no shadow support.
  33896. * - Only PBR materials are supported.
  33897. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  33898. * into your app and init the uniforms/textures.
  33899. *
  33900. * ```js
  33901. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  33902. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  33903. *
  33904. * const intensity = 1; const width = 10; const height = 10;
  33905. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  33906. * rectLight.position.set( 5, 5, 0 );
  33907. * rectLight.lookAt( 0, 0, 0 );
  33908. * scene.add( rectLight )
  33909. * ```
  33910. *
  33911. * @augments Light
  33912. */
  33913. class RectAreaLight extends Light {
  33914. /**
  33915. * Constructs a new area light.
  33916. *
  33917. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33918. * @param {number} [intensity=1] - The light's strength/intensity.
  33919. * @param {number} [width=10] - The width of the light.
  33920. * @param {number} [height=10] - The height of the light.
  33921. */
  33922. constructor( color, intensity, width = 10, height = 10 ) {
  33923. super( color, intensity );
  33924. /**
  33925. * This flag can be used for type testing.
  33926. *
  33927. * @type {boolean}
  33928. * @readonly
  33929. * @default true
  33930. */
  33931. this.isRectAreaLight = true;
  33932. this.type = 'RectAreaLight';
  33933. /**
  33934. * The width of the light.
  33935. *
  33936. * @type {number}
  33937. * @default 10
  33938. */
  33939. this.width = width;
  33940. /**
  33941. * The height of the light.
  33942. *
  33943. * @type {number}
  33944. * @default 10
  33945. */
  33946. this.height = height;
  33947. }
  33948. /**
  33949. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33950. * Changing the power will also change the light's intensity.
  33951. *
  33952. * @type {number}
  33953. */
  33954. get power() {
  33955. // compute the light's luminous power (in lumens) from its intensity (in nits)
  33956. return this.intensity * this.width * this.height * Math.PI;
  33957. }
  33958. set power( power ) {
  33959. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  33960. this.intensity = power / ( this.width * this.height * Math.PI );
  33961. }
  33962. copy( source ) {
  33963. super.copy( source );
  33964. this.width = source.width;
  33965. this.height = source.height;
  33966. return this;
  33967. }
  33968. toJSON( meta ) {
  33969. const data = super.toJSON( meta );
  33970. data.object.width = this.width;
  33971. data.object.height = this.height;
  33972. return data;
  33973. }
  33974. }
  33975. /**
  33976. * Represents a third-order spherical harmonics (SH). Light probes use this class
  33977. * to encode lighting information.
  33978. *
  33979. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  33980. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  33981. */
  33982. class SphericalHarmonics3 {
  33983. /**
  33984. * Constructs a new spherical harmonics.
  33985. */
  33986. constructor() {
  33987. /**
  33988. * This flag can be used for type testing.
  33989. *
  33990. * @type {boolean}
  33991. * @readonly
  33992. * @default true
  33993. */
  33994. this.isSphericalHarmonics3 = true;
  33995. /**
  33996. * An array holding the (9) SH coefficients.
  33997. *
  33998. * @type {Array<Vector3>}
  33999. */
  34000. this.coefficients = [];
  34001. for ( let i = 0; i < 9; i ++ ) {
  34002. this.coefficients.push( new Vector3() );
  34003. }
  34004. }
  34005. /**
  34006. * Sets the given SH coefficients to this instance by copying
  34007. * the values.
  34008. *
  34009. * @param {Array<Vector3>} coefficients - The SH coefficients.
  34010. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34011. */
  34012. set( coefficients ) {
  34013. for ( let i = 0; i < 9; i ++ ) {
  34014. this.coefficients[ i ].copy( coefficients[ i ] );
  34015. }
  34016. return this;
  34017. }
  34018. /**
  34019. * Sets all SH coefficients to `0`.
  34020. *
  34021. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34022. */
  34023. zero() {
  34024. for ( let i = 0; i < 9; i ++ ) {
  34025. this.coefficients[ i ].set( 0, 0, 0 );
  34026. }
  34027. return this;
  34028. }
  34029. /**
  34030. * Returns the radiance in the direction of the given normal.
  34031. *
  34032. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34033. * @param {Vector3} target - The target vector that is used to store the method's result.
  34034. * @return {Vector3} The radiance.
  34035. */
  34036. getAt( normal, target ) {
  34037. // normal is assumed to be unit length
  34038. const x = normal.x, y = normal.y, z = normal.z;
  34039. const coeff = this.coefficients;
  34040. // band 0
  34041. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  34042. // band 1
  34043. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  34044. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  34045. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  34046. // band 2
  34047. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  34048. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  34049. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  34050. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  34051. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  34052. return target;
  34053. }
  34054. /**
  34055. * Returns the irradiance (radiance convolved with cosine lobe) in the
  34056. * direction of the given normal.
  34057. *
  34058. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34059. * @param {Vector3} target - The target vector that is used to store the method's result.
  34060. * @return {Vector3} The irradiance.
  34061. */
  34062. getIrradianceAt( normal, target ) {
  34063. // normal is assumed to be unit length
  34064. const x = normal.x, y = normal.y, z = normal.z;
  34065. const coeff = this.coefficients;
  34066. // band 0
  34067. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  34068. // band 1
  34069. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  34070. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  34071. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  34072. // band 2
  34073. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  34074. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  34075. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  34076. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  34077. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  34078. return target;
  34079. }
  34080. /**
  34081. * Adds the given SH to this instance.
  34082. *
  34083. * @param {SphericalHarmonics3} sh - The SH to add.
  34084. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34085. */
  34086. add( sh ) {
  34087. for ( let i = 0; i < 9; i ++ ) {
  34088. this.coefficients[ i ].add( sh.coefficients[ i ] );
  34089. }
  34090. return this;
  34091. }
  34092. /**
  34093. * A convenience method for performing {@link SphericalHarmonics3#add} and
  34094. * {@link SphericalHarmonics3#scale} at once.
  34095. *
  34096. * @param {SphericalHarmonics3} sh - The SH to add.
  34097. * @param {number} s - The scale factor.
  34098. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34099. */
  34100. addScaledSH( sh, s ) {
  34101. for ( let i = 0; i < 9; i ++ ) {
  34102. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  34103. }
  34104. return this;
  34105. }
  34106. /**
  34107. * Scales this SH by the given scale factor.
  34108. *
  34109. * @param {number} s - The scale factor.
  34110. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34111. */
  34112. scale( s ) {
  34113. for ( let i = 0; i < 9; i ++ ) {
  34114. this.coefficients[ i ].multiplyScalar( s );
  34115. }
  34116. return this;
  34117. }
  34118. /**
  34119. * Linear interpolates between the given SH and this instance by the given
  34120. * alpha factor.
  34121. *
  34122. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  34123. * @param {number} alpha - The alpha factor.
  34124. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34125. */
  34126. lerp( sh, alpha ) {
  34127. for ( let i = 0; i < 9; i ++ ) {
  34128. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  34129. }
  34130. return this;
  34131. }
  34132. /**
  34133. * Returns `true` if this spherical harmonics is equal with the given one.
  34134. *
  34135. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  34136. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  34137. */
  34138. equals( sh ) {
  34139. for ( let i = 0; i < 9; i ++ ) {
  34140. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  34141. return false;
  34142. }
  34143. }
  34144. return true;
  34145. }
  34146. /**
  34147. * Copies the values of the given spherical harmonics to this instance.
  34148. *
  34149. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  34150. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34151. */
  34152. copy( sh ) {
  34153. return this.set( sh.coefficients );
  34154. }
  34155. /**
  34156. * Returns a new spherical harmonics with copied values from this instance.
  34157. *
  34158. * @return {SphericalHarmonics3} A clone of this instance.
  34159. */
  34160. clone() {
  34161. return new this.constructor().copy( this );
  34162. }
  34163. /**
  34164. * Sets the SH coefficients of this instance from the given array.
  34165. *
  34166. * @param {Array<number>} array - An array holding the SH coefficients.
  34167. * @param {number} [offset=0] - The array offset where to start copying.
  34168. * @return {SphericalHarmonics3} A clone of this instance.
  34169. */
  34170. fromArray( array, offset = 0 ) {
  34171. const coefficients = this.coefficients;
  34172. for ( let i = 0; i < 9; i ++ ) {
  34173. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  34174. }
  34175. return this;
  34176. }
  34177. /**
  34178. * Returns an array with the SH coefficients, or copies them into the provided
  34179. * array. The coefficients are represented as numbers.
  34180. *
  34181. * @param {Array<number>} [array=[]] - The target array.
  34182. * @param {number} [offset=0] - The array offset where to start copying.
  34183. * @return {Array<number>} An array with flat SH coefficients.
  34184. */
  34185. toArray( array = [], offset = 0 ) {
  34186. const coefficients = this.coefficients;
  34187. for ( let i = 0; i < 9; i ++ ) {
  34188. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  34189. }
  34190. return array;
  34191. }
  34192. /**
  34193. * Computes the SH basis for the given normal vector.
  34194. *
  34195. * @param {Vector3} normal - The normal.
  34196. * @param {Array<number>} shBasis - The target array holding the SH basis.
  34197. */
  34198. static getBasisAt( normal, shBasis ) {
  34199. // normal is assumed to be unit length
  34200. const x = normal.x, y = normal.y, z = normal.z;
  34201. // band 0
  34202. shBasis[ 0 ] = 0.282095;
  34203. // band 1
  34204. shBasis[ 1 ] = 0.488603 * y;
  34205. shBasis[ 2 ] = 0.488603 * z;
  34206. shBasis[ 3 ] = 0.488603 * x;
  34207. // band 2
  34208. shBasis[ 4 ] = 1.092548 * x * y;
  34209. shBasis[ 5 ] = 1.092548 * y * z;
  34210. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  34211. shBasis[ 7 ] = 1.092548 * x * z;
  34212. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  34213. }
  34214. }
  34215. /**
  34216. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  34217. * classical light sources (e.g. directional, point or spot lights), light
  34218. * probes do not emit light. Instead they store information about light
  34219. * passing through 3D space. During rendering, the light that hits a 3D
  34220. * object is approximated by using the data from the light probe.
  34221. *
  34222. * Light probes are usually created from (radiance) environment maps. The
  34223. * class {@link LightProbeGenerator} can be used to create light probes from
  34224. * cube textures or render targets. However, light estimation data could also
  34225. * be provided in other forms e.g. by WebXR. This enables the rendering of
  34226. * augmented reality content that reacts to real world lighting.
  34227. *
  34228. * The current probe implementation in three.js supports so-called diffuse
  34229. * light probes. This type of light probe is functionally equivalent to an
  34230. * irradiance environment map.
  34231. *
  34232. * @augments Light
  34233. */
  34234. class LightProbe extends Light {
  34235. /**
  34236. * Constructs a new light probe.
  34237. *
  34238. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  34239. * @param {number} [intensity=1] - The light's strength/intensity.
  34240. */
  34241. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  34242. super( undefined, intensity );
  34243. /**
  34244. * This flag can be used for type testing.
  34245. *
  34246. * @type {boolean}
  34247. * @readonly
  34248. * @default true
  34249. */
  34250. this.isLightProbe = true;
  34251. /**
  34252. * A light probe uses spherical harmonics to encode lighting information.
  34253. *
  34254. * @type {SphericalHarmonics3}
  34255. */
  34256. this.sh = sh;
  34257. }
  34258. copy( source ) {
  34259. super.copy( source );
  34260. this.sh.copy( source.sh );
  34261. return this;
  34262. }
  34263. /**
  34264. * Deserializes the light prove from the given JSON.
  34265. *
  34266. * @param {Object} json - The JSON holding the serialized light probe.
  34267. * @return {LightProbe} A reference to this light probe.
  34268. */
  34269. fromJSON( json ) {
  34270. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  34271. this.sh.fromArray( json.sh );
  34272. return this;
  34273. }
  34274. toJSON( meta ) {
  34275. const data = super.toJSON( meta );
  34276. data.object.sh = this.sh.toArray();
  34277. return data;
  34278. }
  34279. }
  34280. /**
  34281. * Class for loading geometries. The files are internally
  34282. * loaded via {@link FileLoader}.
  34283. *
  34284. * ```js
  34285. * const loader = new THREE.MaterialLoader();
  34286. * const material = await loader.loadAsync( 'material.json' );
  34287. * ```
  34288. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  34289. *
  34290. * @augments Loader
  34291. */
  34292. class MaterialLoader extends Loader {
  34293. /**
  34294. * Constructs a new material loader.
  34295. *
  34296. * @param {LoadingManager} [manager] - The loading manager.
  34297. */
  34298. constructor( manager ) {
  34299. super( manager );
  34300. /**
  34301. * A dictionary holding textures used by the material.
  34302. *
  34303. * @type {Object<string,Texture>}
  34304. */
  34305. this.textures = {};
  34306. }
  34307. /**
  34308. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  34309. *
  34310. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34311. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  34312. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34313. * @param {onErrorCallback} onError - Executed when errors occur.
  34314. */
  34315. load( url, onLoad, onProgress, onError ) {
  34316. const scope = this;
  34317. const loader = new FileLoader( scope.manager );
  34318. loader.setPath( scope.path );
  34319. loader.setRequestHeader( scope.requestHeader );
  34320. loader.setWithCredentials( scope.withCredentials );
  34321. loader.load( url, function ( text ) {
  34322. try {
  34323. onLoad( scope.parse( JSON.parse( text ) ) );
  34324. } catch ( e ) {
  34325. if ( onError ) {
  34326. onError( e );
  34327. } else {
  34328. console.error( e );
  34329. }
  34330. scope.manager.itemError( url );
  34331. }
  34332. }, onProgress, onError );
  34333. }
  34334. /**
  34335. * Parses the given JSON object and returns a material.
  34336. *
  34337. * @param {Object} json - The serialized material.
  34338. * @return {Material} The parsed material.
  34339. */
  34340. parse( json ) {
  34341. const textures = this.textures;
  34342. function getTexture( name ) {
  34343. if ( textures[ name ] === undefined ) {
  34344. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  34345. }
  34346. return textures[ name ];
  34347. }
  34348. const material = this.createMaterialFromType( json.type );
  34349. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  34350. if ( json.name !== undefined ) material.name = json.name;
  34351. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  34352. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  34353. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  34354. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  34355. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  34356. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  34357. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  34358. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  34359. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  34360. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  34361. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  34362. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  34363. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  34364. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  34365. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  34366. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  34367. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  34368. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  34369. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  34370. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  34371. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  34372. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  34373. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  34374. if ( json.fog !== undefined ) material.fog = json.fog;
  34375. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  34376. if ( json.blending !== undefined ) material.blending = json.blending;
  34377. if ( json.combine !== undefined ) material.combine = json.combine;
  34378. if ( json.side !== undefined ) material.side = json.side;
  34379. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  34380. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  34381. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  34382. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  34383. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  34384. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  34385. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  34386. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  34387. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  34388. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  34389. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  34390. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  34391. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  34392. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  34393. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  34394. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  34395. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  34396. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  34397. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  34398. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  34399. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  34400. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  34401. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  34402. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  34403. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  34404. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  34405. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  34406. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  34407. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  34408. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  34409. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  34410. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  34411. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  34412. if ( json.scale !== undefined ) material.scale = json.scale;
  34413. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  34414. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  34415. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  34416. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  34417. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  34418. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  34419. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  34420. if ( json.visible !== undefined ) material.visible = json.visible;
  34421. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  34422. if ( json.userData !== undefined ) material.userData = json.userData;
  34423. if ( json.vertexColors !== undefined ) {
  34424. if ( typeof json.vertexColors === 'number' ) {
  34425. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  34426. } else {
  34427. material.vertexColors = json.vertexColors;
  34428. }
  34429. }
  34430. // Shader Material
  34431. if ( json.uniforms !== undefined ) {
  34432. for ( const name in json.uniforms ) {
  34433. const uniform = json.uniforms[ name ];
  34434. material.uniforms[ name ] = {};
  34435. switch ( uniform.type ) {
  34436. case 't':
  34437. material.uniforms[ name ].value = getTexture( uniform.value );
  34438. break;
  34439. case 'c':
  34440. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  34441. break;
  34442. case 'v2':
  34443. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  34444. break;
  34445. case 'v3':
  34446. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  34447. break;
  34448. case 'v4':
  34449. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  34450. break;
  34451. case 'm3':
  34452. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  34453. break;
  34454. case 'm4':
  34455. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  34456. break;
  34457. default:
  34458. material.uniforms[ name ].value = uniform.value;
  34459. }
  34460. }
  34461. }
  34462. if ( json.defines !== undefined ) material.defines = json.defines;
  34463. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  34464. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  34465. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  34466. if ( json.extensions !== undefined ) {
  34467. for ( const key in json.extensions ) {
  34468. material.extensions[ key ] = json.extensions[ key ];
  34469. }
  34470. }
  34471. if ( json.lights !== undefined ) material.lights = json.lights;
  34472. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  34473. // for PointsMaterial
  34474. if ( json.size !== undefined ) material.size = json.size;
  34475. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  34476. // maps
  34477. if ( json.map !== undefined ) material.map = getTexture( json.map );
  34478. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  34479. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  34480. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  34481. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  34482. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  34483. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  34484. if ( json.normalScale !== undefined ) {
  34485. let normalScale = json.normalScale;
  34486. if ( Array.isArray( normalScale ) === false ) {
  34487. // Blender exporter used to export a scalar. See #7459
  34488. normalScale = [ normalScale, normalScale ];
  34489. }
  34490. material.normalScale = new Vector2().fromArray( normalScale );
  34491. }
  34492. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  34493. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  34494. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  34495. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  34496. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  34497. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  34498. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  34499. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  34500. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  34501. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  34502. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  34503. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  34504. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  34505. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  34506. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  34507. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  34508. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  34509. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  34510. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  34511. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  34512. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  34513. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  34514. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  34515. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  34516. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  34517. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  34518. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  34519. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  34520. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  34521. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  34522. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  34523. return material;
  34524. }
  34525. /**
  34526. * Textures are not embedded in the material JSON so they have
  34527. * to be injected before the loading process starts.
  34528. *
  34529. * @param {Object} value - A dictionary holding textures for material properties.
  34530. * @return {MaterialLoader} A reference to this material loader.
  34531. */
  34532. setTextures( value ) {
  34533. this.textures = value;
  34534. return this;
  34535. }
  34536. /**
  34537. * Creates a material for the given type.
  34538. *
  34539. * @param {string} type - The material type.
  34540. * @return {Material} The new material.
  34541. */
  34542. createMaterialFromType( type ) {
  34543. return MaterialLoader.createMaterialFromType( type );
  34544. }
  34545. /**
  34546. * Creates a material for the given type.
  34547. *
  34548. * @static
  34549. * @param {string} type - The material type.
  34550. * @return {Material} The new material.
  34551. */
  34552. static createMaterialFromType( type ) {
  34553. const materialLib = {
  34554. ShadowMaterial,
  34555. SpriteMaterial,
  34556. RawShaderMaterial,
  34557. ShaderMaterial,
  34558. PointsMaterial,
  34559. MeshPhysicalMaterial,
  34560. MeshStandardMaterial,
  34561. MeshPhongMaterial,
  34562. MeshToonMaterial,
  34563. MeshNormalMaterial,
  34564. MeshLambertMaterial,
  34565. MeshDepthMaterial,
  34566. MeshDistanceMaterial,
  34567. MeshBasicMaterial,
  34568. MeshMatcapMaterial,
  34569. LineDashedMaterial,
  34570. LineBasicMaterial,
  34571. Material
  34572. };
  34573. return new materialLib[ type ]();
  34574. }
  34575. }
  34576. /**
  34577. * A class with loader utility functions.
  34578. */
  34579. class LoaderUtils {
  34580. /**
  34581. * Extracts the base URL from the given URL.
  34582. *
  34583. * @param {string} url -The URL to extract the base URL from.
  34584. * @return {string} The extracted base URL.
  34585. */
  34586. static extractUrlBase( url ) {
  34587. const index = url.lastIndexOf( '/' );
  34588. if ( index === -1 ) return './';
  34589. return url.slice( 0, index + 1 );
  34590. }
  34591. /**
  34592. * Resolves relative URLs against the given path. Absolute paths, data urls,
  34593. * and blob URLs will be returned as is. Invalid URLs will return an empty
  34594. * string.
  34595. *
  34596. * @param {string} url -The URL to resolve.
  34597. * @param {string} path - The base path for relative URLs to be resolved against.
  34598. * @return {string} The resolved URL.
  34599. */
  34600. static resolveURL( url, path ) {
  34601. // Invalid URL
  34602. if ( typeof url !== 'string' || url === '' ) return '';
  34603. // Host Relative URL
  34604. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  34605. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  34606. }
  34607. // Absolute URL http://,https://,//
  34608. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  34609. // Data URI
  34610. if ( /^data:.*,.*$/i.test( url ) ) return url;
  34611. // Blob URL
  34612. if ( /^blob:.*$/i.test( url ) ) return url;
  34613. // Relative URL
  34614. return path + url;
  34615. }
  34616. }
  34617. /**
  34618. * An instanced version of a geometry.
  34619. */
  34620. class InstancedBufferGeometry extends BufferGeometry {
  34621. /**
  34622. * Constructs a new instanced buffer geometry.
  34623. */
  34624. constructor() {
  34625. super();
  34626. /**
  34627. * This flag can be used for type testing.
  34628. *
  34629. * @type {boolean}
  34630. * @readonly
  34631. * @default true
  34632. */
  34633. this.isInstancedBufferGeometry = true;
  34634. this.type = 'InstancedBufferGeometry';
  34635. /**
  34636. * The instance count.
  34637. *
  34638. * @type {number}
  34639. * @default Infinity
  34640. */
  34641. this.instanceCount = Infinity;
  34642. }
  34643. copy( source ) {
  34644. super.copy( source );
  34645. this.instanceCount = source.instanceCount;
  34646. return this;
  34647. }
  34648. toJSON() {
  34649. const data = super.toJSON();
  34650. data.instanceCount = this.instanceCount;
  34651. data.isInstancedBufferGeometry = true;
  34652. return data;
  34653. }
  34654. }
  34655. /**
  34656. * Class for loading geometries. The files are internally
  34657. * loaded via {@link FileLoader}.
  34658. *
  34659. * ```js
  34660. * const loader = new THREE.BufferGeometryLoader();
  34661. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  34662. *
  34663. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  34664. * const object = new THREE.Mesh( geometry, material );
  34665. * scene.add( object );
  34666. * ```
  34667. *
  34668. * @augments Loader
  34669. */
  34670. class BufferGeometryLoader extends Loader {
  34671. /**
  34672. * Constructs a new geometry loader.
  34673. *
  34674. * @param {LoadingManager} [manager] - The loading manager.
  34675. */
  34676. constructor( manager ) {
  34677. super( manager );
  34678. }
  34679. /**
  34680. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  34681. *
  34682. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34683. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  34684. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34685. * @param {onErrorCallback} onError - Executed when errors occur.
  34686. */
  34687. load( url, onLoad, onProgress, onError ) {
  34688. const scope = this;
  34689. const loader = new FileLoader( scope.manager );
  34690. loader.setPath( scope.path );
  34691. loader.setRequestHeader( scope.requestHeader );
  34692. loader.setWithCredentials( scope.withCredentials );
  34693. loader.load( url, function ( text ) {
  34694. try {
  34695. onLoad( scope.parse( JSON.parse( text ) ) );
  34696. } catch ( e ) {
  34697. if ( onError ) {
  34698. onError( e );
  34699. } else {
  34700. console.error( e );
  34701. }
  34702. scope.manager.itemError( url );
  34703. }
  34704. }, onProgress, onError );
  34705. }
  34706. /**
  34707. * Parses the given JSON object and returns a geometry.
  34708. *
  34709. * @param {Object} json - The serialized geometry.
  34710. * @return {BufferGeometry} The parsed geometry.
  34711. */
  34712. parse( json ) {
  34713. const interleavedBufferMap = {};
  34714. const arrayBufferMap = {};
  34715. function getInterleavedBuffer( json, uuid ) {
  34716. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  34717. const interleavedBuffers = json.interleavedBuffers;
  34718. const interleavedBuffer = interleavedBuffers[ uuid ];
  34719. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  34720. const array = getTypedArray( interleavedBuffer.type, buffer );
  34721. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  34722. ib.uuid = interleavedBuffer.uuid;
  34723. interleavedBufferMap[ uuid ] = ib;
  34724. return ib;
  34725. }
  34726. function getArrayBuffer( json, uuid ) {
  34727. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  34728. const arrayBuffers = json.arrayBuffers;
  34729. const arrayBuffer = arrayBuffers[ uuid ];
  34730. const ab = new Uint32Array( arrayBuffer ).buffer;
  34731. arrayBufferMap[ uuid ] = ab;
  34732. return ab;
  34733. }
  34734. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  34735. const index = json.data.index;
  34736. if ( index !== undefined ) {
  34737. const typedArray = getTypedArray( index.type, index.array );
  34738. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  34739. }
  34740. const attributes = json.data.attributes;
  34741. for ( const key in attributes ) {
  34742. const attribute = attributes[ key ];
  34743. let bufferAttribute;
  34744. if ( attribute.isInterleavedBufferAttribute ) {
  34745. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34746. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34747. } else {
  34748. const typedArray = getTypedArray( attribute.type, attribute.array );
  34749. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  34750. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  34751. }
  34752. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  34753. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  34754. geometry.setAttribute( key, bufferAttribute );
  34755. }
  34756. const morphAttributes = json.data.morphAttributes;
  34757. if ( morphAttributes ) {
  34758. for ( const key in morphAttributes ) {
  34759. const attributeArray = morphAttributes[ key ];
  34760. const array = [];
  34761. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  34762. const attribute = attributeArray[ i ];
  34763. let bufferAttribute;
  34764. if ( attribute.isInterleavedBufferAttribute ) {
  34765. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34766. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34767. } else {
  34768. const typedArray = getTypedArray( attribute.type, attribute.array );
  34769. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  34770. }
  34771. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  34772. array.push( bufferAttribute );
  34773. }
  34774. geometry.morphAttributes[ key ] = array;
  34775. }
  34776. }
  34777. const morphTargetsRelative = json.data.morphTargetsRelative;
  34778. if ( morphTargetsRelative ) {
  34779. geometry.morphTargetsRelative = true;
  34780. }
  34781. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  34782. if ( groups !== undefined ) {
  34783. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  34784. const group = groups[ i ];
  34785. geometry.addGroup( group.start, group.count, group.materialIndex );
  34786. }
  34787. }
  34788. const boundingSphere = json.data.boundingSphere;
  34789. if ( boundingSphere !== undefined ) {
  34790. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  34791. }
  34792. if ( json.name ) geometry.name = json.name;
  34793. if ( json.userData ) geometry.userData = json.userData;
  34794. return geometry;
  34795. }
  34796. }
  34797. /**
  34798. * 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}.
  34799. * The files are internally loaded via {@link FileLoader}.
  34800. *
  34801. * ```js
  34802. * const loader = new THREE.ObjectLoader();
  34803. * const obj = await loader.loadAsync( 'models/json/example.json' );
  34804. * scene.add( obj );
  34805. *
  34806. * // Alternatively, to parse a previously loaded JSON structure
  34807. * const object = await loader.parseAsync( a_json_object );
  34808. * scene.add( object );
  34809. * ```
  34810. *
  34811. * @augments Loader
  34812. */
  34813. class ObjectLoader extends Loader {
  34814. /**
  34815. * Constructs a new object loader.
  34816. *
  34817. * @param {LoadingManager} [manager] - The loading manager.
  34818. */
  34819. constructor( manager ) {
  34820. super( manager );
  34821. }
  34822. /**
  34823. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  34824. *
  34825. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34826. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  34827. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34828. * @param {onErrorCallback} onError - Executed when errors occur.
  34829. */
  34830. load( url, onLoad, onProgress, onError ) {
  34831. const scope = this;
  34832. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  34833. this.resourcePath = this.resourcePath || path;
  34834. const loader = new FileLoader( this.manager );
  34835. loader.setPath( this.path );
  34836. loader.setRequestHeader( this.requestHeader );
  34837. loader.setWithCredentials( this.withCredentials );
  34838. loader.load( url, function ( text ) {
  34839. let json = null;
  34840. try {
  34841. json = JSON.parse( text );
  34842. } catch ( error ) {
  34843. if ( onError !== undefined ) onError( error );
  34844. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  34845. return;
  34846. }
  34847. const metadata = json.metadata;
  34848. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  34849. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  34850. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  34851. return;
  34852. }
  34853. scope.parse( json, onLoad );
  34854. }, onProgress, onError );
  34855. }
  34856. /**
  34857. * Async version of {@link ObjectLoader#load}.
  34858. *
  34859. * @async
  34860. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34861. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34862. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  34863. */
  34864. async loadAsync( url, onProgress ) {
  34865. const scope = this;
  34866. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  34867. this.resourcePath = this.resourcePath || path;
  34868. const loader = new FileLoader( this.manager );
  34869. loader.setPath( this.path );
  34870. loader.setRequestHeader( this.requestHeader );
  34871. loader.setWithCredentials( this.withCredentials );
  34872. const text = await loader.loadAsync( url, onProgress );
  34873. const json = JSON.parse( text );
  34874. const metadata = json.metadata;
  34875. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  34876. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  34877. }
  34878. return await scope.parseAsync( json );
  34879. }
  34880. /**
  34881. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  34882. * but can also be used directly to parse a previously loaded JSON structure.
  34883. *
  34884. * @param {Object} json - The serialized 3D object.
  34885. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  34886. * @return {Object3D} The parsed 3D object.
  34887. */
  34888. parse( json, onLoad ) {
  34889. const animations = this.parseAnimations( json.animations );
  34890. const shapes = this.parseShapes( json.shapes );
  34891. const geometries = this.parseGeometries( json.geometries, shapes );
  34892. const images = this.parseImages( json.images, function () {
  34893. if ( onLoad !== undefined ) onLoad( object );
  34894. } );
  34895. const textures = this.parseTextures( json.textures, images );
  34896. const materials = this.parseMaterials( json.materials, textures );
  34897. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  34898. const skeletons = this.parseSkeletons( json.skeletons, object );
  34899. this.bindSkeletons( object, skeletons );
  34900. this.bindLightTargets( object );
  34901. //
  34902. if ( onLoad !== undefined ) {
  34903. let hasImages = false;
  34904. for ( const uuid in images ) {
  34905. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  34906. hasImages = true;
  34907. break;
  34908. }
  34909. }
  34910. if ( hasImages === false ) onLoad( object );
  34911. }
  34912. return object;
  34913. }
  34914. /**
  34915. * Async version of {@link ObjectLoader#parse}.
  34916. *
  34917. * @param {Object} json - The serialized 3D object.
  34918. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  34919. */
  34920. async parseAsync( json ) {
  34921. const animations = this.parseAnimations( json.animations );
  34922. const shapes = this.parseShapes( json.shapes );
  34923. const geometries = this.parseGeometries( json.geometries, shapes );
  34924. const images = await this.parseImagesAsync( json.images );
  34925. const textures = this.parseTextures( json.textures, images );
  34926. const materials = this.parseMaterials( json.materials, textures );
  34927. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  34928. const skeletons = this.parseSkeletons( json.skeletons, object );
  34929. this.bindSkeletons( object, skeletons );
  34930. this.bindLightTargets( object );
  34931. return object;
  34932. }
  34933. // internals
  34934. parseShapes( json ) {
  34935. const shapes = {};
  34936. if ( json !== undefined ) {
  34937. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34938. const shape = new Shape().fromJSON( json[ i ] );
  34939. shapes[ shape.uuid ] = shape;
  34940. }
  34941. }
  34942. return shapes;
  34943. }
  34944. parseSkeletons( json, object ) {
  34945. const skeletons = {};
  34946. const bones = {};
  34947. // generate bone lookup table
  34948. object.traverse( function ( child ) {
  34949. if ( child.isBone ) bones[ child.uuid ] = child;
  34950. } );
  34951. // create skeletons
  34952. if ( json !== undefined ) {
  34953. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34954. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  34955. skeletons[ skeleton.uuid ] = skeleton;
  34956. }
  34957. }
  34958. return skeletons;
  34959. }
  34960. parseGeometries( json, shapes ) {
  34961. const geometries = {};
  34962. if ( json !== undefined ) {
  34963. const bufferGeometryLoader = new BufferGeometryLoader();
  34964. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34965. let geometry;
  34966. const data = json[ i ];
  34967. switch ( data.type ) {
  34968. case 'BufferGeometry':
  34969. case 'InstancedBufferGeometry':
  34970. geometry = bufferGeometryLoader.parse( data );
  34971. break;
  34972. default:
  34973. if ( data.type in Geometries ) {
  34974. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  34975. } else {
  34976. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  34977. }
  34978. }
  34979. geometry.uuid = data.uuid;
  34980. if ( data.name !== undefined ) geometry.name = data.name;
  34981. if ( data.userData !== undefined ) geometry.userData = data.userData;
  34982. geometries[ data.uuid ] = geometry;
  34983. }
  34984. }
  34985. return geometries;
  34986. }
  34987. parseMaterials( json, textures ) {
  34988. const cache = {}; // MultiMaterial
  34989. const materials = {};
  34990. if ( json !== undefined ) {
  34991. const loader = new MaterialLoader();
  34992. loader.setTextures( textures );
  34993. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34994. const data = json[ i ];
  34995. if ( cache[ data.uuid ] === undefined ) {
  34996. cache[ data.uuid ] = loader.parse( data );
  34997. }
  34998. materials[ data.uuid ] = cache[ data.uuid ];
  34999. }
  35000. }
  35001. return materials;
  35002. }
  35003. parseAnimations( json ) {
  35004. const animations = {};
  35005. if ( json !== undefined ) {
  35006. for ( let i = 0; i < json.length; i ++ ) {
  35007. const data = json[ i ];
  35008. const clip = AnimationClip.parse( data );
  35009. animations[ clip.uuid ] = clip;
  35010. }
  35011. }
  35012. return animations;
  35013. }
  35014. parseImages( json, onLoad ) {
  35015. const scope = this;
  35016. const images = {};
  35017. let loader;
  35018. function loadImage( url ) {
  35019. scope.manager.itemStart( url );
  35020. return loader.load( url, function () {
  35021. scope.manager.itemEnd( url );
  35022. }, undefined, function () {
  35023. scope.manager.itemError( url );
  35024. scope.manager.itemEnd( url );
  35025. } );
  35026. }
  35027. function deserializeImage( image ) {
  35028. if ( typeof image === 'string' ) {
  35029. const url = image;
  35030. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35031. return loadImage( path );
  35032. } else {
  35033. if ( image.data ) {
  35034. return {
  35035. data: getTypedArray( image.type, image.data ),
  35036. width: image.width,
  35037. height: image.height
  35038. };
  35039. } else {
  35040. return null;
  35041. }
  35042. }
  35043. }
  35044. if ( json !== undefined && json.length > 0 ) {
  35045. const manager = new LoadingManager( onLoad );
  35046. loader = new ImageLoader( manager );
  35047. loader.setCrossOrigin( this.crossOrigin );
  35048. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35049. const image = json[ i ];
  35050. const url = image.url;
  35051. if ( Array.isArray( url ) ) {
  35052. // load array of images e.g CubeTexture
  35053. const imageArray = [];
  35054. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35055. const currentUrl = url[ j ];
  35056. const deserializedImage = deserializeImage( currentUrl );
  35057. if ( deserializedImage !== null ) {
  35058. if ( deserializedImage instanceof HTMLImageElement ) {
  35059. imageArray.push( deserializedImage );
  35060. } else {
  35061. // special case: handle array of data textures for cube textures
  35062. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35063. }
  35064. }
  35065. }
  35066. images[ image.uuid ] = new Source( imageArray );
  35067. } else {
  35068. // load single image
  35069. const deserializedImage = deserializeImage( image.url );
  35070. images[ image.uuid ] = new Source( deserializedImage );
  35071. }
  35072. }
  35073. }
  35074. return images;
  35075. }
  35076. async parseImagesAsync( json ) {
  35077. const scope = this;
  35078. const images = {};
  35079. let loader;
  35080. async function deserializeImage( image ) {
  35081. if ( typeof image === 'string' ) {
  35082. const url = image;
  35083. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35084. return await loader.loadAsync( path );
  35085. } else {
  35086. if ( image.data ) {
  35087. return {
  35088. data: getTypedArray( image.type, image.data ),
  35089. width: image.width,
  35090. height: image.height
  35091. };
  35092. } else {
  35093. return null;
  35094. }
  35095. }
  35096. }
  35097. if ( json !== undefined && json.length > 0 ) {
  35098. loader = new ImageLoader( this.manager );
  35099. loader.setCrossOrigin( this.crossOrigin );
  35100. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35101. const image = json[ i ];
  35102. const url = image.url;
  35103. if ( Array.isArray( url ) ) {
  35104. // load array of images e.g CubeTexture
  35105. const imageArray = [];
  35106. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35107. const currentUrl = url[ j ];
  35108. const deserializedImage = await deserializeImage( currentUrl );
  35109. if ( deserializedImage !== null ) {
  35110. if ( deserializedImage instanceof HTMLImageElement ) {
  35111. imageArray.push( deserializedImage );
  35112. } else {
  35113. // special case: handle array of data textures for cube textures
  35114. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35115. }
  35116. }
  35117. }
  35118. images[ image.uuid ] = new Source( imageArray );
  35119. } else {
  35120. // load single image
  35121. const deserializedImage = await deserializeImage( image.url );
  35122. images[ image.uuid ] = new Source( deserializedImage );
  35123. }
  35124. }
  35125. }
  35126. return images;
  35127. }
  35128. parseTextures( json, images ) {
  35129. function parseConstant( value, type ) {
  35130. if ( typeof value === 'number' ) return value;
  35131. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  35132. return type[ value ];
  35133. }
  35134. const textures = {};
  35135. if ( json !== undefined ) {
  35136. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35137. const data = json[ i ];
  35138. if ( data.image === undefined ) {
  35139. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  35140. }
  35141. if ( images[ data.image ] === undefined ) {
  35142. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  35143. }
  35144. const source = images[ data.image ];
  35145. const image = source.data;
  35146. let texture;
  35147. if ( Array.isArray( image ) ) {
  35148. texture = new CubeTexture();
  35149. if ( image.length === 6 ) texture.needsUpdate = true;
  35150. } else {
  35151. if ( image && image.data ) {
  35152. texture = new DataTexture();
  35153. } else {
  35154. texture = new Texture();
  35155. }
  35156. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  35157. }
  35158. texture.source = source;
  35159. texture.uuid = data.uuid;
  35160. if ( data.name !== undefined ) texture.name = data.name;
  35161. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  35162. if ( data.channel !== undefined ) texture.channel = data.channel;
  35163. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  35164. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  35165. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  35166. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  35167. if ( data.wrap !== undefined ) {
  35168. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  35169. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  35170. }
  35171. if ( data.format !== undefined ) texture.format = data.format;
  35172. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  35173. if ( data.type !== undefined ) texture.type = data.type;
  35174. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  35175. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  35176. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  35177. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  35178. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  35179. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  35180. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  35181. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  35182. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  35183. if ( data.userData !== undefined ) texture.userData = data.userData;
  35184. textures[ data.uuid ] = texture;
  35185. }
  35186. }
  35187. return textures;
  35188. }
  35189. parseObject( data, geometries, materials, textures, animations ) {
  35190. let object;
  35191. function getGeometry( name ) {
  35192. if ( geometries[ name ] === undefined ) {
  35193. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  35194. }
  35195. return geometries[ name ];
  35196. }
  35197. function getMaterial( name ) {
  35198. if ( name === undefined ) return undefined;
  35199. if ( Array.isArray( name ) ) {
  35200. const array = [];
  35201. for ( let i = 0, l = name.length; i < l; i ++ ) {
  35202. const uuid = name[ i ];
  35203. if ( materials[ uuid ] === undefined ) {
  35204. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  35205. }
  35206. array.push( materials[ uuid ] );
  35207. }
  35208. return array;
  35209. }
  35210. if ( materials[ name ] === undefined ) {
  35211. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  35212. }
  35213. return materials[ name ];
  35214. }
  35215. function getTexture( uuid ) {
  35216. if ( textures[ uuid ] === undefined ) {
  35217. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  35218. }
  35219. return textures[ uuid ];
  35220. }
  35221. let geometry, material;
  35222. switch ( data.type ) {
  35223. case 'Scene':
  35224. object = new Scene();
  35225. if ( data.background !== undefined ) {
  35226. if ( Number.isInteger( data.background ) ) {
  35227. object.background = new Color( data.background );
  35228. } else {
  35229. object.background = getTexture( data.background );
  35230. }
  35231. }
  35232. if ( data.environment !== undefined ) {
  35233. object.environment = getTexture( data.environment );
  35234. }
  35235. if ( data.fog !== undefined ) {
  35236. if ( data.fog.type === 'Fog' ) {
  35237. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  35238. } else if ( data.fog.type === 'FogExp2' ) {
  35239. object.fog = new FogExp2( data.fog.color, data.fog.density );
  35240. }
  35241. if ( data.fog.name !== '' ) {
  35242. object.fog.name = data.fog.name;
  35243. }
  35244. }
  35245. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  35246. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  35247. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  35248. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  35249. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  35250. break;
  35251. case 'PerspectiveCamera':
  35252. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  35253. if ( data.focus !== undefined ) object.focus = data.focus;
  35254. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35255. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  35256. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  35257. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35258. break;
  35259. case 'OrthographicCamera':
  35260. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  35261. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35262. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35263. break;
  35264. case 'AmbientLight':
  35265. object = new AmbientLight( data.color, data.intensity );
  35266. break;
  35267. case 'DirectionalLight':
  35268. object = new DirectionalLight( data.color, data.intensity );
  35269. object.target = data.target || '';
  35270. break;
  35271. case 'PointLight':
  35272. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  35273. break;
  35274. case 'RectAreaLight':
  35275. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  35276. break;
  35277. case 'SpotLight':
  35278. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  35279. object.target = data.target || '';
  35280. break;
  35281. case 'HemisphereLight':
  35282. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  35283. break;
  35284. case 'LightProbe':
  35285. object = new LightProbe().fromJSON( data );
  35286. break;
  35287. case 'SkinnedMesh':
  35288. geometry = getGeometry( data.geometry );
  35289. material = getMaterial( data.material );
  35290. object = new SkinnedMesh( geometry, material );
  35291. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  35292. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  35293. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  35294. break;
  35295. case 'Mesh':
  35296. geometry = getGeometry( data.geometry );
  35297. material = getMaterial( data.material );
  35298. object = new Mesh( geometry, material );
  35299. break;
  35300. case 'InstancedMesh':
  35301. geometry = getGeometry( data.geometry );
  35302. material = getMaterial( data.material );
  35303. const count = data.count;
  35304. const instanceMatrix = data.instanceMatrix;
  35305. const instanceColor = data.instanceColor;
  35306. object = new InstancedMesh( geometry, material, count );
  35307. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  35308. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  35309. break;
  35310. case 'BatchedMesh':
  35311. geometry = getGeometry( data.geometry );
  35312. material = getMaterial( data.material );
  35313. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  35314. object.geometry = geometry;
  35315. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  35316. object.sortObjects = data.sortObjects;
  35317. object._drawRanges = data.drawRanges;
  35318. object._reservedRanges = data.reservedRanges;
  35319. object._geometryInfo = data.geometryInfo.map( info => {
  35320. let box = null;
  35321. let sphere = null;
  35322. if ( info.boundingBox !== undefined ) {
  35323. box = new Box3().fromJSON( info.boundingBox );
  35324. }
  35325. if ( info.boundingSphere !== undefined ) {
  35326. sphere = new Sphere().fromJSON( info.boundingSphere );
  35327. }
  35328. return {
  35329. ...info,
  35330. boundingBox: box,
  35331. boundingSphere: sphere
  35332. };
  35333. } );
  35334. object._instanceInfo = data.instanceInfo;
  35335. object._availableInstanceIds = data._availableInstanceIds;
  35336. object._availableGeometryIds = data._availableGeometryIds;
  35337. object._nextIndexStart = data.nextIndexStart;
  35338. object._nextVertexStart = data.nextVertexStart;
  35339. object._geometryCount = data.geometryCount;
  35340. object._maxInstanceCount = data.maxInstanceCount;
  35341. object._maxVertexCount = data.maxVertexCount;
  35342. object._maxIndexCount = data.maxIndexCount;
  35343. object._geometryInitialized = data.geometryInitialized;
  35344. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  35345. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  35346. if ( data.colorsTexture !== undefined ) {
  35347. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  35348. }
  35349. if ( data.boundingSphere !== undefined ) {
  35350. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  35351. }
  35352. if ( data.boundingBox !== undefined ) {
  35353. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  35354. }
  35355. break;
  35356. case 'LOD':
  35357. object = new LOD();
  35358. break;
  35359. case 'Line':
  35360. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  35361. break;
  35362. case 'LineLoop':
  35363. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  35364. break;
  35365. case 'LineSegments':
  35366. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  35367. break;
  35368. case 'PointCloud':
  35369. case 'Points':
  35370. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  35371. break;
  35372. case 'Sprite':
  35373. object = new Sprite( getMaterial( data.material ) );
  35374. break;
  35375. case 'Group':
  35376. object = new Group();
  35377. break;
  35378. case 'Bone':
  35379. object = new Bone();
  35380. break;
  35381. default:
  35382. object = new Object3D();
  35383. }
  35384. object.uuid = data.uuid;
  35385. if ( data.name !== undefined ) object.name = data.name;
  35386. if ( data.matrix !== undefined ) {
  35387. object.matrix.fromArray( data.matrix );
  35388. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  35389. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  35390. } else {
  35391. if ( data.position !== undefined ) object.position.fromArray( data.position );
  35392. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  35393. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  35394. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  35395. }
  35396. if ( data.up !== undefined ) object.up.fromArray( data.up );
  35397. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  35398. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  35399. if ( data.shadow ) {
  35400. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  35401. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  35402. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  35403. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  35404. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  35405. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  35406. }
  35407. if ( data.visible !== undefined ) object.visible = data.visible;
  35408. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  35409. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  35410. if ( data.userData !== undefined ) object.userData = data.userData;
  35411. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  35412. if ( data.children !== undefined ) {
  35413. const children = data.children;
  35414. for ( let i = 0; i < children.length; i ++ ) {
  35415. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  35416. }
  35417. }
  35418. if ( data.animations !== undefined ) {
  35419. const objectAnimations = data.animations;
  35420. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  35421. const uuid = objectAnimations[ i ];
  35422. object.animations.push( animations[ uuid ] );
  35423. }
  35424. }
  35425. if ( data.type === 'LOD' ) {
  35426. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  35427. const levels = data.levels;
  35428. for ( let l = 0; l < levels.length; l ++ ) {
  35429. const level = levels[ l ];
  35430. const child = object.getObjectByProperty( 'uuid', level.object );
  35431. if ( child !== undefined ) {
  35432. object.addLevel( child, level.distance, level.hysteresis );
  35433. }
  35434. }
  35435. }
  35436. return object;
  35437. }
  35438. bindSkeletons( object, skeletons ) {
  35439. if ( Object.keys( skeletons ).length === 0 ) return;
  35440. object.traverse( function ( child ) {
  35441. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  35442. const skeleton = skeletons[ child.skeleton ];
  35443. if ( skeleton === undefined ) {
  35444. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  35445. } else {
  35446. child.bind( skeleton, child.bindMatrix );
  35447. }
  35448. }
  35449. } );
  35450. }
  35451. bindLightTargets( object ) {
  35452. object.traverse( function ( child ) {
  35453. if ( child.isDirectionalLight || child.isSpotLight ) {
  35454. const uuid = child.target;
  35455. const target = object.getObjectByProperty( 'uuid', uuid );
  35456. if ( target !== undefined ) {
  35457. child.target = target;
  35458. } else {
  35459. child.target = new Object3D();
  35460. }
  35461. }
  35462. } );
  35463. }
  35464. }
  35465. const TEXTURE_MAPPING = {
  35466. UVMapping: UVMapping,
  35467. CubeReflectionMapping: CubeReflectionMapping,
  35468. CubeRefractionMapping: CubeRefractionMapping,
  35469. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  35470. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  35471. CubeUVReflectionMapping: CubeUVReflectionMapping
  35472. };
  35473. const TEXTURE_WRAPPING = {
  35474. RepeatWrapping: RepeatWrapping,
  35475. ClampToEdgeWrapping: ClampToEdgeWrapping,
  35476. MirroredRepeatWrapping: MirroredRepeatWrapping
  35477. };
  35478. const TEXTURE_FILTER = {
  35479. NearestFilter: NearestFilter,
  35480. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  35481. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  35482. LinearFilter: LinearFilter,
  35483. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  35484. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  35485. };
  35486. const _errorMap = new WeakMap();
  35487. /**
  35488. * A loader for loading images as an [ImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap}.
  35489. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  35490. * textures for rendering.
  35491. *
  35492. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  35493. * They needs these configuration on bitmap creation unlike regular images need them on uploading to GPU.
  35494. *
  35495. * You need to set the equivalent options via {@link ImageBitmapLoader#setOptions} instead.
  35496. *
  35497. * Also note that unlike {@link FileLoader}, this loader avoids multiple concurrent requests to the same URL only if `Cache` is enabled.
  35498. *
  35499. * ```js
  35500. * const loader = new THREE.ImageBitmapLoader();
  35501. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  35502. * const imageBitmap = await loader.loadAsync( 'image.png' );
  35503. *
  35504. * const texture = new THREE.Texture( imageBitmap );
  35505. * texture.needsUpdate = true;
  35506. * ```
  35507. *
  35508. * @augments Loader
  35509. */
  35510. class ImageBitmapLoader extends Loader {
  35511. /**
  35512. * Constructs a new image bitmap loader.
  35513. *
  35514. * @param {LoadingManager} [manager] - The loading manager.
  35515. */
  35516. constructor( manager ) {
  35517. super( manager );
  35518. /**
  35519. * This flag can be used for type testing.
  35520. *
  35521. * @type {boolean}
  35522. * @readonly
  35523. * @default true
  35524. */
  35525. this.isImageBitmapLoader = true;
  35526. if ( typeof createImageBitmap === 'undefined' ) {
  35527. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  35528. }
  35529. if ( typeof fetch === 'undefined' ) {
  35530. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  35531. }
  35532. /**
  35533. * Represents the loader options.
  35534. *
  35535. * @type {Object}
  35536. * @default {premultiplyAlpha:'none'}
  35537. */
  35538. this.options = { premultiplyAlpha: 'none' };
  35539. /**
  35540. * Used for aborting requests.
  35541. *
  35542. * @private
  35543. * @type {AbortController}
  35544. */
  35545. this._abortController = new AbortController();
  35546. }
  35547. /**
  35548. * Sets the given loader options. The structure of the object must match the `options` parameter of
  35549. * [createImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap}.
  35550. *
  35551. * @param {Object} options - The loader options to set.
  35552. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  35553. */
  35554. setOptions( options ) {
  35555. this.options = options;
  35556. return this;
  35557. }
  35558. /**
  35559. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  35560. *
  35561. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35562. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  35563. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  35564. * @param {onErrorCallback} onError - Executed when errors occur.
  35565. * @return {ImageBitmap|undefined} The image bitmap.
  35566. */
  35567. load( url, onLoad, onProgress, onError ) {
  35568. if ( url === undefined ) url = '';
  35569. if ( this.path !== undefined ) url = this.path + url;
  35570. url = this.manager.resolveURL( url );
  35571. const scope = this;
  35572. const cached = Cache.get( `image-bitmap:${url}` );
  35573. if ( cached !== undefined ) {
  35574. scope.manager.itemStart( url );
  35575. // If cached is a promise, wait for it to resolve
  35576. if ( cached.then ) {
  35577. cached.then( imageBitmap => {
  35578. // check if there is an error for the cached promise
  35579. if ( _errorMap.has( cached ) === true ) {
  35580. if ( onError ) onError( _errorMap.get( cached ) );
  35581. scope.manager.itemError( url );
  35582. scope.manager.itemEnd( url );
  35583. } else {
  35584. if ( onLoad ) onLoad( imageBitmap );
  35585. scope.manager.itemEnd( url );
  35586. return imageBitmap;
  35587. }
  35588. } );
  35589. return;
  35590. }
  35591. // If cached is not a promise (i.e., it's already an imageBitmap)
  35592. setTimeout( function () {
  35593. if ( onLoad ) onLoad( cached );
  35594. scope.manager.itemEnd( url );
  35595. }, 0 );
  35596. return cached;
  35597. }
  35598. const fetchOptions = {};
  35599. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  35600. fetchOptions.headers = this.requestHeader;
  35601. fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal;
  35602. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  35603. return res.blob();
  35604. } ).then( function ( blob ) {
  35605. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  35606. } ).then( function ( imageBitmap ) {
  35607. Cache.add( `image-bitmap:${url}`, imageBitmap );
  35608. if ( onLoad ) onLoad( imageBitmap );
  35609. scope.manager.itemEnd( url );
  35610. return imageBitmap;
  35611. } ).catch( function ( e ) {
  35612. if ( onError ) onError( e );
  35613. _errorMap.set( promise, e );
  35614. Cache.remove( `image-bitmap:${url}` );
  35615. scope.manager.itemError( url );
  35616. scope.manager.itemEnd( url );
  35617. } );
  35618. Cache.add( `image-bitmap:${url}`, promise );
  35619. scope.manager.itemStart( url );
  35620. }
  35621. /**
  35622. * Aborts ongoing fetch requests.
  35623. *
  35624. * @return {ImageBitmapLoader} A reference to this instance.
  35625. */
  35626. abort() {
  35627. this._abortController.abort();
  35628. this._abortController = new AbortController();
  35629. return this;
  35630. }
  35631. }
  35632. let _context;
  35633. /**
  35634. * Manages the global audio context in the engine.
  35635. *
  35636. * @hideconstructor
  35637. */
  35638. class AudioContext {
  35639. /**
  35640. * Returns the global native audio context.
  35641. *
  35642. * @return {AudioContext} The native audio context.
  35643. */
  35644. static getContext() {
  35645. if ( _context === undefined ) {
  35646. _context = new ( window.AudioContext || window.webkitAudioContext )();
  35647. }
  35648. return _context;
  35649. }
  35650. /**
  35651. * Allows to set the global native audio context from outside.
  35652. *
  35653. * @param {AudioContext} value - The native context to set.
  35654. */
  35655. static setContext( value ) {
  35656. _context = value;
  35657. }
  35658. }
  35659. /**
  35660. * Class for loading audio buffers. Audios are internally
  35661. * loaded via {@link FileLoader}.
  35662. *
  35663. * ```js
  35664. * const audioListener = new THREE.AudioListener();
  35665. * const ambientSound = new THREE.Audio( audioListener );
  35666. *
  35667. * const loader = new THREE.AudioLoader();
  35668. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  35669. *
  35670. * ambientSound.setBuffer( audioBuffer );
  35671. * ambientSound.play();
  35672. * ```
  35673. *
  35674. * @augments Loader
  35675. */
  35676. class AudioLoader extends Loader {
  35677. /**
  35678. * Constructs a new audio loader.
  35679. *
  35680. * @param {LoadingManager} [manager] - The loading manager.
  35681. */
  35682. constructor( manager ) {
  35683. super( manager );
  35684. }
  35685. /**
  35686. * Starts loading from the given URL and passes the loaded audio buffer
  35687. * to the `onLoad()` callback.
  35688. *
  35689. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35690. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  35691. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35692. * @param {onErrorCallback} onError - Executed when errors occur.
  35693. */
  35694. load( url, onLoad, onProgress, onError ) {
  35695. const scope = this;
  35696. const loader = new FileLoader( this.manager );
  35697. loader.setResponseType( 'arraybuffer' );
  35698. loader.setPath( this.path );
  35699. loader.setRequestHeader( this.requestHeader );
  35700. loader.setWithCredentials( this.withCredentials );
  35701. loader.load( url, function ( buffer ) {
  35702. try {
  35703. // Create a copy of the buffer. The `decodeAudioData` method
  35704. // detaches the buffer when complete, preventing reuse.
  35705. const bufferCopy = buffer.slice( 0 );
  35706. const context = AudioContext.getContext();
  35707. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  35708. onLoad( audioBuffer );
  35709. } ).catch( handleError );
  35710. } catch ( e ) {
  35711. handleError( e );
  35712. }
  35713. }, onProgress, onError );
  35714. function handleError( e ) {
  35715. if ( onError ) {
  35716. onError( e );
  35717. } else {
  35718. console.error( e );
  35719. }
  35720. scope.manager.itemError( url );
  35721. }
  35722. }
  35723. }
  35724. const _eyeRight = /*@__PURE__*/ new Matrix4();
  35725. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  35726. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  35727. /**
  35728. * A special type of camera that uses two perspective cameras with
  35729. * stereoscopic projection. Can be used for rendering stereo effects
  35730. * like [3D Anaglyph]{@link https://en.wikipedia.org/wiki/Anaglyph_3D} or
  35731. * [Parallax Barrier]{@link https://en.wikipedia.org/wiki/parallax_barrier}.
  35732. */
  35733. class StereoCamera {
  35734. /**
  35735. * Constructs a new stereo camera.
  35736. */
  35737. constructor() {
  35738. /**
  35739. * The type property is used for detecting the object type
  35740. * in context of serialization/deserialization.
  35741. *
  35742. * @type {string}
  35743. * @readonly
  35744. */
  35745. this.type = 'StereoCamera';
  35746. /**
  35747. * The aspect.
  35748. *
  35749. * @type {number}
  35750. * @default 1
  35751. */
  35752. this.aspect = 1;
  35753. /**
  35754. * The eye separation which represents the distance
  35755. * between the left and right camera.
  35756. *
  35757. * @type {number}
  35758. * @default 0.064
  35759. */
  35760. this.eyeSep = 0.064;
  35761. /**
  35762. * The camera representing the left eye. This is added to layer `1` so objects to be
  35763. * rendered by the left camera must also be added to this layer.
  35764. *
  35765. * @type {PerspectiveCamera}
  35766. */
  35767. this.cameraL = new PerspectiveCamera();
  35768. this.cameraL.layers.enable( 1 );
  35769. this.cameraL.matrixAutoUpdate = false;
  35770. /**
  35771. * The camera representing the right eye. This is added to layer `2` so objects to be
  35772. * rendered by the right camera must also be added to this layer.
  35773. *
  35774. * @type {PerspectiveCamera}
  35775. */
  35776. this.cameraR = new PerspectiveCamera();
  35777. this.cameraR.layers.enable( 2 );
  35778. this.cameraR.matrixAutoUpdate = false;
  35779. this._cache = {
  35780. focus: null,
  35781. fov: null,
  35782. aspect: null,
  35783. near: null,
  35784. far: null,
  35785. zoom: null,
  35786. eyeSep: null
  35787. };
  35788. }
  35789. /**
  35790. * Updates the stereo camera based on the given perspective camera.
  35791. *
  35792. * @param {PerspectiveCamera} camera - The perspective camera.
  35793. */
  35794. update( camera ) {
  35795. const cache = this._cache;
  35796. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  35797. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  35798. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  35799. if ( needsUpdate ) {
  35800. cache.focus = camera.focus;
  35801. cache.fov = camera.fov;
  35802. cache.aspect = camera.aspect * this.aspect;
  35803. cache.near = camera.near;
  35804. cache.far = camera.far;
  35805. cache.zoom = camera.zoom;
  35806. cache.eyeSep = this.eyeSep;
  35807. // Off-axis stereoscopic effect based on
  35808. // http://paulbourke.net/stereographics/stereorender/
  35809. _projectionMatrix.copy( camera.projectionMatrix );
  35810. const eyeSepHalf = cache.eyeSep / 2;
  35811. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  35812. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  35813. let xmin, xmax;
  35814. // translate xOffset
  35815. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  35816. _eyeRight.elements[ 12 ] = eyeSepHalf;
  35817. // for left eye
  35818. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  35819. xmax = ymax * cache.aspect + eyeSepOnProjection;
  35820. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  35821. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  35822. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  35823. // for right eye
  35824. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  35825. xmax = ymax * cache.aspect - eyeSepOnProjection;
  35826. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  35827. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  35828. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  35829. }
  35830. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  35831. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  35832. }
  35833. }
  35834. /**
  35835. * This type of camera can be used in order to efficiently render a scene with a
  35836. * predefined set of cameras. This is an important performance aspect for
  35837. * rendering VR scenes.
  35838. *
  35839. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  35840. * to define for each sub camera the `viewport` property which determines the
  35841. * part of the viewport that is rendered with this camera.
  35842. *
  35843. * @augments PerspectiveCamera
  35844. */
  35845. class ArrayCamera extends PerspectiveCamera {
  35846. /**
  35847. * Constructs a new array camera.
  35848. *
  35849. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  35850. */
  35851. constructor( array = [] ) {
  35852. super();
  35853. /**
  35854. * This flag can be used for type testing.
  35855. *
  35856. * @type {boolean}
  35857. * @readonly
  35858. * @default true
  35859. */
  35860. this.isArrayCamera = true;
  35861. /**
  35862. * Whether this camera is used with multiview rendering or not.
  35863. *
  35864. * @type {boolean}
  35865. * @readonly
  35866. * @default false
  35867. */
  35868. this.isMultiViewCamera = false;
  35869. /**
  35870. * An array of perspective sub cameras.
  35871. *
  35872. * @type {Array<PerspectiveCamera>}
  35873. */
  35874. this.cameras = array;
  35875. }
  35876. }
  35877. /**
  35878. * Class for keeping track of time.
  35879. */
  35880. class Clock {
  35881. /**
  35882. * Constructs a new clock.
  35883. *
  35884. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  35885. * `getDelta()` is called for the first time.
  35886. */
  35887. constructor( autoStart = true ) {
  35888. /**
  35889. * If set to `true`, the clock starts automatically when `getDelta()` is called
  35890. * for the first time.
  35891. *
  35892. * @type {boolean}
  35893. * @default true
  35894. */
  35895. this.autoStart = autoStart;
  35896. /**
  35897. * Holds the time at which the clock's `start()` method was last called.
  35898. *
  35899. * @type {number}
  35900. * @default 0
  35901. */
  35902. this.startTime = 0;
  35903. /**
  35904. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  35905. * `getDelta()` methods were last called.
  35906. *
  35907. * @type {number}
  35908. * @default 0
  35909. */
  35910. this.oldTime = 0;
  35911. /**
  35912. * Keeps track of the total time that the clock has been running.
  35913. *
  35914. * @type {number}
  35915. * @default 0
  35916. */
  35917. this.elapsedTime = 0;
  35918. /**
  35919. * Whether the clock is running or not.
  35920. *
  35921. * @type {boolean}
  35922. * @default true
  35923. */
  35924. this.running = false;
  35925. }
  35926. /**
  35927. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  35928. * called by the class.
  35929. */
  35930. start() {
  35931. this.startTime = performance.now();
  35932. this.oldTime = this.startTime;
  35933. this.elapsedTime = 0;
  35934. this.running = true;
  35935. }
  35936. /**
  35937. * Stops the clock.
  35938. */
  35939. stop() {
  35940. this.getElapsedTime();
  35941. this.running = false;
  35942. this.autoStart = false;
  35943. }
  35944. /**
  35945. * Returns the elapsed time in seconds.
  35946. *
  35947. * @return {number} The elapsed time.
  35948. */
  35949. getElapsedTime() {
  35950. this.getDelta();
  35951. return this.elapsedTime;
  35952. }
  35953. /**
  35954. * Returns the delta time in seconds.
  35955. *
  35956. * @return {number} The delta time.
  35957. */
  35958. getDelta() {
  35959. let diff = 0;
  35960. if ( this.autoStart && ! this.running ) {
  35961. this.start();
  35962. return 0;
  35963. }
  35964. if ( this.running ) {
  35965. const newTime = performance.now();
  35966. diff = ( newTime - this.oldTime ) / 1000;
  35967. this.oldTime = newTime;
  35968. this.elapsedTime += diff;
  35969. }
  35970. return diff;
  35971. }
  35972. }
  35973. const _position$1 = /*@__PURE__*/ new Vector3();
  35974. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  35975. const _scale$1 = /*@__PURE__*/ new Vector3();
  35976. const _forward = /*@__PURE__*/ new Vector3();
  35977. const _up = /*@__PURE__*/ new Vector3();
  35978. /**
  35979. * The class represents a virtual listener of the all positional and non-positional audio effects
  35980. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  35981. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  35982. *
  35983. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  35984. * camera represents the 3D transformation of the listener.
  35985. *
  35986. * @augments Object3D
  35987. */
  35988. class AudioListener extends Object3D {
  35989. /**
  35990. * Constructs a new audio listener.
  35991. */
  35992. constructor() {
  35993. super();
  35994. this.type = 'AudioListener';
  35995. /**
  35996. * The native audio context.
  35997. *
  35998. * @type {AudioContext}
  35999. * @readonly
  36000. */
  36001. this.context = AudioContext.getContext();
  36002. /**
  36003. * The gain node used for volume control.
  36004. *
  36005. * @type {GainNode}
  36006. * @readonly
  36007. */
  36008. this.gain = this.context.createGain();
  36009. this.gain.connect( this.context.destination );
  36010. /**
  36011. * An optional filter.
  36012. *
  36013. * Defined via {@link AudioListener#setFilter}.
  36014. *
  36015. * @type {?AudioNode}
  36016. * @default null
  36017. * @readonly
  36018. */
  36019. this.filter = null;
  36020. /**
  36021. * Time delta values required for `linearRampToValueAtTime()` usage.
  36022. *
  36023. * @type {number}
  36024. * @default 0
  36025. * @readonly
  36026. */
  36027. this.timeDelta = 0;
  36028. // private
  36029. this._clock = new Clock();
  36030. }
  36031. /**
  36032. * Returns the listener's input node.
  36033. *
  36034. * This method is used by other audio nodes to connect to this listener.
  36035. *
  36036. * @return {GainNode} The input node.
  36037. */
  36038. getInput() {
  36039. return this.gain;
  36040. }
  36041. /**
  36042. * Removes the current filter from this listener.
  36043. *
  36044. * @return {AudioListener} A reference to this listener.
  36045. */
  36046. removeFilter() {
  36047. if ( this.filter !== null ) {
  36048. this.gain.disconnect( this.filter );
  36049. this.filter.disconnect( this.context.destination );
  36050. this.gain.connect( this.context.destination );
  36051. this.filter = null;
  36052. }
  36053. return this;
  36054. }
  36055. /**
  36056. * Returns the current set filter.
  36057. *
  36058. * @return {?AudioNode} The filter.
  36059. */
  36060. getFilter() {
  36061. return this.filter;
  36062. }
  36063. /**
  36064. * Sets the given filter to this listener.
  36065. *
  36066. * @param {AudioNode} value - The filter to set.
  36067. * @return {AudioListener} A reference to this listener.
  36068. */
  36069. setFilter( value ) {
  36070. if ( this.filter !== null ) {
  36071. this.gain.disconnect( this.filter );
  36072. this.filter.disconnect( this.context.destination );
  36073. } else {
  36074. this.gain.disconnect( this.context.destination );
  36075. }
  36076. this.filter = value;
  36077. this.gain.connect( this.filter );
  36078. this.filter.connect( this.context.destination );
  36079. return this;
  36080. }
  36081. /**
  36082. * Returns the applications master volume.
  36083. *
  36084. * @return {number} The master volume.
  36085. */
  36086. getMasterVolume() {
  36087. return this.gain.gain.value;
  36088. }
  36089. /**
  36090. * Sets the applications master volume. This volume setting affects
  36091. * all audio nodes in the scene.
  36092. *
  36093. * @param {number} value - The master volume to set.
  36094. * @return {AudioListener} A reference to this listener.
  36095. */
  36096. setMasterVolume( value ) {
  36097. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36098. return this;
  36099. }
  36100. updateMatrixWorld( force ) {
  36101. super.updateMatrixWorld( force );
  36102. const listener = this.context.listener;
  36103. this.timeDelta = this._clock.getDelta();
  36104. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  36105. // the initial forward and up directions must be orthogonal
  36106. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  36107. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  36108. if ( listener.positionX ) {
  36109. // code path for Chrome (see #14393)
  36110. const endTime = this.context.currentTime + this.timeDelta;
  36111. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  36112. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  36113. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  36114. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  36115. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  36116. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  36117. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  36118. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  36119. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  36120. } else {
  36121. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  36122. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  36123. }
  36124. }
  36125. }
  36126. /**
  36127. * Represents a non-positional ( global ) audio object.
  36128. *
  36129. * This and related audio modules make use of the [Web Audio API]{@link https://www.w3.org/TR/webaudio-1.1/}.
  36130. *
  36131. * ```js
  36132. * // create an AudioListener and add it to the camera
  36133. * const listener = new THREE.AudioListener();
  36134. * camera.add( listener );
  36135. *
  36136. * // create a global audio source
  36137. * const sound = new THREE.Audio( listener );
  36138. *
  36139. * // load a sound and set it as the Audio object's buffer
  36140. * const audioLoader = new THREE.AudioLoader();
  36141. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36142. * sound.setBuffer( buffer );
  36143. * sound.setLoop( true );
  36144. * sound.setVolume( 0.5 );
  36145. * sound.play();
  36146. * });
  36147. * ```
  36148. *
  36149. * @augments Object3D
  36150. */
  36151. class Audio extends Object3D {
  36152. /**
  36153. * Constructs a new audio.
  36154. *
  36155. * @param {AudioListener} listener - The global audio listener.
  36156. */
  36157. constructor( listener ) {
  36158. super();
  36159. this.type = 'Audio';
  36160. /**
  36161. * The global audio listener.
  36162. *
  36163. * @type {AudioListener}
  36164. * @readonly
  36165. */
  36166. this.listener = listener;
  36167. /**
  36168. * The audio context.
  36169. *
  36170. * @type {AudioContext}
  36171. * @readonly
  36172. */
  36173. this.context = listener.context;
  36174. /**
  36175. * The gain node used for volume control.
  36176. *
  36177. * @type {GainNode}
  36178. * @readonly
  36179. */
  36180. this.gain = this.context.createGain();
  36181. this.gain.connect( listener.getInput() );
  36182. /**
  36183. * Whether to start playback automatically or not.
  36184. *
  36185. * @type {boolean}
  36186. * @default false
  36187. */
  36188. this.autoplay = false;
  36189. /**
  36190. * A reference to an audio buffer.
  36191. *
  36192. * Defined via {@link Audio#setBuffer}.
  36193. *
  36194. * @type {?AudioBuffer}
  36195. * @default null
  36196. * @readonly
  36197. */
  36198. this.buffer = null;
  36199. /**
  36200. * Modify pitch, measured in cents. +/- 100 is a semitone.
  36201. * +/- 1200 is an octave.
  36202. *
  36203. * Defined via {@link Audio#setDetune}.
  36204. *
  36205. * @type {number}
  36206. * @default 0
  36207. * @readonly
  36208. */
  36209. this.detune = 0;
  36210. /**
  36211. * Whether the audio should loop or not.
  36212. *
  36213. * Defined via {@link Audio#setLoop}.
  36214. *
  36215. * @type {boolean}
  36216. * @default false
  36217. * @readonly
  36218. */
  36219. this.loop = false;
  36220. /**
  36221. * Defines where in the audio buffer the replay should
  36222. * start, in seconds.
  36223. *
  36224. * @type {number}
  36225. * @default 0
  36226. */
  36227. this.loopStart = 0;
  36228. /**
  36229. * Defines where in the audio buffer the replay should
  36230. * stop, in seconds.
  36231. *
  36232. * @type {number}
  36233. * @default 0
  36234. */
  36235. this.loopEnd = 0;
  36236. /**
  36237. * An offset to the time within the audio buffer the playback
  36238. * should begin, in seconds.
  36239. *
  36240. * @type {number}
  36241. * @default 0
  36242. */
  36243. this.offset = 0;
  36244. /**
  36245. * Overrides the default duration of the audio.
  36246. *
  36247. * @type {undefined|number}
  36248. * @default undefined
  36249. */
  36250. this.duration = undefined;
  36251. /**
  36252. * The playback speed.
  36253. *
  36254. * Defined via {@link Audio#setPlaybackRate}.
  36255. *
  36256. * @type {number}
  36257. * @readonly
  36258. * @default 1
  36259. */
  36260. this.playbackRate = 1;
  36261. /**
  36262. * Indicates whether the audio is playing or not.
  36263. *
  36264. * This flag will be automatically set when using {@link Audio#play},
  36265. * {@link Audio#pause}, {@link Audio#stop}.
  36266. *
  36267. * @type {boolean}
  36268. * @readonly
  36269. * @default false
  36270. */
  36271. this.isPlaying = false;
  36272. /**
  36273. * Indicates whether the audio playback can be controlled
  36274. * with method like {@link Audio#play} or {@link Audio#pause}.
  36275. *
  36276. * This flag will be automatically set when audio sources are
  36277. * defined.
  36278. *
  36279. * @type {boolean}
  36280. * @readonly
  36281. * @default true
  36282. */
  36283. this.hasPlaybackControl = true;
  36284. /**
  36285. * Holds a reference to the current audio source.
  36286. *
  36287. * The property is automatically by one of the `set*()` methods.
  36288. *
  36289. * @type {?AudioNode}
  36290. * @readonly
  36291. * @default null
  36292. */
  36293. this.source = null;
  36294. /**
  36295. * Defines the source type.
  36296. *
  36297. * The property is automatically by one of the `set*()` methods.
  36298. *
  36299. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  36300. * @readonly
  36301. * @default 'empty'
  36302. */
  36303. this.sourceType = 'empty';
  36304. this._startedAt = 0;
  36305. this._progress = 0;
  36306. this._connected = false;
  36307. /**
  36308. * Can be used to apply a variety of low-order filters to create
  36309. * more complex sound effects e.g. via `BiquadFilterNode`.
  36310. *
  36311. * The property is automatically set by {@link Audio#setFilters}.
  36312. *
  36313. * @type {Array<AudioNode>}
  36314. * @readonly
  36315. */
  36316. this.filters = [];
  36317. }
  36318. /**
  36319. * Returns the output audio node.
  36320. *
  36321. * @return {GainNode} The output node.
  36322. */
  36323. getOutput() {
  36324. return this.gain;
  36325. }
  36326. /**
  36327. * Sets the given audio node as the source of this instance.
  36328. *
  36329. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  36330. *
  36331. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  36332. * @return {Audio} A reference to this instance.
  36333. */
  36334. setNodeSource( audioNode ) {
  36335. this.hasPlaybackControl = false;
  36336. this.sourceType = 'audioNode';
  36337. this.source = audioNode;
  36338. this.connect();
  36339. return this;
  36340. }
  36341. /**
  36342. * Sets the given media element as the source of this instance.
  36343. *
  36344. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  36345. *
  36346. * @param {HTMLMediaElement} mediaElement - The media element.
  36347. * @return {Audio} A reference to this instance.
  36348. */
  36349. setMediaElementSource( mediaElement ) {
  36350. this.hasPlaybackControl = false;
  36351. this.sourceType = 'mediaNode';
  36352. this.source = this.context.createMediaElementSource( mediaElement );
  36353. this.connect();
  36354. return this;
  36355. }
  36356. /**
  36357. * Sets the given media stream as the source of this instance.
  36358. *
  36359. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  36360. *
  36361. * @param {MediaStream} mediaStream - The media stream.
  36362. * @return {Audio} A reference to this instance.
  36363. */
  36364. setMediaStreamSource( mediaStream ) {
  36365. this.hasPlaybackControl = false;
  36366. this.sourceType = 'mediaStreamNode';
  36367. this.source = this.context.createMediaStreamSource( mediaStream );
  36368. this.connect();
  36369. return this;
  36370. }
  36371. /**
  36372. * Sets the given audio buffer as the source of this instance.
  36373. *
  36374. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  36375. *
  36376. * @param {AudioBuffer} audioBuffer - The audio buffer.
  36377. * @return {Audio} A reference to this instance.
  36378. */
  36379. setBuffer( audioBuffer ) {
  36380. this.buffer = audioBuffer;
  36381. this.sourceType = 'buffer';
  36382. if ( this.autoplay ) this.play();
  36383. return this;
  36384. }
  36385. /**
  36386. * Starts the playback of the audio.
  36387. *
  36388. * Can only be used with compatible audio sources that allow playback control.
  36389. *
  36390. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  36391. * @return {Audio|undefined} A reference to this instance.
  36392. */
  36393. play( delay = 0 ) {
  36394. if ( this.isPlaying === true ) {
  36395. console.warn( 'THREE.Audio: Audio is already playing.' );
  36396. return;
  36397. }
  36398. if ( this.hasPlaybackControl === false ) {
  36399. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36400. return;
  36401. }
  36402. this._startedAt = this.context.currentTime + delay;
  36403. const source = this.context.createBufferSource();
  36404. source.buffer = this.buffer;
  36405. source.loop = this.loop;
  36406. source.loopStart = this.loopStart;
  36407. source.loopEnd = this.loopEnd;
  36408. source.onended = this.onEnded.bind( this );
  36409. source.start( this._startedAt, this._progress + this.offset, this.duration );
  36410. this.isPlaying = true;
  36411. this.source = source;
  36412. this.setDetune( this.detune );
  36413. this.setPlaybackRate( this.playbackRate );
  36414. return this.connect();
  36415. }
  36416. /**
  36417. * Pauses the playback of the audio.
  36418. *
  36419. * Can only be used with compatible audio sources that allow playback control.
  36420. *
  36421. * @return {Audio|undefined} A reference to this instance.
  36422. */
  36423. pause() {
  36424. if ( this.hasPlaybackControl === false ) {
  36425. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36426. return;
  36427. }
  36428. if ( this.isPlaying === true ) {
  36429. // update current progress
  36430. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  36431. if ( this.loop === true ) {
  36432. // ensure _progress does not exceed duration with looped audios
  36433. this._progress = this._progress % ( this.duration || this.buffer.duration );
  36434. }
  36435. this.source.stop();
  36436. this.source.onended = null;
  36437. this.isPlaying = false;
  36438. }
  36439. return this;
  36440. }
  36441. /**
  36442. * Stops 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 stop playing.
  36447. * @return {Audio|undefined} A reference to this instance.
  36448. */
  36449. stop( delay = 0 ) {
  36450. if ( this.hasPlaybackControl === false ) {
  36451. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36452. return;
  36453. }
  36454. this._progress = 0;
  36455. if ( this.source !== null ) {
  36456. this.source.stop( this.context.currentTime + delay );
  36457. this.source.onended = null;
  36458. }
  36459. this.isPlaying = false;
  36460. return this;
  36461. }
  36462. /**
  36463. * Connects to the audio source. This is used internally on
  36464. * initialisation and when setting / removing filters.
  36465. *
  36466. * @return {Audio} A reference to this instance.
  36467. */
  36468. connect() {
  36469. if ( this.filters.length > 0 ) {
  36470. this.source.connect( this.filters[ 0 ] );
  36471. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36472. this.filters[ i - 1 ].connect( this.filters[ i ] );
  36473. }
  36474. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  36475. } else {
  36476. this.source.connect( this.getOutput() );
  36477. }
  36478. this._connected = true;
  36479. return this;
  36480. }
  36481. /**
  36482. * Disconnects to the audio source. This is used internally on
  36483. * initialisation and when setting / removing filters.
  36484. *
  36485. * @return {Audio|undefined} A reference to this instance.
  36486. */
  36487. disconnect() {
  36488. if ( this._connected === false ) {
  36489. return;
  36490. }
  36491. if ( this.filters.length > 0 ) {
  36492. this.source.disconnect( this.filters[ 0 ] );
  36493. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36494. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  36495. }
  36496. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  36497. } else {
  36498. this.source.disconnect( this.getOutput() );
  36499. }
  36500. this._connected = false;
  36501. return this;
  36502. }
  36503. /**
  36504. * Returns the current set filters.
  36505. *
  36506. * @return {Array<AudioNode>} The list of filters.
  36507. */
  36508. getFilters() {
  36509. return this.filters;
  36510. }
  36511. /**
  36512. * Sets an array of filters and connects them with the audio source.
  36513. *
  36514. * @param {Array<AudioNode>} [value] - A list of filters.
  36515. * @return {Audio} A reference to this instance.
  36516. */
  36517. setFilters( value ) {
  36518. if ( ! value ) value = [];
  36519. if ( this._connected === true ) {
  36520. this.disconnect();
  36521. this.filters = value.slice();
  36522. this.connect();
  36523. } else {
  36524. this.filters = value.slice();
  36525. }
  36526. return this;
  36527. }
  36528. /**
  36529. * Defines the detuning of oscillation in cents.
  36530. *
  36531. * @param {number} value - The detuning of oscillation in cents.
  36532. * @return {Audio} A reference to this instance.
  36533. */
  36534. setDetune( value ) {
  36535. this.detune = value;
  36536. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  36537. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  36538. }
  36539. return this;
  36540. }
  36541. /**
  36542. * Returns the detuning of oscillation in cents.
  36543. *
  36544. * @return {number} The detuning of oscillation in cents.
  36545. */
  36546. getDetune() {
  36547. return this.detune;
  36548. }
  36549. /**
  36550. * Returns the first filter in the list of filters.
  36551. *
  36552. * @return {AudioNode|undefined} The first filter in the list of filters.
  36553. */
  36554. getFilter() {
  36555. return this.getFilters()[ 0 ];
  36556. }
  36557. /**
  36558. * Applies a single filter node to the audio.
  36559. *
  36560. * @param {AudioNode} [filter] - The filter to set.
  36561. * @return {Audio} A reference to this instance.
  36562. */
  36563. setFilter( filter ) {
  36564. return this.setFilters( filter ? [ filter ] : [] );
  36565. }
  36566. /**
  36567. * Sets the playback rate.
  36568. *
  36569. * Can only be used with compatible audio sources that allow playback control.
  36570. *
  36571. * @param {number} [value] - The playback rate to set.
  36572. * @return {Audio|undefined} A reference to this instance.
  36573. */
  36574. setPlaybackRate( value ) {
  36575. if ( this.hasPlaybackControl === false ) {
  36576. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36577. return;
  36578. }
  36579. this.playbackRate = value;
  36580. if ( this.isPlaying === true ) {
  36581. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  36582. }
  36583. return this;
  36584. }
  36585. /**
  36586. * Returns the current playback rate.
  36587. * @return {number} The playback rate.
  36588. */
  36589. getPlaybackRate() {
  36590. return this.playbackRate;
  36591. }
  36592. /**
  36593. * Automatically called when playback finished.
  36594. */
  36595. onEnded() {
  36596. this.isPlaying = false;
  36597. this._progress = 0;
  36598. }
  36599. /**
  36600. * Returns the loop flag.
  36601. *
  36602. * Can only be used with compatible audio sources that allow playback control.
  36603. *
  36604. * @return {boolean} Whether the audio should loop or not.
  36605. */
  36606. getLoop() {
  36607. if ( this.hasPlaybackControl === false ) {
  36608. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36609. return false;
  36610. }
  36611. return this.loop;
  36612. }
  36613. /**
  36614. * Sets the loop flag.
  36615. *
  36616. * Can only be used with compatible audio sources that allow playback control.
  36617. *
  36618. * @param {boolean} value - Whether the audio should loop or not.
  36619. * @return {Audio|undefined} A reference to this instance.
  36620. */
  36621. setLoop( value ) {
  36622. if ( this.hasPlaybackControl === false ) {
  36623. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36624. return;
  36625. }
  36626. this.loop = value;
  36627. if ( this.isPlaying === true ) {
  36628. this.source.loop = this.loop;
  36629. }
  36630. return this;
  36631. }
  36632. /**
  36633. * Sets the loop start value which defines where in the audio buffer the replay should
  36634. * start, in seconds.
  36635. *
  36636. * @param {number} value - The loop start value.
  36637. * @return {Audio} A reference to this instance.
  36638. */
  36639. setLoopStart( value ) {
  36640. this.loopStart = value;
  36641. return this;
  36642. }
  36643. /**
  36644. * Sets the loop end value which defines where in the audio buffer the replay should
  36645. * stop, in seconds.
  36646. *
  36647. * @param {number} value - The loop end value.
  36648. * @return {Audio} A reference to this instance.
  36649. */
  36650. setLoopEnd( value ) {
  36651. this.loopEnd = value;
  36652. return this;
  36653. }
  36654. /**
  36655. * Returns the volume.
  36656. *
  36657. * @return {number} The volume.
  36658. */
  36659. getVolume() {
  36660. return this.gain.gain.value;
  36661. }
  36662. /**
  36663. * Sets the volume.
  36664. *
  36665. * @param {number} value - The volume to set.
  36666. * @return {Audio} A reference to this instance.
  36667. */
  36668. setVolume( value ) {
  36669. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36670. return this;
  36671. }
  36672. copy( source, recursive ) {
  36673. super.copy( source, recursive );
  36674. if ( source.sourceType !== 'buffer' ) {
  36675. console.warn( 'THREE.Audio: Audio source type cannot be copied.' );
  36676. return this;
  36677. }
  36678. this.autoplay = source.autoplay;
  36679. this.buffer = source.buffer;
  36680. this.detune = source.detune;
  36681. this.loop = source.loop;
  36682. this.loopStart = source.loopStart;
  36683. this.loopEnd = source.loopEnd;
  36684. this.offset = source.offset;
  36685. this.duration = source.duration;
  36686. this.playbackRate = source.playbackRate;
  36687. this.hasPlaybackControl = source.hasPlaybackControl;
  36688. this.sourceType = source.sourceType;
  36689. this.filters = source.filters.slice();
  36690. return this;
  36691. }
  36692. clone( recursive ) {
  36693. return new this.constructor( this.listener ).copy( this, recursive );
  36694. }
  36695. }
  36696. const _position = /*@__PURE__*/ new Vector3();
  36697. const _quaternion = /*@__PURE__*/ new Quaternion();
  36698. const _scale = /*@__PURE__*/ new Vector3();
  36699. const _orientation = /*@__PURE__*/ new Vector3();
  36700. /**
  36701. * Represents a positional audio object.
  36702. *
  36703. * ```js
  36704. * // create an AudioListener and add it to the camera
  36705. * const listener = new THREE.AudioListener();
  36706. * camera.add( listener );
  36707. *
  36708. * // create the PositionalAudio object (passing in the listener)
  36709. * const sound = new THREE.PositionalAudio( listener );
  36710. *
  36711. * // load a sound and set it as the PositionalAudio object's buffer
  36712. * const audioLoader = new THREE.AudioLoader();
  36713. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  36714. * sound.setBuffer( buffer );
  36715. * sound.setRefDistance( 20 );
  36716. * sound.play();
  36717. * });
  36718. *
  36719. * // create an object for the sound to play from
  36720. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  36721. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  36722. * const mesh = new THREE.Mesh( sphere, material );
  36723. * scene.add( mesh );
  36724. *
  36725. * // finally add the sound to the mesh
  36726. * mesh.add( sound );
  36727. *
  36728. * @augments Audio
  36729. */
  36730. class PositionalAudio extends Audio {
  36731. /**
  36732. * Constructs a positional audio.
  36733. *
  36734. * @param {AudioListener} listener - The global audio listener.
  36735. */
  36736. constructor( listener ) {
  36737. super( listener );
  36738. /**
  36739. * The panner node represents the location, direction, and behavior of an audio
  36740. * source in 3D space.
  36741. *
  36742. * @type {PannerNode}
  36743. * @readonly
  36744. */
  36745. this.panner = this.context.createPanner();
  36746. this.panner.panningModel = 'HRTF';
  36747. this.panner.connect( this.gain );
  36748. }
  36749. connect() {
  36750. super.connect();
  36751. this.panner.connect( this.gain );
  36752. return this;
  36753. }
  36754. disconnect() {
  36755. super.disconnect();
  36756. this.panner.disconnect( this.gain );
  36757. return this;
  36758. }
  36759. getOutput() {
  36760. return this.panner;
  36761. }
  36762. /**
  36763. * Returns the current reference distance.
  36764. *
  36765. * @return {number} The reference distance.
  36766. */
  36767. getRefDistance() {
  36768. return this.panner.refDistance;
  36769. }
  36770. /**
  36771. * Defines the reference distance for reducing volume as the audio source moves
  36772. * further from the listener – i.e. the distance at which the volume reduction
  36773. * starts taking effect.
  36774. *
  36775. * @param {number} value - The reference distance to set.
  36776. * @return {PositionalAudio} A reference to this instance.
  36777. */
  36778. setRefDistance( value ) {
  36779. this.panner.refDistance = value;
  36780. return this;
  36781. }
  36782. /**
  36783. * Returns the current rolloff factor.
  36784. *
  36785. * @return {number} The rolloff factor.
  36786. */
  36787. getRolloffFactor() {
  36788. return this.panner.rolloffFactor;
  36789. }
  36790. /**
  36791. * Defines how quickly the volume is reduced as the source moves away from the listener.
  36792. *
  36793. * @param {number} value - The rolloff factor.
  36794. * @return {PositionalAudio} A reference to this instance.
  36795. */
  36796. setRolloffFactor( value ) {
  36797. this.panner.rolloffFactor = value;
  36798. return this;
  36799. }
  36800. /**
  36801. * Returns the current distance model.
  36802. *
  36803. * @return {('linear'|'inverse'|'exponential')} The distance model.
  36804. */
  36805. getDistanceModel() {
  36806. return this.panner.distanceModel;
  36807. }
  36808. /**
  36809. * Defines which algorithm to use to reduce the volume of the audio source
  36810. * as it moves away from the listener.
  36811. *
  36812. * Read [the spec]{@link https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype}
  36813. * for more details.
  36814. *
  36815. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  36816. * @return {PositionalAudio} A reference to this instance.
  36817. */
  36818. setDistanceModel( value ) {
  36819. this.panner.distanceModel = value;
  36820. return this;
  36821. }
  36822. /**
  36823. * Returns the current max distance.
  36824. *
  36825. * @return {number} The max distance.
  36826. */
  36827. getMaxDistance() {
  36828. return this.panner.maxDistance;
  36829. }
  36830. /**
  36831. * Defines the maximum distance between the audio source and the listener,
  36832. * after which the volume is not reduced any further.
  36833. *
  36834. * This value is used only by the `linear` distance model.
  36835. *
  36836. * @param {number} value - The max distance.
  36837. * @return {PositionalAudio} A reference to this instance.
  36838. */
  36839. setMaxDistance( value ) {
  36840. this.panner.maxDistance = value;
  36841. return this;
  36842. }
  36843. /**
  36844. * Sets the directional cone in which the audio can be listened.
  36845. *
  36846. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  36847. * @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.
  36848. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  36849. * @return {PositionalAudio} A reference to this instance.
  36850. */
  36851. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  36852. this.panner.coneInnerAngle = coneInnerAngle;
  36853. this.panner.coneOuterAngle = coneOuterAngle;
  36854. this.panner.coneOuterGain = coneOuterGain;
  36855. return this;
  36856. }
  36857. updateMatrixWorld( force ) {
  36858. super.updateMatrixWorld( force );
  36859. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  36860. this.matrixWorld.decompose( _position, _quaternion, _scale );
  36861. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  36862. const panner = this.panner;
  36863. if ( panner.positionX ) {
  36864. // code path for Chrome and Firefox (see #14393)
  36865. const endTime = this.context.currentTime + this.listener.timeDelta;
  36866. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  36867. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  36868. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  36869. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  36870. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  36871. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  36872. } else {
  36873. panner.setPosition( _position.x, _position.y, _position.z );
  36874. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  36875. }
  36876. }
  36877. }
  36878. /**
  36879. * This class can be used to analyse audio data.
  36880. *
  36881. * ```js
  36882. * // create an AudioListener and add it to the camera
  36883. * const listener = new THREE.AudioListener();
  36884. * camera.add( listener );
  36885. *
  36886. * // create an Audio source
  36887. * const sound = new THREE.Audio( listener );
  36888. *
  36889. * // load a sound and set it as the Audio object's buffer
  36890. * const audioLoader = new THREE.AudioLoader();
  36891. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36892. * sound.setBuffer( buffer );
  36893. * sound.setLoop(true);
  36894. * sound.setVolume(0.5);
  36895. * sound.play();
  36896. * });
  36897. *
  36898. * // create an AudioAnalyser, passing in the sound and desired fftSize
  36899. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  36900. *
  36901. * // get the average frequency of the sound
  36902. * const data = analyser.getAverageFrequency();
  36903. * ```
  36904. */
  36905. class AudioAnalyser {
  36906. /**
  36907. * Constructs a new audio analyzer.
  36908. *
  36909. * @param {Audio} audio - The audio to analyze.
  36910. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  36911. */
  36912. constructor( audio, fftSize = 2048 ) {
  36913. /**
  36914. * The global audio listener.
  36915. *
  36916. * @type {AnalyserNode}
  36917. */
  36918. this.analyser = audio.context.createAnalyser();
  36919. this.analyser.fftSize = fftSize;
  36920. /**
  36921. * Holds the analyzed data.
  36922. *
  36923. * @type {Uint8Array}
  36924. */
  36925. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  36926. audio.getOutput().connect( this.analyser );
  36927. }
  36928. /**
  36929. * Returns an array with frequency data of the audio.
  36930. *
  36931. * Each item in the array represents the decibel value for a specific frequency.
  36932. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  36933. * For example, for 48000 sample rate, the last item of the array will represent
  36934. * the decibel value for 24000 Hz.
  36935. *
  36936. * @return {Uint8Array} The frequency data.
  36937. */
  36938. getFrequencyData() {
  36939. this.analyser.getByteFrequencyData( this.data );
  36940. return this.data;
  36941. }
  36942. /**
  36943. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  36944. *
  36945. * @return {number} The average frequency.
  36946. */
  36947. getAverageFrequency() {
  36948. let value = 0;
  36949. const data = this.getFrequencyData();
  36950. for ( let i = 0; i < data.length; i ++ ) {
  36951. value += data[ i ];
  36952. }
  36953. return value / data.length;
  36954. }
  36955. }
  36956. /**
  36957. * Buffered scene graph property that allows weighted accumulation; used internally.
  36958. */
  36959. class PropertyMixer {
  36960. /**
  36961. * Constructs a new property mixer.
  36962. *
  36963. * @param {PropertyBinding} binding - The property binding.
  36964. * @param {string} typeName - The keyframe track type name.
  36965. * @param {number} valueSize - The keyframe track value size.
  36966. */
  36967. constructor( binding, typeName, valueSize ) {
  36968. /**
  36969. * The property binding.
  36970. *
  36971. * @type {PropertyBinding}
  36972. */
  36973. this.binding = binding;
  36974. /**
  36975. * The keyframe track value size.
  36976. *
  36977. * @type {number}
  36978. */
  36979. this.valueSize = valueSize;
  36980. let mixFunction,
  36981. mixFunctionAdditive,
  36982. setIdentity;
  36983. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  36984. //
  36985. // interpolators can use .buffer as their .result
  36986. // the data then goes to 'incoming'
  36987. //
  36988. // 'accu0' and 'accu1' are used frame-interleaved for
  36989. // the cumulative result and are compared to detect
  36990. // changes
  36991. //
  36992. // 'orig' stores the original state of the property
  36993. //
  36994. // 'add' is used for additive cumulative results
  36995. //
  36996. // 'work' is optional and is only present for quaternion types. It is used
  36997. // to store intermediate quaternion multiplication results
  36998. switch ( typeName ) {
  36999. case 'quaternion':
  37000. mixFunction = this._slerp;
  37001. mixFunctionAdditive = this._slerpAdditive;
  37002. setIdentity = this._setAdditiveIdentityQuaternion;
  37003. this.buffer = new Float64Array( valueSize * 6 );
  37004. this._workIndex = 5;
  37005. break;
  37006. case 'string':
  37007. case 'bool':
  37008. mixFunction = this._select;
  37009. // Use the regular mix function and for additive on these types,
  37010. // additive is not relevant for non-numeric types
  37011. mixFunctionAdditive = this._select;
  37012. setIdentity = this._setAdditiveIdentityOther;
  37013. this.buffer = new Array( valueSize * 5 );
  37014. break;
  37015. default:
  37016. mixFunction = this._lerp;
  37017. mixFunctionAdditive = this._lerpAdditive;
  37018. setIdentity = this._setAdditiveIdentityNumeric;
  37019. this.buffer = new Float64Array( valueSize * 5 );
  37020. }
  37021. this._mixBufferRegion = mixFunction;
  37022. this._mixBufferRegionAdditive = mixFunctionAdditive;
  37023. this._setIdentity = setIdentity;
  37024. this._origIndex = 3;
  37025. this._addIndex = 4;
  37026. /**
  37027. * TODO
  37028. *
  37029. * @type {number}
  37030. * @default 0
  37031. */
  37032. this.cumulativeWeight = 0;
  37033. /**
  37034. * TODO
  37035. *
  37036. * @type {number}
  37037. * @default 0
  37038. */
  37039. this.cumulativeWeightAdditive = 0;
  37040. /**
  37041. * TODO
  37042. *
  37043. * @type {number}
  37044. * @default 0
  37045. */
  37046. this.useCount = 0;
  37047. /**
  37048. * TODO
  37049. *
  37050. * @type {number}
  37051. * @default 0
  37052. */
  37053. this.referenceCount = 0;
  37054. }
  37055. /**
  37056. * Accumulates data in the `incoming` region into `accu<i>`.
  37057. *
  37058. * @param {number} accuIndex - The accumulation index.
  37059. * @param {number} weight - The weight.
  37060. */
  37061. accumulate( accuIndex, weight ) {
  37062. // note: happily accumulating nothing when weight = 0, the caller knows
  37063. // the weight and shouldn't have made the call in the first place
  37064. const buffer = this.buffer,
  37065. stride = this.valueSize,
  37066. offset = accuIndex * stride + stride;
  37067. let currentWeight = this.cumulativeWeight;
  37068. if ( currentWeight === 0 ) {
  37069. // accuN := incoming * weight
  37070. for ( let i = 0; i !== stride; ++ i ) {
  37071. buffer[ offset + i ] = buffer[ i ];
  37072. }
  37073. currentWeight = weight;
  37074. } else {
  37075. // accuN := accuN + incoming * weight
  37076. currentWeight += weight;
  37077. const mix = weight / currentWeight;
  37078. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  37079. }
  37080. this.cumulativeWeight = currentWeight;
  37081. }
  37082. /**
  37083. * Accumulates data in the `incoming` region into `add`.
  37084. *
  37085. * @param {number} weight - The weight.
  37086. */
  37087. accumulateAdditive( weight ) {
  37088. const buffer = this.buffer,
  37089. stride = this.valueSize,
  37090. offset = stride * this._addIndex;
  37091. if ( this.cumulativeWeightAdditive === 0 ) {
  37092. // add = identity
  37093. this._setIdentity();
  37094. }
  37095. // add := add + incoming * weight
  37096. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  37097. this.cumulativeWeightAdditive += weight;
  37098. }
  37099. /**
  37100. * Applies the state of `accu<i>` to the binding when accus differ.
  37101. *
  37102. * @param {number} accuIndex - The accumulation index.
  37103. */
  37104. apply( accuIndex ) {
  37105. const stride = this.valueSize,
  37106. buffer = this.buffer,
  37107. offset = accuIndex * stride + stride,
  37108. weight = this.cumulativeWeight,
  37109. weightAdditive = this.cumulativeWeightAdditive,
  37110. binding = this.binding;
  37111. this.cumulativeWeight = 0;
  37112. this.cumulativeWeightAdditive = 0;
  37113. if ( weight < 1 ) {
  37114. // accuN := accuN + original * ( 1 - cumulativeWeight )
  37115. const originalValueOffset = stride * this._origIndex;
  37116. this._mixBufferRegion(
  37117. buffer, offset, originalValueOffset, 1 - weight, stride );
  37118. }
  37119. if ( weightAdditive > 0 ) {
  37120. // accuN := accuN + additive accuN
  37121. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  37122. }
  37123. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  37124. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  37125. // value has changed -> update scene graph
  37126. binding.setValue( buffer, offset );
  37127. break;
  37128. }
  37129. }
  37130. }
  37131. /**
  37132. * Remembers the state of the bound property and copy it to both accus.
  37133. */
  37134. saveOriginalState() {
  37135. const binding = this.binding;
  37136. const buffer = this.buffer,
  37137. stride = this.valueSize,
  37138. originalValueOffset = stride * this._origIndex;
  37139. binding.getValue( buffer, originalValueOffset );
  37140. // accu[0..1] := orig -- initially detect changes against the original
  37141. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  37142. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  37143. }
  37144. // Add to identity for additive
  37145. this._setIdentity();
  37146. this.cumulativeWeight = 0;
  37147. this.cumulativeWeightAdditive = 0;
  37148. }
  37149. /**
  37150. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  37151. */
  37152. restoreOriginalState() {
  37153. const originalValueOffset = this.valueSize * 3;
  37154. this.binding.setValue( this.buffer, originalValueOffset );
  37155. }
  37156. // internals
  37157. _setAdditiveIdentityNumeric() {
  37158. const startIndex = this._addIndex * this.valueSize;
  37159. const endIndex = startIndex + this.valueSize;
  37160. for ( let i = startIndex; i < endIndex; i ++ ) {
  37161. this.buffer[ i ] = 0;
  37162. }
  37163. }
  37164. _setAdditiveIdentityQuaternion() {
  37165. this._setAdditiveIdentityNumeric();
  37166. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  37167. }
  37168. _setAdditiveIdentityOther() {
  37169. const startIndex = this._origIndex * this.valueSize;
  37170. const targetIndex = this._addIndex * this.valueSize;
  37171. for ( let i = 0; i < this.valueSize; i ++ ) {
  37172. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  37173. }
  37174. }
  37175. // mix functions
  37176. _select( buffer, dstOffset, srcOffset, t, stride ) {
  37177. if ( t >= 0.5 ) {
  37178. for ( let i = 0; i !== stride; ++ i ) {
  37179. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  37180. }
  37181. }
  37182. }
  37183. _slerp( buffer, dstOffset, srcOffset, t ) {
  37184. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  37185. }
  37186. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37187. const workOffset = this._workIndex * stride;
  37188. // Store result in intermediate buffer offset
  37189. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  37190. // Slerp to the intermediate result
  37191. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  37192. }
  37193. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  37194. const s = 1 - t;
  37195. for ( let i = 0; i !== stride; ++ i ) {
  37196. const j = dstOffset + i;
  37197. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  37198. }
  37199. }
  37200. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37201. for ( let i = 0; i !== stride; ++ i ) {
  37202. const j = dstOffset + i;
  37203. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  37204. }
  37205. }
  37206. }
  37207. // Characters [].:/ are reserved for track binding syntax.
  37208. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  37209. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  37210. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  37211. // only latin characters, and the unicode \p{L} is not yet supported. So
  37212. // instead, we exclude reserved characters and match everything else.
  37213. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  37214. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  37215. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  37216. // be matched to parse the rest of the track name.
  37217. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  37218. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  37219. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  37220. // Object on target node, and accessor. May not contain reserved
  37221. // characters. Accessor may contain any character except closing bracket.
  37222. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  37223. // Property and accessor. May not contain reserved characters. Accessor may
  37224. // contain any non-bracket characters.
  37225. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  37226. const _trackRe = new RegExp( ''
  37227. + '^'
  37228. + _directoryRe
  37229. + _nodeRe
  37230. + _objectRe
  37231. + _propertyRe
  37232. + '$'
  37233. );
  37234. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  37235. class Composite {
  37236. constructor( targetGroup, path, optionalParsedPath ) {
  37237. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  37238. this._targetGroup = targetGroup;
  37239. this._bindings = targetGroup.subscribe_( path, parsedPath );
  37240. }
  37241. getValue( array, offset ) {
  37242. this.bind(); // bind all binding
  37243. const firstValidIndex = this._targetGroup.nCachedObjects_,
  37244. binding = this._bindings[ firstValidIndex ];
  37245. // and only call .getValue on the first
  37246. if ( binding !== undefined ) binding.getValue( array, offset );
  37247. }
  37248. setValue( array, offset ) {
  37249. const bindings = this._bindings;
  37250. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37251. bindings[ i ].setValue( array, offset );
  37252. }
  37253. }
  37254. bind() {
  37255. const bindings = this._bindings;
  37256. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37257. bindings[ i ].bind();
  37258. }
  37259. }
  37260. unbind() {
  37261. const bindings = this._bindings;
  37262. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37263. bindings[ i ].unbind();
  37264. }
  37265. }
  37266. }
  37267. // Note: This class uses a State pattern on a per-method basis:
  37268. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  37269. // prototype version of these methods with one that represents
  37270. // the bound state. When the property is not found, the methods
  37271. // become no-ops.
  37272. /**
  37273. * This holds a reference to a real property in the scene graph; used internally.
  37274. */
  37275. class PropertyBinding {
  37276. /**
  37277. * Constructs a new property binding.
  37278. *
  37279. * @param {Object} rootNode - The root node.
  37280. * @param {string} path - The path.
  37281. * @param {?Object} [parsedPath] - The parsed path.
  37282. */
  37283. constructor( rootNode, path, parsedPath ) {
  37284. /**
  37285. * The object path to the animated property.
  37286. *
  37287. * @type {string}
  37288. */
  37289. this.path = path;
  37290. /**
  37291. * An object holding information about the path.
  37292. *
  37293. * @type {Object}
  37294. */
  37295. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  37296. /**
  37297. * The object owns the animated property.
  37298. *
  37299. * @type {?Object}
  37300. */
  37301. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  37302. /**
  37303. * The root node.
  37304. *
  37305. * @type {Object3D|Skeleton}
  37306. */
  37307. this.rootNode = rootNode;
  37308. // initial state of these methods that calls 'bind'
  37309. this.getValue = this._getValue_unbound;
  37310. this.setValue = this._setValue_unbound;
  37311. }
  37312. /**
  37313. * Factory method for creating a property binding from the given parameters.
  37314. *
  37315. * @static
  37316. * @param {Object} root - The root node.
  37317. * @param {string} path - The path.
  37318. * @param {?Object} [parsedPath] - The parsed path.
  37319. * @return {PropertyBinding|Composite} The created property binding or composite.
  37320. */
  37321. static create( root, path, parsedPath ) {
  37322. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  37323. return new PropertyBinding( root, path, parsedPath );
  37324. } else {
  37325. return new PropertyBinding.Composite( root, path, parsedPath );
  37326. }
  37327. }
  37328. /**
  37329. * Replaces spaces with underscores and removes unsupported characters from
  37330. * node names, to ensure compatibility with parseTrackName().
  37331. *
  37332. * @param {string} name - Node name to be sanitized.
  37333. * @return {string} The sanitized node name.
  37334. */
  37335. static sanitizeNodeName( name ) {
  37336. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  37337. }
  37338. /**
  37339. * Parses the given track name (an object path to an animated property) and
  37340. * returns an object with information about the path. Matches strings in the following forms:
  37341. *
  37342. * - nodeName.property
  37343. * - nodeName.property[accessor]
  37344. * - nodeName.material.property[accessor]
  37345. * - uuid.property[accessor]
  37346. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  37347. * - parentName/nodeName.property
  37348. * - parentName/parentName/nodeName.property[index]
  37349. * - .bone[Armature.DEF_cog].position
  37350. * - scene:helium_balloon_model:helium_balloon_model.position
  37351. *
  37352. * @static
  37353. * @param {string} trackName - The track name to parse.
  37354. * @return {Object} The parsed track name as an object.
  37355. */
  37356. static parseTrackName( trackName ) {
  37357. const matches = _trackRe.exec( trackName );
  37358. if ( matches === null ) {
  37359. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  37360. }
  37361. const results = {
  37362. // directoryName: matches[ 1 ], // (tschw) currently unused
  37363. nodeName: matches[ 2 ],
  37364. objectName: matches[ 3 ],
  37365. objectIndex: matches[ 4 ],
  37366. propertyName: matches[ 5 ], // required
  37367. propertyIndex: matches[ 6 ]
  37368. };
  37369. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  37370. if ( lastDot !== undefined && lastDot !== -1 ) {
  37371. const objectName = results.nodeName.substring( lastDot + 1 );
  37372. // Object names must be checked against an allowlist. Otherwise, there
  37373. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  37374. // 'bar' could be the objectName, or part of a nodeName (which can
  37375. // include '.' characters).
  37376. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  37377. results.nodeName = results.nodeName.substring( 0, lastDot );
  37378. results.objectName = objectName;
  37379. }
  37380. }
  37381. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  37382. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  37383. }
  37384. return results;
  37385. }
  37386. /**
  37387. * Searches for a node in the hierarchy of the given root object by the given
  37388. * node name.
  37389. *
  37390. * @static
  37391. * @param {Object} root - The root object.
  37392. * @param {string|number} nodeName - The name of the node.
  37393. * @return {?Object} The found node. Returns `null` if no object was found.
  37394. */
  37395. static findNode( root, nodeName ) {
  37396. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  37397. return root;
  37398. }
  37399. // search into skeleton bones.
  37400. if ( root.skeleton ) {
  37401. const bone = root.skeleton.getBoneByName( nodeName );
  37402. if ( bone !== undefined ) {
  37403. return bone;
  37404. }
  37405. }
  37406. // search into node subtree.
  37407. if ( root.children ) {
  37408. const searchNodeSubtree = function ( children ) {
  37409. for ( let i = 0; i < children.length; i ++ ) {
  37410. const childNode = children[ i ];
  37411. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  37412. return childNode;
  37413. }
  37414. const result = searchNodeSubtree( childNode.children );
  37415. if ( result ) return result;
  37416. }
  37417. return null;
  37418. };
  37419. const subTreeNode = searchNodeSubtree( root.children );
  37420. if ( subTreeNode ) {
  37421. return subTreeNode;
  37422. }
  37423. }
  37424. return null;
  37425. }
  37426. // these are used to "bind" a nonexistent property
  37427. _getValue_unavailable() {}
  37428. _setValue_unavailable() {}
  37429. // Getters
  37430. _getValue_direct( buffer, offset ) {
  37431. buffer[ offset ] = this.targetObject[ this.propertyName ];
  37432. }
  37433. _getValue_array( buffer, offset ) {
  37434. const source = this.resolvedProperty;
  37435. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  37436. buffer[ offset ++ ] = source[ i ];
  37437. }
  37438. }
  37439. _getValue_arrayElement( buffer, offset ) {
  37440. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  37441. }
  37442. _getValue_toArray( buffer, offset ) {
  37443. this.resolvedProperty.toArray( buffer, offset );
  37444. }
  37445. // Direct
  37446. _setValue_direct( buffer, offset ) {
  37447. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37448. }
  37449. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  37450. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37451. this.targetObject.needsUpdate = true;
  37452. }
  37453. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37454. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37455. this.targetObject.matrixWorldNeedsUpdate = true;
  37456. }
  37457. // EntireArray
  37458. _setValue_array( buffer, offset ) {
  37459. const dest = this.resolvedProperty;
  37460. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37461. dest[ i ] = buffer[ offset ++ ];
  37462. }
  37463. }
  37464. _setValue_array_setNeedsUpdate( buffer, offset ) {
  37465. const dest = this.resolvedProperty;
  37466. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37467. dest[ i ] = buffer[ offset ++ ];
  37468. }
  37469. this.targetObject.needsUpdate = true;
  37470. }
  37471. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37472. const dest = this.resolvedProperty;
  37473. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37474. dest[ i ] = buffer[ offset ++ ];
  37475. }
  37476. this.targetObject.matrixWorldNeedsUpdate = true;
  37477. }
  37478. // ArrayElement
  37479. _setValue_arrayElement( buffer, offset ) {
  37480. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37481. }
  37482. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  37483. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37484. this.targetObject.needsUpdate = true;
  37485. }
  37486. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37487. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37488. this.targetObject.matrixWorldNeedsUpdate = true;
  37489. }
  37490. // HasToFromArray
  37491. _setValue_fromArray( buffer, offset ) {
  37492. this.resolvedProperty.fromArray( buffer, offset );
  37493. }
  37494. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  37495. this.resolvedProperty.fromArray( buffer, offset );
  37496. this.targetObject.needsUpdate = true;
  37497. }
  37498. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37499. this.resolvedProperty.fromArray( buffer, offset );
  37500. this.targetObject.matrixWorldNeedsUpdate = true;
  37501. }
  37502. _getValue_unbound( targetArray, offset ) {
  37503. this.bind();
  37504. this.getValue( targetArray, offset );
  37505. }
  37506. _setValue_unbound( sourceArray, offset ) {
  37507. this.bind();
  37508. this.setValue( sourceArray, offset );
  37509. }
  37510. /**
  37511. * Creates a getter / setter pair for the property tracked by this binding.
  37512. */
  37513. bind() {
  37514. let targetObject = this.node;
  37515. const parsedPath = this.parsedPath;
  37516. const objectName = parsedPath.objectName;
  37517. const propertyName = parsedPath.propertyName;
  37518. let propertyIndex = parsedPath.propertyIndex;
  37519. if ( ! targetObject ) {
  37520. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  37521. this.node = targetObject;
  37522. }
  37523. // set fail state so we can just 'return' on error
  37524. this.getValue = this._getValue_unavailable;
  37525. this.setValue = this._setValue_unavailable;
  37526. // ensure there is a value node
  37527. if ( ! targetObject ) {
  37528. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  37529. return;
  37530. }
  37531. if ( objectName ) {
  37532. let objectIndex = parsedPath.objectIndex;
  37533. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  37534. switch ( objectName ) {
  37535. case 'materials':
  37536. if ( ! targetObject.material ) {
  37537. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  37538. return;
  37539. }
  37540. if ( ! targetObject.material.materials ) {
  37541. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  37542. return;
  37543. }
  37544. targetObject = targetObject.material.materials;
  37545. break;
  37546. case 'bones':
  37547. if ( ! targetObject.skeleton ) {
  37548. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  37549. return;
  37550. }
  37551. // potential future optimization: skip this if propertyIndex is already an integer
  37552. // and convert the integer string to a true integer.
  37553. targetObject = targetObject.skeleton.bones;
  37554. // support resolving morphTarget names into indices.
  37555. for ( let i = 0; i < targetObject.length; i ++ ) {
  37556. if ( targetObject[ i ].name === objectIndex ) {
  37557. objectIndex = i;
  37558. break;
  37559. }
  37560. }
  37561. break;
  37562. case 'map':
  37563. if ( 'map' in targetObject ) {
  37564. targetObject = targetObject.map;
  37565. break;
  37566. }
  37567. if ( ! targetObject.material ) {
  37568. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  37569. return;
  37570. }
  37571. if ( ! targetObject.material.map ) {
  37572. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  37573. return;
  37574. }
  37575. targetObject = targetObject.material.map;
  37576. break;
  37577. default:
  37578. if ( targetObject[ objectName ] === undefined ) {
  37579. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  37580. return;
  37581. }
  37582. targetObject = targetObject[ objectName ];
  37583. }
  37584. if ( objectIndex !== undefined ) {
  37585. if ( targetObject[ objectIndex ] === undefined ) {
  37586. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  37587. return;
  37588. }
  37589. targetObject = targetObject[ objectIndex ];
  37590. }
  37591. }
  37592. // resolve property
  37593. const nodeProperty = targetObject[ propertyName ];
  37594. if ( nodeProperty === undefined ) {
  37595. const nodeName = parsedPath.nodeName;
  37596. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  37597. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  37598. return;
  37599. }
  37600. // determine versioning scheme
  37601. let versioning = this.Versioning.None;
  37602. this.targetObject = targetObject;
  37603. if ( targetObject.isMaterial === true ) {
  37604. versioning = this.Versioning.NeedsUpdate;
  37605. } else if ( targetObject.isObject3D === true ) {
  37606. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  37607. }
  37608. // determine how the property gets bound
  37609. let bindingType = this.BindingType.Direct;
  37610. if ( propertyIndex !== undefined ) {
  37611. // access a sub element of the property array (only primitives are supported right now)
  37612. if ( propertyName === 'morphTargetInfluences' ) {
  37613. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  37614. // support resolving morphTarget names into indices.
  37615. if ( ! targetObject.geometry ) {
  37616. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  37617. return;
  37618. }
  37619. if ( ! targetObject.geometry.morphAttributes ) {
  37620. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  37621. return;
  37622. }
  37623. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  37624. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  37625. }
  37626. }
  37627. bindingType = this.BindingType.ArrayElement;
  37628. this.resolvedProperty = nodeProperty;
  37629. this.propertyIndex = propertyIndex;
  37630. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  37631. // must use copy for Object3D.Euler/Quaternion
  37632. bindingType = this.BindingType.HasFromToArray;
  37633. this.resolvedProperty = nodeProperty;
  37634. } else if ( Array.isArray( nodeProperty ) ) {
  37635. bindingType = this.BindingType.EntireArray;
  37636. this.resolvedProperty = nodeProperty;
  37637. } else {
  37638. this.propertyName = propertyName;
  37639. }
  37640. // select getter / setter
  37641. this.getValue = this.GetterByBindingType[ bindingType ];
  37642. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  37643. }
  37644. /**
  37645. * Unbinds the property.
  37646. */
  37647. unbind() {
  37648. this.node = null;
  37649. // back to the prototype version of getValue / setValue
  37650. // note: avoiding to mutate the shape of 'this' via 'delete'
  37651. this.getValue = this._getValue_unbound;
  37652. this.setValue = this._setValue_unbound;
  37653. }
  37654. }
  37655. PropertyBinding.Composite = Composite;
  37656. PropertyBinding.prototype.BindingType = {
  37657. Direct: 0,
  37658. EntireArray: 1,
  37659. ArrayElement: 2,
  37660. HasFromToArray: 3
  37661. };
  37662. PropertyBinding.prototype.Versioning = {
  37663. None: 0,
  37664. NeedsUpdate: 1,
  37665. MatrixWorldNeedsUpdate: 2
  37666. };
  37667. PropertyBinding.prototype.GetterByBindingType = [
  37668. PropertyBinding.prototype._getValue_direct,
  37669. PropertyBinding.prototype._getValue_array,
  37670. PropertyBinding.prototype._getValue_arrayElement,
  37671. PropertyBinding.prototype._getValue_toArray,
  37672. ];
  37673. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  37674. [
  37675. // Direct
  37676. PropertyBinding.prototype._setValue_direct,
  37677. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  37678. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  37679. ], [
  37680. // EntireArray
  37681. PropertyBinding.prototype._setValue_array,
  37682. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  37683. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  37684. ], [
  37685. // ArrayElement
  37686. PropertyBinding.prototype._setValue_arrayElement,
  37687. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  37688. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  37689. ], [
  37690. // HasToFromArray
  37691. PropertyBinding.prototype._setValue_fromArray,
  37692. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  37693. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  37694. ]
  37695. ];
  37696. /**
  37697. * A group of objects that receives a shared animation state.
  37698. *
  37699. * Usage:
  37700. *
  37701. * - Add objects you would otherwise pass as 'root' to the
  37702. * constructor or the .clipAction method of AnimationMixer.
  37703. * - Instead pass this object as 'root'.
  37704. * - You can also add and remove objects later when the mixer is running.
  37705. *
  37706. * Note:
  37707. *
  37708. * - Objects of this class appear as one object to the mixer,
  37709. * so cache control of the individual objects must be done on the group.
  37710. *
  37711. * Limitation:
  37712. *
  37713. * - The animated properties must be compatible among the all objects in the group.
  37714. * - A single property can either be controlled through a target group or directly, but not both.
  37715. */
  37716. class AnimationObjectGroup {
  37717. /**
  37718. * Constructs a new animation group.
  37719. *
  37720. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  37721. */
  37722. constructor() {
  37723. /**
  37724. * This flag can be used for type testing.
  37725. *
  37726. * @type {boolean}
  37727. * @readonly
  37728. * @default true
  37729. */
  37730. this.isAnimationObjectGroup = true;
  37731. /**
  37732. * The UUID of the 3D object.
  37733. *
  37734. * @type {string}
  37735. * @readonly
  37736. */
  37737. this.uuid = generateUUID();
  37738. // cached objects followed by the active ones
  37739. this._objects = Array.prototype.slice.call( arguments );
  37740. this.nCachedObjects_ = 0; // threshold
  37741. // note: read by PropertyBinding.Composite
  37742. const indices = {};
  37743. this._indicesByUUID = indices; // for bookkeeping
  37744. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37745. indices[ arguments[ i ].uuid ] = i;
  37746. }
  37747. this._paths = []; // inside: string
  37748. this._parsedPaths = []; // inside: { we don't care, here }
  37749. this._bindings = []; // inside: Array< PropertyBinding >
  37750. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  37751. const scope = this;
  37752. this.stats = {
  37753. objects: {
  37754. get total() {
  37755. return scope._objects.length;
  37756. },
  37757. get inUse() {
  37758. return this.total - scope.nCachedObjects_;
  37759. }
  37760. },
  37761. get bindingsPerObject() {
  37762. return scope._bindings.length;
  37763. }
  37764. };
  37765. }
  37766. /**
  37767. * Adds an arbitrary number of objects to this animation group.
  37768. *
  37769. * @param {...Object3D} arguments - The 3D objects to add.
  37770. */
  37771. add() {
  37772. const objects = this._objects,
  37773. indicesByUUID = this._indicesByUUID,
  37774. paths = this._paths,
  37775. parsedPaths = this._parsedPaths,
  37776. bindings = this._bindings,
  37777. nBindings = bindings.length;
  37778. let knownObject = undefined,
  37779. nObjects = objects.length,
  37780. nCachedObjects = this.nCachedObjects_;
  37781. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37782. const object = arguments[ i ],
  37783. uuid = object.uuid;
  37784. let index = indicesByUUID[ uuid ];
  37785. if ( index === undefined ) {
  37786. // unknown object -> add it to the ACTIVE region
  37787. index = nObjects ++;
  37788. indicesByUUID[ uuid ] = index;
  37789. objects.push( object );
  37790. // accounting is done, now do the same for all bindings
  37791. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37792. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  37793. }
  37794. } else if ( index < nCachedObjects ) {
  37795. knownObject = objects[ index ];
  37796. // move existing object to the ACTIVE region
  37797. const firstActiveIndex = -- nCachedObjects,
  37798. lastCachedObject = objects[ firstActiveIndex ];
  37799. indicesByUUID[ lastCachedObject.uuid ] = index;
  37800. objects[ index ] = lastCachedObject;
  37801. indicesByUUID[ uuid ] = firstActiveIndex;
  37802. objects[ firstActiveIndex ] = object;
  37803. // accounting is done, now do the same for all bindings
  37804. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37805. const bindingsForPath = bindings[ j ],
  37806. lastCached = bindingsForPath[ firstActiveIndex ];
  37807. let binding = bindingsForPath[ index ];
  37808. bindingsForPath[ index ] = lastCached;
  37809. if ( binding === undefined ) {
  37810. // since we do not bother to create new bindings
  37811. // for objects that are cached, the binding may
  37812. // or may not exist
  37813. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  37814. }
  37815. bindingsForPath[ firstActiveIndex ] = binding;
  37816. }
  37817. } else if ( objects[ index ] !== knownObject ) {
  37818. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  37819. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  37820. } // else the object is already where we want it to be
  37821. } // for arguments
  37822. this.nCachedObjects_ = nCachedObjects;
  37823. }
  37824. /**
  37825. * Removes an arbitrary number of objects to this animation group
  37826. *
  37827. * @param {...Object3D} arguments - The 3D objects to remove.
  37828. */
  37829. remove() {
  37830. const objects = this._objects,
  37831. indicesByUUID = this._indicesByUUID,
  37832. bindings = this._bindings,
  37833. nBindings = bindings.length;
  37834. let nCachedObjects = this.nCachedObjects_;
  37835. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37836. const object = arguments[ i ],
  37837. uuid = object.uuid,
  37838. index = indicesByUUID[ uuid ];
  37839. if ( index !== undefined && index >= nCachedObjects ) {
  37840. // move existing object into the CACHED region
  37841. const lastCachedIndex = nCachedObjects ++,
  37842. firstActiveObject = objects[ lastCachedIndex ];
  37843. indicesByUUID[ firstActiveObject.uuid ] = index;
  37844. objects[ index ] = firstActiveObject;
  37845. indicesByUUID[ uuid ] = lastCachedIndex;
  37846. objects[ lastCachedIndex ] = object;
  37847. // accounting is done, now do the same for all bindings
  37848. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37849. const bindingsForPath = bindings[ j ],
  37850. firstActive = bindingsForPath[ lastCachedIndex ],
  37851. binding = bindingsForPath[ index ];
  37852. bindingsForPath[ index ] = firstActive;
  37853. bindingsForPath[ lastCachedIndex ] = binding;
  37854. }
  37855. }
  37856. } // for arguments
  37857. this.nCachedObjects_ = nCachedObjects;
  37858. }
  37859. /**
  37860. * Deallocates all memory resources for the passed 3D objects of this animation group.
  37861. *
  37862. * @param {...Object3D} arguments - The 3D objects to uncache.
  37863. */
  37864. uncache() {
  37865. const objects = this._objects,
  37866. indicesByUUID = this._indicesByUUID,
  37867. bindings = this._bindings,
  37868. nBindings = bindings.length;
  37869. let nCachedObjects = this.nCachedObjects_,
  37870. nObjects = objects.length;
  37871. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37872. const object = arguments[ i ],
  37873. uuid = object.uuid,
  37874. index = indicesByUUID[ uuid ];
  37875. if ( index !== undefined ) {
  37876. delete indicesByUUID[ uuid ];
  37877. if ( index < nCachedObjects ) {
  37878. // object is cached, shrink the CACHED region
  37879. const firstActiveIndex = -- nCachedObjects,
  37880. lastCachedObject = objects[ firstActiveIndex ],
  37881. lastIndex = -- nObjects,
  37882. lastObject = objects[ lastIndex ];
  37883. // last cached object takes this object's place
  37884. indicesByUUID[ lastCachedObject.uuid ] = index;
  37885. objects[ index ] = lastCachedObject;
  37886. // last object goes to the activated slot and pop
  37887. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  37888. objects[ firstActiveIndex ] = lastObject;
  37889. objects.pop();
  37890. // accounting is done, now do the same for all bindings
  37891. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37892. const bindingsForPath = bindings[ j ],
  37893. lastCached = bindingsForPath[ firstActiveIndex ],
  37894. last = bindingsForPath[ lastIndex ];
  37895. bindingsForPath[ index ] = lastCached;
  37896. bindingsForPath[ firstActiveIndex ] = last;
  37897. bindingsForPath.pop();
  37898. }
  37899. } else {
  37900. // object is active, just swap with the last and pop
  37901. const lastIndex = -- nObjects,
  37902. lastObject = objects[ lastIndex ];
  37903. if ( lastIndex > 0 ) {
  37904. indicesByUUID[ lastObject.uuid ] = index;
  37905. }
  37906. objects[ index ] = lastObject;
  37907. objects.pop();
  37908. // accounting is done, now do the same for all bindings
  37909. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37910. const bindingsForPath = bindings[ j ];
  37911. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  37912. bindingsForPath.pop();
  37913. }
  37914. } // cached or active
  37915. } // if object is known
  37916. } // for arguments
  37917. this.nCachedObjects_ = nCachedObjects;
  37918. }
  37919. // Internal interface used by befriended PropertyBinding.Composite:
  37920. subscribe_( path, parsedPath ) {
  37921. // returns an array of bindings for the given path that is changed
  37922. // according to the contained objects in the group
  37923. const indicesByPath = this._bindingsIndicesByPath;
  37924. let index = indicesByPath[ path ];
  37925. const bindings = this._bindings;
  37926. if ( index !== undefined ) return bindings[ index ];
  37927. const paths = this._paths,
  37928. parsedPaths = this._parsedPaths,
  37929. objects = this._objects,
  37930. nObjects = objects.length,
  37931. nCachedObjects = this.nCachedObjects_,
  37932. bindingsForPath = new Array( nObjects );
  37933. index = bindings.length;
  37934. indicesByPath[ path ] = index;
  37935. paths.push( path );
  37936. parsedPaths.push( parsedPath );
  37937. bindings.push( bindingsForPath );
  37938. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  37939. const object = objects[ i ];
  37940. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  37941. }
  37942. return bindingsForPath;
  37943. }
  37944. unsubscribe_( path ) {
  37945. // tells the group to forget about a property path and no longer
  37946. // update the array previously obtained with 'subscribe_'
  37947. const indicesByPath = this._bindingsIndicesByPath,
  37948. index = indicesByPath[ path ];
  37949. if ( index !== undefined ) {
  37950. const paths = this._paths,
  37951. parsedPaths = this._parsedPaths,
  37952. bindings = this._bindings,
  37953. lastBindingsIndex = bindings.length - 1,
  37954. lastBindings = bindings[ lastBindingsIndex ],
  37955. lastBindingsPath = path[ lastBindingsIndex ];
  37956. indicesByPath[ lastBindingsPath ] = index;
  37957. bindings[ index ] = lastBindings;
  37958. bindings.pop();
  37959. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  37960. parsedPaths.pop();
  37961. paths[ index ] = paths[ lastBindingsIndex ];
  37962. paths.pop();
  37963. }
  37964. }
  37965. }
  37966. /**
  37967. * An instance of `AnimationAction` schedules the playback of an animation which is
  37968. * stored in {@link AnimationClip}.
  37969. */
  37970. class AnimationAction {
  37971. /**
  37972. * Constructs a new animation action.
  37973. *
  37974. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  37975. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  37976. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  37977. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  37978. */
  37979. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  37980. this._mixer = mixer;
  37981. this._clip = clip;
  37982. this._localRoot = localRoot;
  37983. /**
  37984. * Defines how the animation is blended/combined when two or more animations
  37985. * are simultaneously played.
  37986. *
  37987. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  37988. */
  37989. this.blendMode = blendMode;
  37990. const tracks = clip.tracks,
  37991. nTracks = tracks.length,
  37992. interpolants = new Array( nTracks );
  37993. const interpolantSettings = {
  37994. endingStart: ZeroCurvatureEnding,
  37995. endingEnd: ZeroCurvatureEnding
  37996. };
  37997. for ( let i = 0; i !== nTracks; ++ i ) {
  37998. const interpolant = tracks[ i ].createInterpolant( null );
  37999. interpolants[ i ] = interpolant;
  38000. interpolant.settings = interpolantSettings;
  38001. }
  38002. this._interpolantSettings = interpolantSettings;
  38003. this._interpolants = interpolants; // bound by the mixer
  38004. // inside: PropertyMixer (managed by the mixer)
  38005. this._propertyBindings = new Array( nTracks );
  38006. this._cacheIndex = null; // for the memory manager
  38007. this._byClipCacheIndex = null; // for the memory manager
  38008. this._timeScaleInterpolant = null;
  38009. this._weightInterpolant = null;
  38010. /**
  38011. * The loop mode, set via {@link AnimationAction#setLoop}.
  38012. *
  38013. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  38014. * @default LoopRepeat
  38015. */
  38016. this.loop = LoopRepeat;
  38017. this._loopCount = -1;
  38018. // global mixer time when the action is to be started
  38019. // it's set back to 'null' upon start of the action
  38020. this._startTime = null;
  38021. /**
  38022. * The local time of this action (in seconds, starting with `0`).
  38023. *
  38024. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  38025. * loop state).
  38026. *
  38027. * @type {number}
  38028. * @default Infinity
  38029. */
  38030. this.time = 0;
  38031. /**
  38032. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  38033. * animation to pause. Negative values cause the animation to play backwards.
  38034. *
  38035. * @type {number}
  38036. * @default 1
  38037. */
  38038. this.timeScale = 1;
  38039. this._effectiveTimeScale = 1;
  38040. /**
  38041. * The degree of influence of this action (in the interval `[0, 1]`). Values
  38042. * between `0` (no impact) and `1` (full impact) can be used to blend between
  38043. * several actions.
  38044. *
  38045. * @type {number}
  38046. * @default 1
  38047. */
  38048. this.weight = 1;
  38049. this._effectiveWeight = 1;
  38050. /**
  38051. * The number of repetitions of the performed clip over the course of this action.
  38052. * Can be set via {@link AnimationAction#setLoop}.
  38053. *
  38054. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  38055. * `THREE:LoopOnce`.
  38056. *
  38057. * @type {number}
  38058. * @default Infinity
  38059. */
  38060. this.repetitions = Infinity;
  38061. /**
  38062. * If set to `true`, the playback of the action is paused.
  38063. *
  38064. * @type {boolean}
  38065. * @default false
  38066. */
  38067. this.paused = false;
  38068. /**
  38069. * If set to `false`, the action is disabled so it has no impact.
  38070. *
  38071. * When the action is re-enabled, the animation continues from its current
  38072. * time (setting `enabled` to `false` doesn't reset the action).
  38073. *
  38074. * @type {boolean}
  38075. * @default true
  38076. */
  38077. this.enabled = true;
  38078. /**
  38079. * If set to true the animation will automatically be paused on its last frame.
  38080. *
  38081. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  38082. * to `false` when the last loop of the action has finished, so that this action has
  38083. * no further impact.
  38084. *
  38085. * Note: This member has no impact if the action is interrupted (it
  38086. * has only an effect if its last loop has really finished).
  38087. *
  38088. * @type {boolean}
  38089. * @default false
  38090. */
  38091. this.clampWhenFinished = false;
  38092. /**
  38093. * Enables smooth interpolation without separate clips for start, loop and end.
  38094. *
  38095. * @type {boolean}
  38096. * @default true
  38097. */
  38098. this.zeroSlopeAtStart = true;
  38099. /**
  38100. * Enables smooth interpolation without separate clips for start, loop and end.
  38101. *
  38102. * @type {boolean}
  38103. * @default true
  38104. */
  38105. this.zeroSlopeAtEnd = true;
  38106. }
  38107. /**
  38108. * Starts the playback of the animation.
  38109. *
  38110. * @return {AnimationAction} A reference to this animation action.
  38111. */
  38112. play() {
  38113. this._mixer._activateAction( this );
  38114. return this;
  38115. }
  38116. /**
  38117. * Stops the playback of the animation.
  38118. *
  38119. * @return {AnimationAction} A reference to this animation action.
  38120. */
  38121. stop() {
  38122. this._mixer._deactivateAction( this );
  38123. return this.reset();
  38124. }
  38125. /**
  38126. * Resets the playback of the animation.
  38127. *
  38128. * @return {AnimationAction} A reference to this animation action.
  38129. */
  38130. reset() {
  38131. this.paused = false;
  38132. this.enabled = true;
  38133. this.time = 0; // restart clip
  38134. this._loopCount = -1;// forget previous loops
  38135. this._startTime = null;// forget scheduling
  38136. return this.stopFading().stopWarping();
  38137. }
  38138. /**
  38139. * Returns `true` if the animation is running.
  38140. *
  38141. * @return {boolean} Whether the animation is running or not.
  38142. */
  38143. isRunning() {
  38144. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  38145. this._startTime === null && this._mixer._isActiveAction( this );
  38146. }
  38147. /**
  38148. * Returns `true` when {@link AnimationAction#play} has been called.
  38149. *
  38150. * @return {boolean} Whether the animation is scheduled or not.
  38151. */
  38152. isScheduled() {
  38153. return this._mixer._isActiveAction( this );
  38154. }
  38155. /**
  38156. * Defines the time when the animation should start.
  38157. *
  38158. * @param {number} time - The start time in seconds.
  38159. * @return {AnimationAction} A reference to this animation action.
  38160. */
  38161. startAt( time ) {
  38162. this._startTime = time;
  38163. return this;
  38164. }
  38165. /**
  38166. * Configures the loop settings for this action.
  38167. *
  38168. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  38169. * @param {number} repetitions - The number of repetitions.
  38170. * @return {AnimationAction} A reference to this animation action.
  38171. */
  38172. setLoop( mode, repetitions ) {
  38173. this.loop = mode;
  38174. this.repetitions = repetitions;
  38175. return this;
  38176. }
  38177. /**
  38178. * Sets the effective weight of this action.
  38179. *
  38180. * An action has no effect and thus an effective weight of zero when the
  38181. * action is disabled.
  38182. *
  38183. * @param {number} weight - The weight to set.
  38184. * @return {AnimationAction} A reference to this animation action.
  38185. */
  38186. setEffectiveWeight( weight ) {
  38187. this.weight = weight;
  38188. // note: same logic as when updated at runtime
  38189. this._effectiveWeight = this.enabled ? weight : 0;
  38190. return this.stopFading();
  38191. }
  38192. /**
  38193. * Returns the effective weight of this action.
  38194. *
  38195. * @return {number} The effective weight.
  38196. */
  38197. getEffectiveWeight() {
  38198. return this._effectiveWeight;
  38199. }
  38200. /**
  38201. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  38202. * within the passed time interval.
  38203. *
  38204. * @param {number} duration - The duration of the fade.
  38205. * @return {AnimationAction} A reference to this animation action.
  38206. */
  38207. fadeIn( duration ) {
  38208. return this._scheduleFading( duration, 0, 1 );
  38209. }
  38210. /**
  38211. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  38212. * within the passed time interval.
  38213. *
  38214. * @param {number} duration - The duration of the fade.
  38215. * @return {AnimationAction} A reference to this animation action.
  38216. */
  38217. fadeOut( duration ) {
  38218. return this._scheduleFading( duration, 1, 0 );
  38219. }
  38220. /**
  38221. * Causes this action to fade in and the given action to fade out,
  38222. * within the passed time interval.
  38223. *
  38224. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  38225. * @param {number} duration - The duration of the fade.
  38226. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38227. * @return {AnimationAction} A reference to this animation action.
  38228. */
  38229. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  38230. fadeOutAction.fadeOut( duration );
  38231. this.fadeIn( duration );
  38232. if ( warp === true ) {
  38233. const fadeInDuration = this._clip.duration,
  38234. fadeOutDuration = fadeOutAction._clip.duration,
  38235. startEndRatio = fadeOutDuration / fadeInDuration,
  38236. endStartRatio = fadeInDuration / fadeOutDuration;
  38237. fadeOutAction.warp( 1.0, startEndRatio, duration );
  38238. this.warp( endStartRatio, 1.0, duration );
  38239. }
  38240. return this;
  38241. }
  38242. /**
  38243. * Causes this action to fade out and the given action to fade in,
  38244. * within the passed time interval.
  38245. *
  38246. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  38247. * @param {number} duration - The duration of the fade.
  38248. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38249. * @return {AnimationAction} A reference to this animation action.
  38250. */
  38251. crossFadeTo( fadeInAction, duration, warp = false ) {
  38252. return fadeInAction.crossFadeFrom( this, duration, warp );
  38253. }
  38254. /**
  38255. * Stops any fading which is applied to this action.
  38256. *
  38257. * @return {AnimationAction} A reference to this animation action.
  38258. */
  38259. stopFading() {
  38260. const weightInterpolant = this._weightInterpolant;
  38261. if ( weightInterpolant !== null ) {
  38262. this._weightInterpolant = null;
  38263. this._mixer._takeBackControlInterpolant( weightInterpolant );
  38264. }
  38265. return this;
  38266. }
  38267. /**
  38268. * Sets the effective time scale of this action.
  38269. *
  38270. * An action has no effect and thus an effective time scale of zero when the
  38271. * action is paused.
  38272. *
  38273. * @param {number} timeScale - The time scale to set.
  38274. * @return {AnimationAction} A reference to this animation action.
  38275. */
  38276. setEffectiveTimeScale( timeScale ) {
  38277. this.timeScale = timeScale;
  38278. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  38279. return this.stopWarping();
  38280. }
  38281. /**
  38282. * Returns the effective time scale of this action.
  38283. *
  38284. * @return {number} The effective time scale.
  38285. */
  38286. getEffectiveTimeScale() {
  38287. return this._effectiveTimeScale;
  38288. }
  38289. /**
  38290. * Sets the duration for a single loop of this action.
  38291. *
  38292. * @param {number} duration - The duration to set.
  38293. * @return {AnimationAction} A reference to this animation action.
  38294. */
  38295. setDuration( duration ) {
  38296. this.timeScale = this._clip.duration / duration;
  38297. return this.stopWarping();
  38298. }
  38299. /**
  38300. * Synchronizes this action with the passed other action.
  38301. *
  38302. * @param {AnimationAction} action - The action to sync with.
  38303. * @return {AnimationAction} A reference to this animation action.
  38304. */
  38305. syncWith( action ) {
  38306. this.time = action.time;
  38307. this.timeScale = action.timeScale;
  38308. return this.stopWarping();
  38309. }
  38310. /**
  38311. * Decelerates this animation's speed to `0` within the passed time interval.
  38312. *
  38313. * @param {number} duration - The duration.
  38314. * @return {AnimationAction} A reference to this animation action.
  38315. */
  38316. halt( duration ) {
  38317. return this.warp( this._effectiveTimeScale, 0, duration );
  38318. }
  38319. /**
  38320. * Changes the playback speed, within the passed time interval, by modifying
  38321. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  38322. * `endTimeScale`.
  38323. *
  38324. * @param {number} startTimeScale - The start time scale.
  38325. * @param {number} endTimeScale - The end time scale.
  38326. * @param {number} duration - The duration.
  38327. * @return {AnimationAction} A reference to this animation action.
  38328. */
  38329. warp( startTimeScale, endTimeScale, duration ) {
  38330. const mixer = this._mixer,
  38331. now = mixer.time,
  38332. timeScale = this.timeScale;
  38333. let interpolant = this._timeScaleInterpolant;
  38334. if ( interpolant === null ) {
  38335. interpolant = mixer._lendControlInterpolant();
  38336. this._timeScaleInterpolant = interpolant;
  38337. }
  38338. const times = interpolant.parameterPositions,
  38339. values = interpolant.sampleValues;
  38340. times[ 0 ] = now;
  38341. times[ 1 ] = now + duration;
  38342. values[ 0 ] = startTimeScale / timeScale;
  38343. values[ 1 ] = endTimeScale / timeScale;
  38344. return this;
  38345. }
  38346. /**
  38347. * Stops any scheduled warping which is applied to this action.
  38348. *
  38349. * @return {AnimationAction} A reference to this animation action.
  38350. */
  38351. stopWarping() {
  38352. const timeScaleInterpolant = this._timeScaleInterpolant;
  38353. if ( timeScaleInterpolant !== null ) {
  38354. this._timeScaleInterpolant = null;
  38355. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  38356. }
  38357. return this;
  38358. }
  38359. /**
  38360. * Returns the animation mixer of this animation action.
  38361. *
  38362. * @return {AnimationMixer} The animation mixer.
  38363. */
  38364. getMixer() {
  38365. return this._mixer;
  38366. }
  38367. /**
  38368. * Returns the animation clip of this animation action.
  38369. *
  38370. * @return {AnimationClip} The animation clip.
  38371. */
  38372. getClip() {
  38373. return this._clip;
  38374. }
  38375. /**
  38376. * Returns the root object of this animation action.
  38377. *
  38378. * @return {Object3D} The root object.
  38379. */
  38380. getRoot() {
  38381. return this._localRoot || this._mixer._root;
  38382. }
  38383. // Interna
  38384. _update( time, deltaTime, timeDirection, accuIndex ) {
  38385. // called by the mixer
  38386. if ( ! this.enabled ) {
  38387. // call ._updateWeight() to update ._effectiveWeight
  38388. this._updateWeight( time );
  38389. return;
  38390. }
  38391. const startTime = this._startTime;
  38392. if ( startTime !== null ) {
  38393. // check for scheduled start of action
  38394. const timeRunning = ( time - startTime ) * timeDirection;
  38395. if ( timeRunning < 0 || timeDirection === 0 ) {
  38396. deltaTime = 0;
  38397. } else {
  38398. this._startTime = null; // unschedule
  38399. deltaTime = timeDirection * timeRunning;
  38400. }
  38401. }
  38402. // apply time scale and advance time
  38403. deltaTime *= this._updateTimeScale( time );
  38404. const clipTime = this._updateTime( deltaTime );
  38405. // note: _updateTime may disable the action resulting in
  38406. // an effective weight of 0
  38407. const weight = this._updateWeight( time );
  38408. if ( weight > 0 ) {
  38409. const interpolants = this._interpolants;
  38410. const propertyMixers = this._propertyBindings;
  38411. switch ( this.blendMode ) {
  38412. case AdditiveAnimationBlendMode:
  38413. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38414. interpolants[ j ].evaluate( clipTime );
  38415. propertyMixers[ j ].accumulateAdditive( weight );
  38416. }
  38417. break;
  38418. case NormalAnimationBlendMode:
  38419. default:
  38420. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38421. interpolants[ j ].evaluate( clipTime );
  38422. propertyMixers[ j ].accumulate( accuIndex, weight );
  38423. }
  38424. }
  38425. }
  38426. }
  38427. _updateWeight( time ) {
  38428. let weight = 0;
  38429. if ( this.enabled ) {
  38430. weight = this.weight;
  38431. const interpolant = this._weightInterpolant;
  38432. if ( interpolant !== null ) {
  38433. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38434. weight *= interpolantValue;
  38435. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38436. this.stopFading();
  38437. if ( interpolantValue === 0 ) {
  38438. // faded out, disable
  38439. this.enabled = false;
  38440. }
  38441. }
  38442. }
  38443. }
  38444. this._effectiveWeight = weight;
  38445. return weight;
  38446. }
  38447. _updateTimeScale( time ) {
  38448. let timeScale = 0;
  38449. if ( ! this.paused ) {
  38450. timeScale = this.timeScale;
  38451. const interpolant = this._timeScaleInterpolant;
  38452. if ( interpolant !== null ) {
  38453. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38454. timeScale *= interpolantValue;
  38455. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38456. this.stopWarping();
  38457. if ( timeScale === 0 ) {
  38458. // motion has halted, pause
  38459. this.paused = true;
  38460. } else {
  38461. // warp done - apply final time scale
  38462. this.timeScale = timeScale;
  38463. }
  38464. }
  38465. }
  38466. }
  38467. this._effectiveTimeScale = timeScale;
  38468. return timeScale;
  38469. }
  38470. _updateTime( deltaTime ) {
  38471. const duration = this._clip.duration;
  38472. const loop = this.loop;
  38473. let time = this.time + deltaTime;
  38474. let loopCount = this._loopCount;
  38475. const pingPong = ( loop === LoopPingPong );
  38476. if ( deltaTime === 0 ) {
  38477. if ( loopCount === -1 ) return time;
  38478. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  38479. }
  38480. if ( loop === LoopOnce ) {
  38481. if ( loopCount === -1 ) {
  38482. // just started
  38483. this._loopCount = 0;
  38484. this._setEndings( true, true, false );
  38485. }
  38486. handle_stop: {
  38487. if ( time >= duration ) {
  38488. time = duration;
  38489. } else if ( time < 0 ) {
  38490. time = 0;
  38491. } else {
  38492. this.time = time;
  38493. break handle_stop;
  38494. }
  38495. if ( this.clampWhenFinished ) this.paused = true;
  38496. else this.enabled = false;
  38497. this.time = time;
  38498. this._mixer.dispatchEvent( {
  38499. type: 'finished', action: this,
  38500. direction: deltaTime < 0 ? -1 : 1
  38501. } );
  38502. }
  38503. } else { // repetitive Repeat or PingPong
  38504. if ( loopCount === -1 ) {
  38505. // just started
  38506. if ( deltaTime >= 0 ) {
  38507. loopCount = 0;
  38508. this._setEndings( true, this.repetitions === 0, pingPong );
  38509. } else {
  38510. // when looping in reverse direction, the initial
  38511. // transition through zero counts as a repetition,
  38512. // so leave loopCount at -1
  38513. this._setEndings( this.repetitions === 0, true, pingPong );
  38514. }
  38515. }
  38516. if ( time >= duration || time < 0 ) {
  38517. // wrap around
  38518. const loopDelta = Math.floor( time / duration ); // signed
  38519. time -= duration * loopDelta;
  38520. loopCount += Math.abs( loopDelta );
  38521. const pending = this.repetitions - loopCount;
  38522. if ( pending <= 0 ) {
  38523. // have to stop (switch state, clamp time, fire event)
  38524. if ( this.clampWhenFinished ) this.paused = true;
  38525. else this.enabled = false;
  38526. time = deltaTime > 0 ? duration : 0;
  38527. this.time = time;
  38528. this._mixer.dispatchEvent( {
  38529. type: 'finished', action: this,
  38530. direction: deltaTime > 0 ? 1 : -1
  38531. } );
  38532. } else {
  38533. // keep running
  38534. if ( pending === 1 ) {
  38535. // entering the last round
  38536. const atStart = deltaTime < 0;
  38537. this._setEndings( atStart, ! atStart, pingPong );
  38538. } else {
  38539. this._setEndings( false, false, pingPong );
  38540. }
  38541. this._loopCount = loopCount;
  38542. this.time = time;
  38543. this._mixer.dispatchEvent( {
  38544. type: 'loop', action: this, loopDelta: loopDelta
  38545. } );
  38546. }
  38547. } else {
  38548. this.time = time;
  38549. }
  38550. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  38551. // invert time for the "pong round"
  38552. return duration - time;
  38553. }
  38554. }
  38555. return time;
  38556. }
  38557. _setEndings( atStart, atEnd, pingPong ) {
  38558. const settings = this._interpolantSettings;
  38559. if ( pingPong ) {
  38560. settings.endingStart = ZeroSlopeEnding;
  38561. settings.endingEnd = ZeroSlopeEnding;
  38562. } else {
  38563. // assuming for LoopOnce atStart == atEnd == true
  38564. if ( atStart ) {
  38565. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38566. } else {
  38567. settings.endingStart = WrapAroundEnding;
  38568. }
  38569. if ( atEnd ) {
  38570. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38571. } else {
  38572. settings.endingEnd = WrapAroundEnding;
  38573. }
  38574. }
  38575. }
  38576. _scheduleFading( duration, weightNow, weightThen ) {
  38577. const mixer = this._mixer, now = mixer.time;
  38578. let interpolant = this._weightInterpolant;
  38579. if ( interpolant === null ) {
  38580. interpolant = mixer._lendControlInterpolant();
  38581. this._weightInterpolant = interpolant;
  38582. }
  38583. const times = interpolant.parameterPositions,
  38584. values = interpolant.sampleValues;
  38585. times[ 0 ] = now;
  38586. values[ 0 ] = weightNow;
  38587. times[ 1 ] = now + duration;
  38588. values[ 1 ] = weightThen;
  38589. return this;
  38590. }
  38591. }
  38592. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  38593. /**
  38594. * `AnimationMixer` is a player for animations on a particular object in
  38595. * the scene. When multiple objects in the scene are animated independently,
  38596. * one `AnimationMixer` may be used for each object.
  38597. */
  38598. class AnimationMixer extends EventDispatcher {
  38599. /**
  38600. * Constructs a new animation mixer.
  38601. *
  38602. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  38603. */
  38604. constructor( root ) {
  38605. super();
  38606. this._root = root;
  38607. this._initMemoryManager();
  38608. this._accuIndex = 0;
  38609. /**
  38610. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  38611. *
  38612. * @type {number}
  38613. * @default 0
  38614. */
  38615. this.time = 0;
  38616. /**
  38617. * A scaling factor for the global time.
  38618. *
  38619. * Note: Setting this member to `0` and later back to `1` is a
  38620. * possibility to pause/unpause all actions that are controlled by this
  38621. * mixer.
  38622. *
  38623. * @type {number}
  38624. * @default 1
  38625. */
  38626. this.timeScale = 1.0;
  38627. }
  38628. _bindAction( action, prototypeAction ) {
  38629. const root = action._localRoot || this._root,
  38630. tracks = action._clip.tracks,
  38631. nTracks = tracks.length,
  38632. bindings = action._propertyBindings,
  38633. interpolants = action._interpolants,
  38634. rootUuid = root.uuid,
  38635. bindingsByRoot = this._bindingsByRootAndName;
  38636. let bindingsByName = bindingsByRoot[ rootUuid ];
  38637. if ( bindingsByName === undefined ) {
  38638. bindingsByName = {};
  38639. bindingsByRoot[ rootUuid ] = bindingsByName;
  38640. }
  38641. for ( let i = 0; i !== nTracks; ++ i ) {
  38642. const track = tracks[ i ],
  38643. trackName = track.name;
  38644. let binding = bindingsByName[ trackName ];
  38645. if ( binding !== undefined ) {
  38646. ++ binding.referenceCount;
  38647. bindings[ i ] = binding;
  38648. } else {
  38649. binding = bindings[ i ];
  38650. if ( binding !== undefined ) {
  38651. // existing binding, make sure the cache knows
  38652. if ( binding._cacheIndex === null ) {
  38653. ++ binding.referenceCount;
  38654. this._addInactiveBinding( binding, rootUuid, trackName );
  38655. }
  38656. continue;
  38657. }
  38658. const path = prototypeAction && prototypeAction.
  38659. _propertyBindings[ i ].binding.parsedPath;
  38660. binding = new PropertyMixer(
  38661. PropertyBinding.create( root, trackName, path ),
  38662. track.ValueTypeName, track.getValueSize() );
  38663. ++ binding.referenceCount;
  38664. this._addInactiveBinding( binding, rootUuid, trackName );
  38665. bindings[ i ] = binding;
  38666. }
  38667. interpolants[ i ].resultBuffer = binding.buffer;
  38668. }
  38669. }
  38670. _activateAction( action ) {
  38671. if ( ! this._isActiveAction( action ) ) {
  38672. if ( action._cacheIndex === null ) {
  38673. // this action has been forgotten by the cache, but the user
  38674. // appears to be still using it -> rebind
  38675. const rootUuid = ( action._localRoot || this._root ).uuid,
  38676. clipUuid = action._clip.uuid,
  38677. actionsForClip = this._actionsByClip[ clipUuid ];
  38678. this._bindAction( action,
  38679. actionsForClip && actionsForClip.knownActions[ 0 ] );
  38680. this._addInactiveAction( action, clipUuid, rootUuid );
  38681. }
  38682. const bindings = action._propertyBindings;
  38683. // increment reference counts / sort out state
  38684. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38685. const binding = bindings[ i ];
  38686. if ( binding.useCount ++ === 0 ) {
  38687. this._lendBinding( binding );
  38688. binding.saveOriginalState();
  38689. }
  38690. }
  38691. this._lendAction( action );
  38692. }
  38693. }
  38694. _deactivateAction( action ) {
  38695. if ( this._isActiveAction( action ) ) {
  38696. const bindings = action._propertyBindings;
  38697. // decrement reference counts / sort out state
  38698. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38699. const binding = bindings[ i ];
  38700. if ( -- binding.useCount === 0 ) {
  38701. binding.restoreOriginalState();
  38702. this._takeBackBinding( binding );
  38703. }
  38704. }
  38705. this._takeBackAction( action );
  38706. }
  38707. }
  38708. // Memory manager
  38709. _initMemoryManager() {
  38710. this._actions = []; // 'nActiveActions' followed by inactive ones
  38711. this._nActiveActions = 0;
  38712. this._actionsByClip = {};
  38713. // inside:
  38714. // {
  38715. // knownActions: Array< AnimationAction > - used as prototypes
  38716. // actionByRoot: AnimationAction - lookup
  38717. // }
  38718. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  38719. this._nActiveBindings = 0;
  38720. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  38721. this._controlInterpolants = []; // same game as above
  38722. this._nActiveControlInterpolants = 0;
  38723. const scope = this;
  38724. this.stats = {
  38725. actions: {
  38726. get total() {
  38727. return scope._actions.length;
  38728. },
  38729. get inUse() {
  38730. return scope._nActiveActions;
  38731. }
  38732. },
  38733. bindings: {
  38734. get total() {
  38735. return scope._bindings.length;
  38736. },
  38737. get inUse() {
  38738. return scope._nActiveBindings;
  38739. }
  38740. },
  38741. controlInterpolants: {
  38742. get total() {
  38743. return scope._controlInterpolants.length;
  38744. },
  38745. get inUse() {
  38746. return scope._nActiveControlInterpolants;
  38747. }
  38748. }
  38749. };
  38750. }
  38751. // Memory management for AnimationAction objects
  38752. _isActiveAction( action ) {
  38753. const index = action._cacheIndex;
  38754. return index !== null && index < this._nActiveActions;
  38755. }
  38756. _addInactiveAction( action, clipUuid, rootUuid ) {
  38757. const actions = this._actions,
  38758. actionsByClip = this._actionsByClip;
  38759. let actionsForClip = actionsByClip[ clipUuid ];
  38760. if ( actionsForClip === undefined ) {
  38761. actionsForClip = {
  38762. knownActions: [ action ],
  38763. actionByRoot: {}
  38764. };
  38765. action._byClipCacheIndex = 0;
  38766. actionsByClip[ clipUuid ] = actionsForClip;
  38767. } else {
  38768. const knownActions = actionsForClip.knownActions;
  38769. action._byClipCacheIndex = knownActions.length;
  38770. knownActions.push( action );
  38771. }
  38772. action._cacheIndex = actions.length;
  38773. actions.push( action );
  38774. actionsForClip.actionByRoot[ rootUuid ] = action;
  38775. }
  38776. _removeInactiveAction( action ) {
  38777. const actions = this._actions,
  38778. lastInactiveAction = actions[ actions.length - 1 ],
  38779. cacheIndex = action._cacheIndex;
  38780. lastInactiveAction._cacheIndex = cacheIndex;
  38781. actions[ cacheIndex ] = lastInactiveAction;
  38782. actions.pop();
  38783. action._cacheIndex = null;
  38784. const clipUuid = action._clip.uuid,
  38785. actionsByClip = this._actionsByClip,
  38786. actionsForClip = actionsByClip[ clipUuid ],
  38787. knownActionsForClip = actionsForClip.knownActions,
  38788. lastKnownAction =
  38789. knownActionsForClip[ knownActionsForClip.length - 1 ],
  38790. byClipCacheIndex = action._byClipCacheIndex;
  38791. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  38792. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  38793. knownActionsForClip.pop();
  38794. action._byClipCacheIndex = null;
  38795. const actionByRoot = actionsForClip.actionByRoot,
  38796. rootUuid = ( action._localRoot || this._root ).uuid;
  38797. delete actionByRoot[ rootUuid ];
  38798. if ( knownActionsForClip.length === 0 ) {
  38799. delete actionsByClip[ clipUuid ];
  38800. }
  38801. this._removeInactiveBindingsForAction( action );
  38802. }
  38803. _removeInactiveBindingsForAction( action ) {
  38804. const bindings = action._propertyBindings;
  38805. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38806. const binding = bindings[ i ];
  38807. if ( -- binding.referenceCount === 0 ) {
  38808. this._removeInactiveBinding( binding );
  38809. }
  38810. }
  38811. }
  38812. _lendAction( action ) {
  38813. // [ active actions | inactive actions ]
  38814. // [ active actions >| inactive actions ]
  38815. // s a
  38816. // <-swap->
  38817. // a s
  38818. const actions = this._actions,
  38819. prevIndex = action._cacheIndex,
  38820. lastActiveIndex = this._nActiveActions ++,
  38821. firstInactiveAction = actions[ lastActiveIndex ];
  38822. action._cacheIndex = lastActiveIndex;
  38823. actions[ lastActiveIndex ] = action;
  38824. firstInactiveAction._cacheIndex = prevIndex;
  38825. actions[ prevIndex ] = firstInactiveAction;
  38826. }
  38827. _takeBackAction( action ) {
  38828. // [ active actions | inactive actions ]
  38829. // [ active actions |< inactive actions ]
  38830. // a s
  38831. // <-swap->
  38832. // s a
  38833. const actions = this._actions,
  38834. prevIndex = action._cacheIndex,
  38835. firstInactiveIndex = -- this._nActiveActions,
  38836. lastActiveAction = actions[ firstInactiveIndex ];
  38837. action._cacheIndex = firstInactiveIndex;
  38838. actions[ firstInactiveIndex ] = action;
  38839. lastActiveAction._cacheIndex = prevIndex;
  38840. actions[ prevIndex ] = lastActiveAction;
  38841. }
  38842. // Memory management for PropertyMixer objects
  38843. _addInactiveBinding( binding, rootUuid, trackName ) {
  38844. const bindingsByRoot = this._bindingsByRootAndName,
  38845. bindings = this._bindings;
  38846. let bindingByName = bindingsByRoot[ rootUuid ];
  38847. if ( bindingByName === undefined ) {
  38848. bindingByName = {};
  38849. bindingsByRoot[ rootUuid ] = bindingByName;
  38850. }
  38851. bindingByName[ trackName ] = binding;
  38852. binding._cacheIndex = bindings.length;
  38853. bindings.push( binding );
  38854. }
  38855. _removeInactiveBinding( binding ) {
  38856. const bindings = this._bindings,
  38857. propBinding = binding.binding,
  38858. rootUuid = propBinding.rootNode.uuid,
  38859. trackName = propBinding.path,
  38860. bindingsByRoot = this._bindingsByRootAndName,
  38861. bindingByName = bindingsByRoot[ rootUuid ],
  38862. lastInactiveBinding = bindings[ bindings.length - 1 ],
  38863. cacheIndex = binding._cacheIndex;
  38864. lastInactiveBinding._cacheIndex = cacheIndex;
  38865. bindings[ cacheIndex ] = lastInactiveBinding;
  38866. bindings.pop();
  38867. delete bindingByName[ trackName ];
  38868. if ( Object.keys( bindingByName ).length === 0 ) {
  38869. delete bindingsByRoot[ rootUuid ];
  38870. }
  38871. }
  38872. _lendBinding( binding ) {
  38873. const bindings = this._bindings,
  38874. prevIndex = binding._cacheIndex,
  38875. lastActiveIndex = this._nActiveBindings ++,
  38876. firstInactiveBinding = bindings[ lastActiveIndex ];
  38877. binding._cacheIndex = lastActiveIndex;
  38878. bindings[ lastActiveIndex ] = binding;
  38879. firstInactiveBinding._cacheIndex = prevIndex;
  38880. bindings[ prevIndex ] = firstInactiveBinding;
  38881. }
  38882. _takeBackBinding( binding ) {
  38883. const bindings = this._bindings,
  38884. prevIndex = binding._cacheIndex,
  38885. firstInactiveIndex = -- this._nActiveBindings,
  38886. lastActiveBinding = bindings[ firstInactiveIndex ];
  38887. binding._cacheIndex = firstInactiveIndex;
  38888. bindings[ firstInactiveIndex ] = binding;
  38889. lastActiveBinding._cacheIndex = prevIndex;
  38890. bindings[ prevIndex ] = lastActiveBinding;
  38891. }
  38892. // Memory management of Interpolants for weight and time scale
  38893. _lendControlInterpolant() {
  38894. const interpolants = this._controlInterpolants,
  38895. lastActiveIndex = this._nActiveControlInterpolants ++;
  38896. let interpolant = interpolants[ lastActiveIndex ];
  38897. if ( interpolant === undefined ) {
  38898. interpolant = new LinearInterpolant(
  38899. new Float32Array( 2 ), new Float32Array( 2 ),
  38900. 1, _controlInterpolantsResultBuffer );
  38901. interpolant.__cacheIndex = lastActiveIndex;
  38902. interpolants[ lastActiveIndex ] = interpolant;
  38903. }
  38904. return interpolant;
  38905. }
  38906. _takeBackControlInterpolant( interpolant ) {
  38907. const interpolants = this._controlInterpolants,
  38908. prevIndex = interpolant.__cacheIndex,
  38909. firstInactiveIndex = -- this._nActiveControlInterpolants,
  38910. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  38911. interpolant.__cacheIndex = firstInactiveIndex;
  38912. interpolants[ firstInactiveIndex ] = interpolant;
  38913. lastActiveInterpolant.__cacheIndex = prevIndex;
  38914. interpolants[ prevIndex ] = lastActiveInterpolant;
  38915. }
  38916. /**
  38917. * Returns an instance of {@link AnimationAction} for the passed clip.
  38918. *
  38919. * If an action fitting the clip and root parameters doesn't yet exist, it
  38920. * will be created by this method. Calling this method several times with the
  38921. * same clip and root parameters always returns the same action.
  38922. *
  38923. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  38924. * @param {Object3D} [optionalRoot] - An alternative root object.
  38925. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38926. * @return {?AnimationAction} The animation action.
  38927. */
  38928. clipAction( clip, optionalRoot, blendMode ) {
  38929. const root = optionalRoot || this._root,
  38930. rootUuid = root.uuid;
  38931. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  38932. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  38933. const actionsForClip = this._actionsByClip[ clipUuid ];
  38934. let prototypeAction = null;
  38935. if ( blendMode === undefined ) {
  38936. if ( clipObject !== null ) {
  38937. blendMode = clipObject.blendMode;
  38938. } else {
  38939. blendMode = NormalAnimationBlendMode;
  38940. }
  38941. }
  38942. if ( actionsForClip !== undefined ) {
  38943. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  38944. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  38945. return existingAction;
  38946. }
  38947. // we know the clip, so we don't have to parse all
  38948. // the bindings again but can just copy
  38949. prototypeAction = actionsForClip.knownActions[ 0 ];
  38950. // also, take the clip from the prototype action
  38951. if ( clipObject === null )
  38952. clipObject = prototypeAction._clip;
  38953. }
  38954. // clip must be known when specified via string
  38955. if ( clipObject === null ) return null;
  38956. // allocate all resources required to run it
  38957. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  38958. this._bindAction( newAction, prototypeAction );
  38959. // and make the action known to the memory manager
  38960. this._addInactiveAction( newAction, clipUuid, rootUuid );
  38961. return newAction;
  38962. }
  38963. /**
  38964. * Returns an existing animation action for the passed clip.
  38965. *
  38966. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  38967. * @param {Object3D} [optionalRoot] - An alternative root object.
  38968. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  38969. */
  38970. existingAction( clip, optionalRoot ) {
  38971. const root = optionalRoot || this._root,
  38972. rootUuid = root.uuid,
  38973. clipObject = typeof clip === 'string' ?
  38974. AnimationClip.findByName( root, clip ) : clip,
  38975. clipUuid = clipObject ? clipObject.uuid : clip,
  38976. actionsForClip = this._actionsByClip[ clipUuid ];
  38977. if ( actionsForClip !== undefined ) {
  38978. return actionsForClip.actionByRoot[ rootUuid ] || null;
  38979. }
  38980. return null;
  38981. }
  38982. /**
  38983. * Deactivates all previously scheduled actions on this mixer.
  38984. *
  38985. * @return {AnimationMixer} A reference to thi animation mixer.
  38986. */
  38987. stopAllAction() {
  38988. const actions = this._actions,
  38989. nActions = this._nActiveActions;
  38990. for ( let i = nActions - 1; i >= 0; -- i ) {
  38991. actions[ i ].stop();
  38992. }
  38993. return this;
  38994. }
  38995. /**
  38996. * Advances the global mixer time and updates the animation.
  38997. *
  38998. * This is usually done in the render loop by passing the delta
  38999. * time from {@link Clock} or {@link Timer}.
  39000. *
  39001. * @param {number} deltaTime - The delta time in seconds.
  39002. * @return {AnimationMixer} A reference to thi animation mixer.
  39003. */
  39004. update( deltaTime ) {
  39005. deltaTime *= this.timeScale;
  39006. const actions = this._actions,
  39007. nActions = this._nActiveActions,
  39008. time = this.time += deltaTime,
  39009. timeDirection = Math.sign( deltaTime ),
  39010. accuIndex = this._accuIndex ^= 1;
  39011. // run active actions
  39012. for ( let i = 0; i !== nActions; ++ i ) {
  39013. const action = actions[ i ];
  39014. action._update( time, deltaTime, timeDirection, accuIndex );
  39015. }
  39016. // update scene graph
  39017. const bindings = this._bindings,
  39018. nBindings = this._nActiveBindings;
  39019. for ( let i = 0; i !== nBindings; ++ i ) {
  39020. bindings[ i ].apply( accuIndex );
  39021. }
  39022. return this;
  39023. }
  39024. /**
  39025. * Sets the global mixer to a specific time and updates the animation accordingly.
  39026. *
  39027. * This is useful when you need to jump to an exact time in an animation. The
  39028. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  39029. *
  39030. * @param {number} time - The time to set in seconds.
  39031. * @return {AnimationMixer} A reference to thi animation mixer.
  39032. */
  39033. setTime( time ) {
  39034. this.time = 0; // Zero out time attribute for AnimationMixer object;
  39035. for ( let i = 0; i < this._actions.length; i ++ ) {
  39036. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  39037. }
  39038. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  39039. }
  39040. /**
  39041. * Returns this mixer's root object.
  39042. *
  39043. * @return {Object3D} The mixer's root object.
  39044. */
  39045. getRoot() {
  39046. return this._root;
  39047. }
  39048. /**
  39049. * Deallocates all memory resources for a clip. Before using this method make
  39050. * sure to call {@link AnimationAction#stop} for all related actions.
  39051. *
  39052. * @param {AnimationClip} clip - The clip to uncache.
  39053. */
  39054. uncacheClip( clip ) {
  39055. const actions = this._actions,
  39056. clipUuid = clip.uuid,
  39057. actionsByClip = this._actionsByClip,
  39058. actionsForClip = actionsByClip[ clipUuid ];
  39059. if ( actionsForClip !== undefined ) {
  39060. // note: just calling _removeInactiveAction would mess up the
  39061. // iteration state and also require updating the state we can
  39062. // just throw away
  39063. const actionsToRemove = actionsForClip.knownActions;
  39064. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  39065. const action = actionsToRemove[ i ];
  39066. this._deactivateAction( action );
  39067. const cacheIndex = action._cacheIndex,
  39068. lastInactiveAction = actions[ actions.length - 1 ];
  39069. action._cacheIndex = null;
  39070. action._byClipCacheIndex = null;
  39071. lastInactiveAction._cacheIndex = cacheIndex;
  39072. actions[ cacheIndex ] = lastInactiveAction;
  39073. actions.pop();
  39074. this._removeInactiveBindingsForAction( action );
  39075. }
  39076. delete actionsByClip[ clipUuid ];
  39077. }
  39078. }
  39079. /**
  39080. * Deallocates all memory resources for a root object. Before using this
  39081. * method make sure to call {@link AnimationAction#stop} for all related
  39082. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  39083. * mixer operates on a single root.
  39084. *
  39085. * @param {Object3D} root - The root object to uncache.
  39086. */
  39087. uncacheRoot( root ) {
  39088. const rootUuid = root.uuid,
  39089. actionsByClip = this._actionsByClip;
  39090. for ( const clipUuid in actionsByClip ) {
  39091. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  39092. action = actionByRoot[ rootUuid ];
  39093. if ( action !== undefined ) {
  39094. this._deactivateAction( action );
  39095. this._removeInactiveAction( action );
  39096. }
  39097. }
  39098. const bindingsByRoot = this._bindingsByRootAndName,
  39099. bindingByName = bindingsByRoot[ rootUuid ];
  39100. if ( bindingByName !== undefined ) {
  39101. for ( const trackName in bindingByName ) {
  39102. const binding = bindingByName[ trackName ];
  39103. binding.restoreOriginalState();
  39104. this._removeInactiveBinding( binding );
  39105. }
  39106. }
  39107. }
  39108. /**
  39109. * Deallocates all memory resources for an action. The action is identified by the
  39110. * given clip and an optional root object. Before using this method make
  39111. * sure to call {@link AnimationAction#stop} to deactivate the action.
  39112. *
  39113. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39114. * @param {Object3D} [optionalRoot] - An alternative root object.
  39115. */
  39116. uncacheAction( clip, optionalRoot ) {
  39117. const action = this.existingAction( clip, optionalRoot );
  39118. if ( action !== null ) {
  39119. this._deactivateAction( action );
  39120. this._removeInactiveAction( action );
  39121. }
  39122. }
  39123. }
  39124. /**
  39125. * Represents a 3D render target.
  39126. *
  39127. * @augments RenderTarget
  39128. */
  39129. class RenderTarget3D extends RenderTarget {
  39130. /**
  39131. * Constructs a new 3D render target.
  39132. *
  39133. * @param {number} [width=1] - The width of the render target.
  39134. * @param {number} [height=1] - The height of the render target.
  39135. * @param {number} [depth=1] - The height of the render target.
  39136. * @param {RenderTarget~Options} [options] - The configuration object.
  39137. */
  39138. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  39139. super( width, height, options );
  39140. /**
  39141. * This flag can be used for type testing.
  39142. *
  39143. * @type {boolean}
  39144. * @readonly
  39145. * @default true
  39146. */
  39147. this.isRenderTarget3D = true;
  39148. this.depth = depth;
  39149. /**
  39150. * Overwritten with a different texture type.
  39151. *
  39152. * @type {Data3DTexture}
  39153. */
  39154. this.texture = new Data3DTexture( null, width, height, depth );
  39155. this._setTextureOptions( options );
  39156. this.texture.isRenderTargetTexture = true;
  39157. }
  39158. }
  39159. /**
  39160. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  39161. *
  39162. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  39163. * ```js
  39164. * uniforms: {
  39165. * time: { value: 1.0 },
  39166. * resolution: new Uniform( new Vector2() )
  39167. * };
  39168. * ```
  39169. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39170. * in {@link WebGLRenderer}.
  39171. */
  39172. class Uniform {
  39173. /**
  39174. * Constructs a new uniform.
  39175. *
  39176. * @param {any} value - The uniform value.
  39177. */
  39178. constructor( value ) {
  39179. /**
  39180. * The uniform value.
  39181. *
  39182. * @type {any}
  39183. */
  39184. this.value = value;
  39185. }
  39186. /**
  39187. * Returns a new uniform with copied values from this instance.
  39188. * If the value has a `clone()` method, the value is cloned as well.
  39189. *
  39190. * @return {Uniform} A clone of this instance.
  39191. */
  39192. clone() {
  39193. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  39194. }
  39195. }
  39196. let _id$1 = 0;
  39197. /**
  39198. * A class for managing multiple uniforms in a single group. The renderer will process
  39199. * such a definition as a single UBO.
  39200. *
  39201. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39202. * in {@link WebGLRenderer}.
  39203. *
  39204. * @augments EventDispatcher
  39205. */
  39206. class UniformsGroup extends EventDispatcher {
  39207. /**
  39208. * Constructs a new uniforms group.
  39209. */
  39210. constructor() {
  39211. super();
  39212. /**
  39213. * This flag can be used for type testing.
  39214. *
  39215. * @type {boolean}
  39216. * @readonly
  39217. * @default true
  39218. */
  39219. this.isUniformsGroup = true;
  39220. /**
  39221. * The ID of the 3D object.
  39222. *
  39223. * @name UniformsGroup#id
  39224. * @type {number}
  39225. * @readonly
  39226. */
  39227. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  39228. /**
  39229. * The name of the uniforms group.
  39230. *
  39231. * @type {string}
  39232. */
  39233. this.name = '';
  39234. /**
  39235. * The buffer usage.
  39236. *
  39237. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  39238. * @default StaticDrawUsage
  39239. */
  39240. this.usage = StaticDrawUsage;
  39241. /**
  39242. * An array holding the uniforms.
  39243. *
  39244. * @type {Array<Uniform>}
  39245. */
  39246. this.uniforms = [];
  39247. }
  39248. /**
  39249. * Adds the given uniform to this uniforms group.
  39250. *
  39251. * @param {Uniform} uniform - The uniform to add.
  39252. * @return {UniformsGroup} A reference to this uniforms group.
  39253. */
  39254. add( uniform ) {
  39255. this.uniforms.push( uniform );
  39256. return this;
  39257. }
  39258. /**
  39259. * Removes the given uniform from this uniforms group.
  39260. *
  39261. * @param {Uniform} uniform - The uniform to remove.
  39262. * @return {UniformsGroup} A reference to this uniforms group.
  39263. */
  39264. remove( uniform ) {
  39265. const index = this.uniforms.indexOf( uniform );
  39266. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  39267. return this;
  39268. }
  39269. /**
  39270. * Sets the name of this uniforms group.
  39271. *
  39272. * @param {string} name - The name to set.
  39273. * @return {UniformsGroup} A reference to this uniforms group.
  39274. */
  39275. setName( name ) {
  39276. this.name = name;
  39277. return this;
  39278. }
  39279. /**
  39280. * Sets the usage of this uniforms group.
  39281. *
  39282. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  39283. * @return {UniformsGroup} A reference to this uniforms group.
  39284. */
  39285. setUsage( value ) {
  39286. this.usage = value;
  39287. return this;
  39288. }
  39289. /**
  39290. * Frees the GPU-related resources allocated by this instance. Call this
  39291. * method whenever this instance is no longer used in your app.
  39292. *
  39293. * @fires Texture#dispose
  39294. */
  39295. dispose() {
  39296. this.dispatchEvent( { type: 'dispose' } );
  39297. }
  39298. /**
  39299. * Copies the values of the given uniforms group to this instance.
  39300. *
  39301. * @param {UniformsGroup} source - The uniforms group to copy.
  39302. * @return {UniformsGroup} A reference to this uniforms group.
  39303. */
  39304. copy( source ) {
  39305. this.name = source.name;
  39306. this.usage = source.usage;
  39307. const uniformsSource = source.uniforms;
  39308. this.uniforms.length = 0;
  39309. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  39310. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  39311. for ( let j = 0; j < uniforms.length; j ++ ) {
  39312. this.uniforms.push( uniforms[ j ].clone() );
  39313. }
  39314. }
  39315. return this;
  39316. }
  39317. /**
  39318. * Returns a new uniforms group with copied values from this instance.
  39319. *
  39320. * @return {UniformsGroup} A clone of this instance.
  39321. */
  39322. clone() {
  39323. return new this.constructor().copy( this );
  39324. }
  39325. }
  39326. /**
  39327. * An instanced version of an interleaved buffer.
  39328. *
  39329. * @augments InterleavedBuffer
  39330. */
  39331. class InstancedInterleavedBuffer extends InterleavedBuffer {
  39332. /**
  39333. * Constructs a new instanced interleaved buffer.
  39334. *
  39335. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  39336. * @param {number} stride - The number of typed-array elements per vertex.
  39337. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  39338. */
  39339. constructor( array, stride, meshPerAttribute = 1 ) {
  39340. super( array, stride );
  39341. /**
  39342. * This flag can be used for type testing.
  39343. *
  39344. * @type {boolean}
  39345. * @readonly
  39346. * @default true
  39347. */
  39348. this.isInstancedInterleavedBuffer = true;
  39349. /**
  39350. * Defines how often a value of this buffer attribute should be repeated,
  39351. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  39352. *
  39353. * @type {number}
  39354. * @default 1
  39355. */
  39356. this.meshPerAttribute = meshPerAttribute;
  39357. }
  39358. copy( source ) {
  39359. super.copy( source );
  39360. this.meshPerAttribute = source.meshPerAttribute;
  39361. return this;
  39362. }
  39363. clone( data ) {
  39364. const ib = super.clone( data );
  39365. ib.meshPerAttribute = this.meshPerAttribute;
  39366. return ib;
  39367. }
  39368. toJSON( data ) {
  39369. const json = super.toJSON( data );
  39370. json.isInstancedInterleavedBuffer = true;
  39371. json.meshPerAttribute = this.meshPerAttribute;
  39372. return json;
  39373. }
  39374. }
  39375. /**
  39376. * An alternative version of a buffer attribute with more control over the VBO.
  39377. *
  39378. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  39379. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  39380. *
  39381. * The most common use case for this class is when some kind of GPGPU calculation interferes
  39382. * or even produces the VBOs in question.
  39383. *
  39384. * Notice that this class can only be used with {@link WebGLRenderer}.
  39385. */
  39386. class GLBufferAttribute {
  39387. /**
  39388. * Constructs a new GL buffer attribute.
  39389. *
  39390. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  39391. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39392. * @param {number} itemSize - The item size.
  39393. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39394. * @param {number} count - The expected number of vertices in VBO.
  39395. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  39396. */
  39397. constructor( buffer, type, itemSize, elementSize, count, normalized = false ) {
  39398. /**
  39399. * This flag can be used for type testing.
  39400. *
  39401. * @type {boolean}
  39402. * @readonly
  39403. * @default true
  39404. */
  39405. this.isGLBufferAttribute = true;
  39406. /**
  39407. * The name of the buffer attribute.
  39408. *
  39409. * @type {string}
  39410. */
  39411. this.name = '';
  39412. /**
  39413. * The native WebGL buffer.
  39414. *
  39415. * @type {WebGLBuffer}
  39416. */
  39417. this.buffer = buffer;
  39418. /**
  39419. * The native data type.
  39420. *
  39421. * @type {number}
  39422. */
  39423. this.type = type;
  39424. /**
  39425. * The item size, see {@link BufferAttribute#itemSize}.
  39426. *
  39427. * @type {number}
  39428. */
  39429. this.itemSize = itemSize;
  39430. /**
  39431. * The corresponding size (in bytes) for the given `type` parameter.
  39432. *
  39433. * @type {number}
  39434. */
  39435. this.elementSize = elementSize;
  39436. /**
  39437. * The expected number of vertices in VBO.
  39438. *
  39439. * @type {number}
  39440. */
  39441. this.count = count;
  39442. /**
  39443. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  39444. * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`,
  39445. * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to
  39446. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  39447. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  39448. *
  39449. * @type {boolean}
  39450. */
  39451. this.normalized = normalized;
  39452. /**
  39453. * A version number, incremented every time the `needsUpdate` is set to `true`.
  39454. *
  39455. * @type {number}
  39456. */
  39457. this.version = 0;
  39458. }
  39459. /**
  39460. * Flag to indicate that this attribute has changed and should be re-sent to
  39461. * the GPU. Set this to `true` when you modify the value of the array.
  39462. *
  39463. * @type {number}
  39464. * @default false
  39465. * @param {boolean} value
  39466. */
  39467. set needsUpdate( value ) {
  39468. if ( value === true ) this.version ++;
  39469. }
  39470. /**
  39471. * Sets the given native WebGL buffer.
  39472. *
  39473. * @param {WebGLBuffer} buffer - The buffer to set.
  39474. * @return {BufferAttribute} A reference to this instance.
  39475. */
  39476. setBuffer( buffer ) {
  39477. this.buffer = buffer;
  39478. return this;
  39479. }
  39480. /**
  39481. * Sets the given native data type and element size.
  39482. *
  39483. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39484. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39485. * @return {BufferAttribute} A reference to this instance.
  39486. */
  39487. setType( type, elementSize ) {
  39488. this.type = type;
  39489. this.elementSize = elementSize;
  39490. return this;
  39491. }
  39492. /**
  39493. * Sets the item size.
  39494. *
  39495. * @param {number} itemSize - The item size.
  39496. * @return {BufferAttribute} A reference to this instance.
  39497. */
  39498. setItemSize( itemSize ) {
  39499. this.itemSize = itemSize;
  39500. return this;
  39501. }
  39502. /**
  39503. * Sets the count (the expected number of vertices in VBO).
  39504. *
  39505. * @param {number} count - The count.
  39506. * @return {BufferAttribute} A reference to this instance.
  39507. */
  39508. setCount( count ) {
  39509. this.count = count;
  39510. return this;
  39511. }
  39512. }
  39513. const _matrix = /*@__PURE__*/ new Matrix4();
  39514. /**
  39515. * This class is designed to assist with raycasting. Raycasting is used for
  39516. * mouse picking (working out what objects in the 3d space the mouse is over)
  39517. * amongst other things.
  39518. */
  39519. class Raycaster {
  39520. /**
  39521. * Constructs a new raycaster.
  39522. *
  39523. * @param {Vector3} origin - The origin vector where the ray casts from.
  39524. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39525. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  39526. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  39527. */
  39528. constructor( origin, direction, near = 0, far = Infinity ) {
  39529. /**
  39530. * The ray used for raycasting.
  39531. *
  39532. * @type {Ray}
  39533. */
  39534. this.ray = new Ray( origin, direction );
  39535. /**
  39536. * All results returned are further away than near. Near can't be negative.
  39537. *
  39538. * @type {number}
  39539. * @default 0
  39540. */
  39541. this.near = near;
  39542. /**
  39543. * All results returned are further away than near. Near can't be negative.
  39544. *
  39545. * @type {number}
  39546. * @default Infinity
  39547. */
  39548. this.far = far;
  39549. /**
  39550. * The camera to use when raycasting against view-dependent objects such as
  39551. * billboarded objects like sprites. This field can be set manually or
  39552. * is set when calling `setFromCamera()`.
  39553. *
  39554. * @type {?Camera}
  39555. * @default null
  39556. */
  39557. this.camera = null;
  39558. /**
  39559. * Allows to selectively ignore 3D objects when performing intersection tests.
  39560. * The following code example ensures that only 3D objects on layer `1` will be
  39561. * honored by raycaster.
  39562. * ```js
  39563. * raycaster.layers.set( 1 );
  39564. * object.layers.enable( 1 );
  39565. * ```
  39566. *
  39567. * @type {Layers}
  39568. */
  39569. this.layers = new Layers();
  39570. /**
  39571. * A parameter object that configures the raycasting. It has the structure:
  39572. *
  39573. * ```
  39574. * {
  39575. * Mesh: {},
  39576. * Line: { threshold: 1 },
  39577. * LOD: {},
  39578. * Points: { threshold: 1 },
  39579. * Sprite: {}
  39580. * }
  39581. * ```
  39582. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  39583. *
  39584. * @type {Object}
  39585. */
  39586. this.params = {
  39587. Mesh: {},
  39588. Line: { threshold: 1 },
  39589. LOD: {},
  39590. Points: { threshold: 1 },
  39591. Sprite: {}
  39592. };
  39593. }
  39594. /**
  39595. * Updates the ray with a new origin and direction by copying the values from the arguments.
  39596. *
  39597. * @param {Vector3} origin - The origin vector where the ray casts from.
  39598. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39599. */
  39600. set( origin, direction ) {
  39601. // direction is assumed to be normalized (for accurate distance calculations)
  39602. this.ray.set( origin, direction );
  39603. }
  39604. /**
  39605. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  39606. *
  39607. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  39608. * X and Y components should be between `-1` and `1`.
  39609. * @param {Camera} camera - The camera from which the ray should originate.
  39610. */
  39611. setFromCamera( coords, camera ) {
  39612. if ( camera.isPerspectiveCamera ) {
  39613. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  39614. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  39615. this.camera = camera;
  39616. } else if ( camera.isOrthographicCamera ) {
  39617. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  39618. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  39619. this.camera = camera;
  39620. } else {
  39621. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  39622. }
  39623. }
  39624. /**
  39625. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  39626. *
  39627. * @param {WebXRController} controller - The controller to copy the position and direction from.
  39628. * @return {Raycaster} A reference to this raycaster.
  39629. */
  39630. setFromXRController( controller ) {
  39631. _matrix.identity().extractRotation( controller.matrixWorld );
  39632. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  39633. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  39634. return this;
  39635. }
  39636. /**
  39637. * The intersection point of a raycaster intersection test.
  39638. * @typedef {Object} Raycaster~Intersection
  39639. * @property {number} distance - The distance from the ray's origin to the intersection point.
  39640. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  39641. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  39642. * @property {Vector3} point - The intersection point, in world coordinates.
  39643. * @property {Object} face - The face that has been intersected.
  39644. * @property {number} faceIndex - The face index.
  39645. * @property {Object3D} object - The 3D object that has been intersected.
  39646. * @property {Vector2} uv - U,V coordinates at point of intersection.
  39647. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  39648. * @property {Vector3} uv1 - Interpolated normal vector at point of intersection.
  39649. * @property {number} instanceId - The index number of the instance where the ray
  39650. * intersects the {@link InstancedMesh}.
  39651. */
  39652. /**
  39653. * Checks all intersection between the ray and the object with or without the
  39654. * descendants. Intersections are returned sorted by distance, closest first.
  39655. *
  39656. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  39657. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  39658. * differently to ray casting than lines or points.
  39659. *
  39660. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  39661. * to be detected; intersections of the ray passing through the back of a face will not
  39662. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  39663. * to `THREE.DoubleSide`.
  39664. *
  39665. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  39666. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39667. * Otherwise it only checks intersection with the object.
  39668. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39669. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39670. */
  39671. intersectObject( object, recursive = true, intersects = [] ) {
  39672. intersect( object, this, intersects, recursive );
  39673. intersects.sort( ascSort );
  39674. return intersects;
  39675. }
  39676. /**
  39677. * Checks all intersection between the ray and the objects with or without
  39678. * the descendants. Intersections are returned sorted by distance, closest first.
  39679. *
  39680. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  39681. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39682. * Otherwise it only checks intersection with the object.
  39683. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39684. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39685. */
  39686. intersectObjects( objects, recursive = true, intersects = [] ) {
  39687. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  39688. intersect( objects[ i ], this, intersects, recursive );
  39689. }
  39690. intersects.sort( ascSort );
  39691. return intersects;
  39692. }
  39693. }
  39694. function ascSort( a, b ) {
  39695. return a.distance - b.distance;
  39696. }
  39697. function intersect( object, raycaster, intersects, recursive ) {
  39698. let propagate = true;
  39699. if ( object.layers.test( raycaster.layers ) ) {
  39700. const result = object.raycast( raycaster, intersects );
  39701. if ( result === false ) propagate = false;
  39702. }
  39703. if ( propagate === true && recursive === true ) {
  39704. const children = object.children;
  39705. for ( let i = 0, l = children.length; i < l; i ++ ) {
  39706. intersect( children[ i ], raycaster, intersects, true );
  39707. }
  39708. }
  39709. }
  39710. /**
  39711. * This class is an alternative to {@link Clock} with a different API design and behavior.
  39712. * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
  39713. *
  39714. * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
  39715. * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
  39716. * - The class can make use of the Page Visibility API to avoid large time delta values when the app
  39717. * is inactive (e.g. tab switched or browser hidden).
  39718. *
  39719. * ```js
  39720. * const timer = new Timer();
  39721. * timer.connect( document ); // use Page Visibility API
  39722. * ```
  39723. */
  39724. class Timer {
  39725. /**
  39726. * Constructs a new timer.
  39727. */
  39728. constructor() {
  39729. this._previousTime = 0;
  39730. this._currentTime = 0;
  39731. this._startTime = performance.now();
  39732. this._delta = 0;
  39733. this._elapsed = 0;
  39734. this._timescale = 1;
  39735. this._document = null;
  39736. this._pageVisibilityHandler = null;
  39737. }
  39738. /**
  39739. * Connect the timer to the given document.Calling this method is not mandatory to
  39740. * use the timer but enables the usage of the Page Visibility API to avoid large time
  39741. * delta values.
  39742. *
  39743. * @param {Document} document - The document.
  39744. */
  39745. connect( document ) {
  39746. this._document = document;
  39747. // use Page Visibility API to avoid large time delta values
  39748. if ( document.hidden !== undefined ) {
  39749. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  39750. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  39751. }
  39752. }
  39753. /**
  39754. * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
  39755. */
  39756. disconnect() {
  39757. if ( this._pageVisibilityHandler !== null ) {
  39758. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  39759. this._pageVisibilityHandler = null;
  39760. }
  39761. this._document = null;
  39762. }
  39763. /**
  39764. * Returns the time delta in seconds.
  39765. *
  39766. * @return {number} The time delta in second.
  39767. */
  39768. getDelta() {
  39769. return this._delta / 1000;
  39770. }
  39771. /**
  39772. * Returns the elapsed time in seconds.
  39773. *
  39774. * @return {number} The elapsed time in second.
  39775. */
  39776. getElapsed() {
  39777. return this._elapsed / 1000;
  39778. }
  39779. /**
  39780. * Returns the timescale.
  39781. *
  39782. * @return {number} The timescale.
  39783. */
  39784. getTimescale() {
  39785. return this._timescale;
  39786. }
  39787. /**
  39788. * Sets the given timescale which scale the time delta computation
  39789. * in `update()`.
  39790. *
  39791. * @param {number} timescale - The timescale to set.
  39792. * @return {Timer} A reference to this timer.
  39793. */
  39794. setTimescale( timescale ) {
  39795. this._timescale = timescale;
  39796. return this;
  39797. }
  39798. /**
  39799. * Resets the time computation for the current simulation step.
  39800. *
  39801. * @return {Timer} A reference to this timer.
  39802. */
  39803. reset() {
  39804. this._currentTime = performance.now() - this._startTime;
  39805. return this;
  39806. }
  39807. /**
  39808. * Can be used to free all internal resources. Usually called when
  39809. * the timer instance isn't required anymore.
  39810. */
  39811. dispose() {
  39812. this.disconnect();
  39813. }
  39814. /**
  39815. * Updates the internal state of the timer. This method should be called
  39816. * once per simulation step and before you perform queries against the timer
  39817. * (e.g. via `getDelta()`).
  39818. *
  39819. * @param {number} timestamp - The current time in milliseconds. Can be obtained
  39820. * from the `requestAnimationFrame` callback argument. If not provided, the current
  39821. * time will be determined with `performance.now`.
  39822. * @return {Timer} A reference to this timer.
  39823. */
  39824. update( timestamp ) {
  39825. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  39826. this._delta = 0;
  39827. } else {
  39828. this._previousTime = this._currentTime;
  39829. this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime;
  39830. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  39831. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  39832. }
  39833. return this;
  39834. }
  39835. }
  39836. function handleVisibilityChange() {
  39837. if ( this._document.hidden === false ) this.reset();
  39838. }
  39839. /**
  39840. * This class can be used to represent points in 3D space as
  39841. * [Spherical coordinates]{@link https://en.wikipedia.org/wiki/Spherical_coordinate_system}.
  39842. */
  39843. class Spherical {
  39844. /**
  39845. * Constructs a new spherical.
  39846. *
  39847. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  39848. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  39849. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  39850. */
  39851. constructor( radius = 1, phi = 0, theta = 0 ) {
  39852. /**
  39853. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  39854. *
  39855. * @type {number}
  39856. * @default 1
  39857. */
  39858. this.radius = radius;
  39859. /**
  39860. * The polar angle in radians from the y (up) axis.
  39861. *
  39862. * @type {number}
  39863. * @default 0
  39864. */
  39865. this.phi = phi;
  39866. /**
  39867. * The equator/azimuthal angle in radians around the y (up) axis.
  39868. *
  39869. * @type {number}
  39870. * @default 0
  39871. */
  39872. this.theta = theta;
  39873. }
  39874. /**
  39875. * Sets the spherical components by copying the given values.
  39876. *
  39877. * @param {number} radius - The radius.
  39878. * @param {number} phi - The polar angle.
  39879. * @param {number} theta - The azimuthal angle.
  39880. * @return {Spherical} A reference to this spherical.
  39881. */
  39882. set( radius, phi, theta ) {
  39883. this.radius = radius;
  39884. this.phi = phi;
  39885. this.theta = theta;
  39886. return this;
  39887. }
  39888. /**
  39889. * Copies the values of the given spherical to this instance.
  39890. *
  39891. * @param {Spherical} other - The spherical to copy.
  39892. * @return {Spherical} A reference to this spherical.
  39893. */
  39894. copy( other ) {
  39895. this.radius = other.radius;
  39896. this.phi = other.phi;
  39897. this.theta = other.theta;
  39898. return this;
  39899. }
  39900. /**
  39901. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  39902. * `0.000001`.
  39903. *
  39904. * @return {Spherical} A reference to this spherical.
  39905. */
  39906. makeSafe() {
  39907. const EPS = 0.000001;
  39908. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  39909. return this;
  39910. }
  39911. /**
  39912. * Sets the spherical components from the given vector which is assumed to hold
  39913. * Cartesian coordinates.
  39914. *
  39915. * @param {Vector3} v - The vector to set.
  39916. * @return {Spherical} A reference to this spherical.
  39917. */
  39918. setFromVector3( v ) {
  39919. return this.setFromCartesianCoords( v.x, v.y, v.z );
  39920. }
  39921. /**
  39922. * Sets the spherical components from the given Cartesian coordinates.
  39923. *
  39924. * @param {number} x - The x value.
  39925. * @param {number} y - The y value.
  39926. * @param {number} z - The z value.
  39927. * @return {Spherical} A reference to this spherical.
  39928. */
  39929. setFromCartesianCoords( x, y, z ) {
  39930. this.radius = Math.sqrt( x * x + y * y + z * z );
  39931. if ( this.radius === 0 ) {
  39932. this.theta = 0;
  39933. this.phi = 0;
  39934. } else {
  39935. this.theta = Math.atan2( x, z );
  39936. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  39937. }
  39938. return this;
  39939. }
  39940. /**
  39941. * Returns a new spherical with copied values from this instance.
  39942. *
  39943. * @return {Spherical} A clone of this instance.
  39944. */
  39945. clone() {
  39946. return new this.constructor().copy( this );
  39947. }
  39948. }
  39949. /**
  39950. * This class can be used to represent points in 3D space as
  39951. * [Cylindrical coordinates]{@link https://en.wikipedia.org/wiki/Cylindrical_coordinate_system}.
  39952. */
  39953. class Cylindrical {
  39954. /**
  39955. * Constructs a new cylindrical.
  39956. *
  39957. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  39958. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  39959. * @param {number} [y=0] - The height above the x-z plane.
  39960. */
  39961. constructor( radius = 1, theta = 0, y = 0 ) {
  39962. /**
  39963. * The distance from the origin to a point in the x-z plane.
  39964. *
  39965. * @type {number}
  39966. * @default 1
  39967. */
  39968. this.radius = radius;
  39969. /**
  39970. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  39971. *
  39972. * @type {number}
  39973. * @default 0
  39974. */
  39975. this.theta = theta;
  39976. /**
  39977. * The height above the x-z plane.
  39978. *
  39979. * @type {number}
  39980. * @default 0
  39981. */
  39982. this.y = y;
  39983. }
  39984. /**
  39985. * Sets the cylindrical components by copying the given values.
  39986. *
  39987. * @param {number} radius - The radius.
  39988. * @param {number} theta - The theta angle.
  39989. * @param {number} y - The height value.
  39990. * @return {Cylindrical} A reference to this cylindrical.
  39991. */
  39992. set( radius, theta, y ) {
  39993. this.radius = radius;
  39994. this.theta = theta;
  39995. this.y = y;
  39996. return this;
  39997. }
  39998. /**
  39999. * Copies the values of the given cylindrical to this instance.
  40000. *
  40001. * @param {Cylindrical} other - The cylindrical to copy.
  40002. * @return {Cylindrical} A reference to this cylindrical.
  40003. */
  40004. copy( other ) {
  40005. this.radius = other.radius;
  40006. this.theta = other.theta;
  40007. this.y = other.y;
  40008. return this;
  40009. }
  40010. /**
  40011. * Sets the cylindrical components from the given vector which is assumed to hold
  40012. * Cartesian coordinates.
  40013. *
  40014. * @param {Vector3} v - The vector to set.
  40015. * @return {Cylindrical} A reference to this cylindrical.
  40016. */
  40017. setFromVector3( v ) {
  40018. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40019. }
  40020. /**
  40021. * Sets the cylindrical components from the given Cartesian coordinates.
  40022. *
  40023. * @param {number} x - The x value.
  40024. * @param {number} y - The x value.
  40025. * @param {number} z - The x value.
  40026. * @return {Cylindrical} A reference to this cylindrical.
  40027. */
  40028. setFromCartesianCoords( x, y, z ) {
  40029. this.radius = Math.sqrt( x * x + z * z );
  40030. this.theta = Math.atan2( x, z );
  40031. this.y = y;
  40032. return this;
  40033. }
  40034. /**
  40035. * Returns a new cylindrical with copied values from this instance.
  40036. *
  40037. * @return {Cylindrical} A clone of this instance.
  40038. */
  40039. clone() {
  40040. return new this.constructor().copy( this );
  40041. }
  40042. }
  40043. /**
  40044. * Represents a 2x2 matrix.
  40045. *
  40046. * A Note on Row-Major and Column-Major Ordering:
  40047. *
  40048. * The constructor and {@link Matrix2#set} method take arguments in
  40049. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  40050. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  40051. * This means that calling:
  40052. * ```js
  40053. * const m = new THREE.Matrix2();
  40054. * m.set( 11, 12,
  40055. * 21, 22 );
  40056. * ```
  40057. * will result in the elements array containing:
  40058. * ```js
  40059. * m.elements = [ 11, 21,
  40060. * 12, 22 ];
  40061. * ```
  40062. * and internally all calculations are performed using column-major ordering.
  40063. * However, as the actual ordering makes no difference mathematically and
  40064. * most people are used to thinking about matrices in row-major order, the
  40065. * three.js documentation shows matrices in row-major order. Just bear in
  40066. * mind that if you are reading the source code, you'll have to take the
  40067. * transpose of any matrices outlined here to make sense of the calculations.
  40068. */
  40069. class Matrix2 {
  40070. /**
  40071. * Constructs a new 2x2 matrix. The arguments are supposed to be
  40072. * in row-major order. If no arguments are provided, the constructor
  40073. * initializes the matrix as an identity matrix.
  40074. *
  40075. * @param {number} [n11] - 1-1 matrix element.
  40076. * @param {number} [n12] - 1-2 matrix element.
  40077. * @param {number} [n21] - 2-1 matrix element.
  40078. * @param {number} [n22] - 2-2 matrix element.
  40079. */
  40080. constructor( n11, n12, n21, n22 ) {
  40081. /**
  40082. * This flag can be used for type testing.
  40083. *
  40084. * @type {boolean}
  40085. * @readonly
  40086. * @default true
  40087. */
  40088. Matrix2.prototype.isMatrix2 = true;
  40089. /**
  40090. * A column-major list of matrix values.
  40091. *
  40092. * @type {Array<number>}
  40093. */
  40094. this.elements = [
  40095. 1, 0,
  40096. 0, 1,
  40097. ];
  40098. if ( n11 !== undefined ) {
  40099. this.set( n11, n12, n21, n22 );
  40100. }
  40101. }
  40102. /**
  40103. * Sets this matrix to the 2x2 identity matrix.
  40104. *
  40105. * @return {Matrix2} A reference to this matrix.
  40106. */
  40107. identity() {
  40108. this.set(
  40109. 1, 0,
  40110. 0, 1,
  40111. );
  40112. return this;
  40113. }
  40114. /**
  40115. * Sets the elements of the matrix from the given array.
  40116. *
  40117. * @param {Array<number>} array - The matrix elements in column-major order.
  40118. * @param {number} [offset=0] - Index of the first element in the array.
  40119. * @return {Matrix2} A reference to this matrix.
  40120. */
  40121. fromArray( array, offset = 0 ) {
  40122. for ( let i = 0; i < 4; i ++ ) {
  40123. this.elements[ i ] = array[ i + offset ];
  40124. }
  40125. return this;
  40126. }
  40127. /**
  40128. * Sets the elements of the matrix.The arguments are supposed to be
  40129. * in row-major order.
  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. * @return {Matrix2} A reference to this matrix.
  40136. */
  40137. set( n11, n12, n21, n22 ) {
  40138. const te = this.elements;
  40139. te[ 0 ] = n11; te[ 2 ] = n12;
  40140. te[ 1 ] = n21; te[ 3 ] = n22;
  40141. return this;
  40142. }
  40143. }
  40144. const _vector$4 = /*@__PURE__*/ new Vector2();
  40145. /**
  40146. * Represents an axis-aligned bounding box (AABB) in 2D space.
  40147. */
  40148. class Box2 {
  40149. /**
  40150. * Constructs a new bounding box.
  40151. *
  40152. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  40153. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  40154. */
  40155. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  40156. /**
  40157. * This flag can be used for type testing.
  40158. *
  40159. * @type {boolean}
  40160. * @readonly
  40161. * @default true
  40162. */
  40163. this.isBox2 = true;
  40164. /**
  40165. * The lower boundary of the box.
  40166. *
  40167. * @type {Vector2}
  40168. */
  40169. this.min = min;
  40170. /**
  40171. * The upper boundary of the box.
  40172. *
  40173. * @type {Vector2}
  40174. */
  40175. this.max = max;
  40176. }
  40177. /**
  40178. * Sets the lower and upper boundaries of this box.
  40179. * Please note that this method only copies the values from the given objects.
  40180. *
  40181. * @param {Vector2} min - The lower boundary of the box.
  40182. * @param {Vector2} max - The upper boundary of the box.
  40183. * @return {Box2} A reference to this bounding box.
  40184. */
  40185. set( min, max ) {
  40186. this.min.copy( min );
  40187. this.max.copy( max );
  40188. return this;
  40189. }
  40190. /**
  40191. * Sets the upper and lower bounds of this box so it encloses the position data
  40192. * in the given array.
  40193. *
  40194. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  40195. * @return {Box2} A reference to this bounding box.
  40196. */
  40197. setFromPoints( points ) {
  40198. this.makeEmpty();
  40199. for ( let i = 0, il = points.length; i < il; i ++ ) {
  40200. this.expandByPoint( points[ i ] );
  40201. }
  40202. return this;
  40203. }
  40204. /**
  40205. * Centers this box on the given center vector and sets this box's width, height and
  40206. * depth to the given size values.
  40207. *
  40208. * @param {Vector2} center - The center of the box.
  40209. * @param {Vector2} size - The x and y dimensions of the box.
  40210. * @return {Box2} A reference to this bounding box.
  40211. */
  40212. setFromCenterAndSize( center, size ) {
  40213. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  40214. this.min.copy( center ).sub( halfSize );
  40215. this.max.copy( center ).add( halfSize );
  40216. return this;
  40217. }
  40218. /**
  40219. * Returns a new box with copied values from this instance.
  40220. *
  40221. * @return {Box2} A clone of this instance.
  40222. */
  40223. clone() {
  40224. return new this.constructor().copy( this );
  40225. }
  40226. /**
  40227. * Copies the values of the given box to this instance.
  40228. *
  40229. * @param {Box2} box - The box to copy.
  40230. * @return {Box2} A reference to this bounding box.
  40231. */
  40232. copy( box ) {
  40233. this.min.copy( box.min );
  40234. this.max.copy( box.max );
  40235. return this;
  40236. }
  40237. /**
  40238. * Makes this box empty which means in encloses a zero space in 2D.
  40239. *
  40240. * @return {Box2} A reference to this bounding box.
  40241. */
  40242. makeEmpty() {
  40243. this.min.x = this.min.y = + Infinity;
  40244. this.max.x = this.max.y = - Infinity;
  40245. return this;
  40246. }
  40247. /**
  40248. * Returns true if this box includes zero points within its bounds.
  40249. * Note that a box with equal lower and upper bounds still includes one
  40250. * point, the one both bounds share.
  40251. *
  40252. * @return {boolean} Whether this box is empty or not.
  40253. */
  40254. isEmpty() {
  40255. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  40256. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  40257. }
  40258. /**
  40259. * Returns the center point of this box.
  40260. *
  40261. * @param {Vector2} target - The target vector that is used to store the method's result.
  40262. * @return {Vector2} The center point.
  40263. */
  40264. getCenter( target ) {
  40265. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  40266. }
  40267. /**
  40268. * Returns the dimensions of this box.
  40269. *
  40270. * @param {Vector2} target - The target vector that is used to store the method's result.
  40271. * @return {Vector2} The size.
  40272. */
  40273. getSize( target ) {
  40274. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  40275. }
  40276. /**
  40277. * Expands the boundaries of this box to include the given point.
  40278. *
  40279. * @param {Vector2} point - The point that should be included by the bounding box.
  40280. * @return {Box2} A reference to this bounding box.
  40281. */
  40282. expandByPoint( point ) {
  40283. this.min.min( point );
  40284. this.max.max( point );
  40285. return this;
  40286. }
  40287. /**
  40288. * Expands this box equilaterally by the given vector. The width of this
  40289. * box will be expanded by the x component of the vector in both
  40290. * directions. The height of this box will be expanded by the y component of
  40291. * the vector in both directions.
  40292. *
  40293. * @param {Vector2} vector - The vector that should expand the bounding box.
  40294. * @return {Box2} A reference to this bounding box.
  40295. */
  40296. expandByVector( vector ) {
  40297. this.min.sub( vector );
  40298. this.max.add( vector );
  40299. return this;
  40300. }
  40301. /**
  40302. * Expands each dimension of the box by the given scalar. If negative, the
  40303. * dimensions of the box will be contracted.
  40304. *
  40305. * @param {number} scalar - The scalar value that should expand the bounding box.
  40306. * @return {Box2} A reference to this bounding box.
  40307. */
  40308. expandByScalar( scalar ) {
  40309. this.min.addScalar( - scalar );
  40310. this.max.addScalar( scalar );
  40311. return this;
  40312. }
  40313. /**
  40314. * Returns `true` if the given point lies within or on the boundaries of this box.
  40315. *
  40316. * @param {Vector2} point - The point to test.
  40317. * @return {boolean} Whether the bounding box contains the given point or not.
  40318. */
  40319. containsPoint( point ) {
  40320. return point.x >= this.min.x && point.x <= this.max.x &&
  40321. point.y >= this.min.y && point.y <= this.max.y;
  40322. }
  40323. /**
  40324. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  40325. * If this box and the given one are identical, this function also returns `true`.
  40326. *
  40327. * @param {Box2} box - The bounding box to test.
  40328. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  40329. */
  40330. containsBox( box ) {
  40331. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  40332. this.min.y <= box.min.y && box.max.y <= this.max.y;
  40333. }
  40334. /**
  40335. * Returns a point as a proportion of this box's width and height.
  40336. *
  40337. * @param {Vector2} point - A point in 2D space.
  40338. * @param {Vector2} target - The target vector that is used to store the method's result.
  40339. * @return {Vector2} A point as a proportion of this box's width and height.
  40340. */
  40341. getParameter( point, target ) {
  40342. // This can potentially have a divide by zero if the box
  40343. // has a size dimension of 0.
  40344. return target.set(
  40345. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  40346. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  40347. );
  40348. }
  40349. /**
  40350. * Returns `true` if the given bounding box intersects with this bounding box.
  40351. *
  40352. * @param {Box2} box - The bounding box to test.
  40353. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  40354. */
  40355. intersectsBox( box ) {
  40356. // using 4 splitting planes to rule out intersections
  40357. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  40358. box.max.y >= this.min.y && box.min.y <= this.max.y;
  40359. }
  40360. /**
  40361. * Clamps the given point within the bounds of this box.
  40362. *
  40363. * @param {Vector2} point - The point to clamp.
  40364. * @param {Vector2} target - The target vector that is used to store the method's result.
  40365. * @return {Vector2} The clamped point.
  40366. */
  40367. clampPoint( point, target ) {
  40368. return target.copy( point ).clamp( this.min, this.max );
  40369. }
  40370. /**
  40371. * Returns the euclidean distance from any edge of this box to the specified point. If
  40372. * the given point lies inside of this box, the distance will be `0`.
  40373. *
  40374. * @param {Vector2} point - The point to compute the distance to.
  40375. * @return {number} The euclidean distance.
  40376. */
  40377. distanceToPoint( point ) {
  40378. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  40379. }
  40380. /**
  40381. * Computes the intersection of this bounding box and the given one, setting the upper
  40382. * bound of this box to the lesser of the two boxes' upper bounds and the
  40383. * lower bound of this box to the greater of the two boxes' lower bounds. If
  40384. * there's no overlap, makes this box empty.
  40385. *
  40386. * @param {Box2} box - The bounding box to intersect with.
  40387. * @return {Box2} A reference to this bounding box.
  40388. */
  40389. intersect( box ) {
  40390. this.min.max( box.min );
  40391. this.max.min( box.max );
  40392. if ( this.isEmpty() ) this.makeEmpty();
  40393. return this;
  40394. }
  40395. /**
  40396. * Computes the union of this box and another and the given one, setting the upper
  40397. * bound of this box to the greater of the two boxes' upper bounds and the
  40398. * lower bound of this box to the lesser of the two boxes' lower bounds.
  40399. *
  40400. * @param {Box2} box - The bounding box that will be unioned with this instance.
  40401. * @return {Box2} A reference to this bounding box.
  40402. */
  40403. union( box ) {
  40404. this.min.min( box.min );
  40405. this.max.max( box.max );
  40406. return this;
  40407. }
  40408. /**
  40409. * Adds the given offset to both the upper and lower bounds of this bounding box,
  40410. * effectively moving it in 2D space.
  40411. *
  40412. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  40413. * @return {Box2} A reference to this bounding box.
  40414. */
  40415. translate( offset ) {
  40416. this.min.add( offset );
  40417. this.max.add( offset );
  40418. return this;
  40419. }
  40420. /**
  40421. * Returns `true` if this bounding box is equal with the given one.
  40422. *
  40423. * @param {Box2} box - The box to test for equality.
  40424. * @return {boolean} Whether this bounding box is equal with the given one.
  40425. */
  40426. equals( box ) {
  40427. return box.min.equals( this.min ) && box.max.equals( this.max );
  40428. }
  40429. }
  40430. const _startP = /*@__PURE__*/ new Vector3();
  40431. const _startEnd = /*@__PURE__*/ new Vector3();
  40432. const _d1 = /*@__PURE__*/ new Vector3();
  40433. const _d2 = /*@__PURE__*/ new Vector3();
  40434. const _r = /*@__PURE__*/ new Vector3();
  40435. const _c1 = /*@__PURE__*/ new Vector3();
  40436. const _c2 = /*@__PURE__*/ new Vector3();
  40437. /**
  40438. * An analytical line segment in 3D space represented by a start and end point.
  40439. */
  40440. class Line3 {
  40441. /**
  40442. * Constructs a new line segment.
  40443. *
  40444. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  40445. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  40446. */
  40447. constructor( start = new Vector3(), end = new Vector3() ) {
  40448. /**
  40449. * Start of the line segment.
  40450. *
  40451. * @type {Vector3}
  40452. */
  40453. this.start = start;
  40454. /**
  40455. * End of the line segment.
  40456. *
  40457. * @type {Vector3}
  40458. */
  40459. this.end = end;
  40460. }
  40461. /**
  40462. * Sets the start and end values by copying the given vectors.
  40463. *
  40464. * @param {Vector3} start - The start point.
  40465. * @param {Vector3} end - The end point.
  40466. * @return {Line3} A reference to this line segment.
  40467. */
  40468. set( start, end ) {
  40469. this.start.copy( start );
  40470. this.end.copy( end );
  40471. return this;
  40472. }
  40473. /**
  40474. * Copies the values of the given line segment to this instance.
  40475. *
  40476. * @param {Line3} line - The line segment to copy.
  40477. * @return {Line3} A reference to this line segment.
  40478. */
  40479. copy( line ) {
  40480. this.start.copy( line.start );
  40481. this.end.copy( line.end );
  40482. return this;
  40483. }
  40484. /**
  40485. * Returns the center of the line segment.
  40486. *
  40487. * @param {Vector3} target - The target vector that is used to store the method's result.
  40488. * @return {Vector3} The center point.
  40489. */
  40490. getCenter( target ) {
  40491. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  40492. }
  40493. /**
  40494. * Returns the delta vector of the line segment's start and end point.
  40495. *
  40496. * @param {Vector3} target - The target vector that is used to store the method's result.
  40497. * @return {Vector3} The delta vector.
  40498. */
  40499. delta( target ) {
  40500. return target.subVectors( this.end, this.start );
  40501. }
  40502. /**
  40503. * Returns the squared Euclidean distance between the line' start and end point.
  40504. *
  40505. * @return {number} The squared Euclidean distance.
  40506. */
  40507. distanceSq() {
  40508. return this.start.distanceToSquared( this.end );
  40509. }
  40510. /**
  40511. * Returns the Euclidean distance between the line' start and end point.
  40512. *
  40513. * @return {number} The Euclidean distance.
  40514. */
  40515. distance() {
  40516. return this.start.distanceTo( this.end );
  40517. }
  40518. /**
  40519. * Returns a vector at a certain position along the line segment.
  40520. *
  40521. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  40522. * @param {Vector3} target - The target vector that is used to store the method's result.
  40523. * @return {Vector3} The delta vector.
  40524. */
  40525. at( t, target ) {
  40526. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40527. }
  40528. /**
  40529. * Returns a point parameter based on the closest point as projected on the line segment.
  40530. *
  40531. * @param {Vector3} point - The point for which to return a point parameter.
  40532. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40533. * @return {number} The point parameter.
  40534. */
  40535. closestPointToPointParameter( point, clampToLine ) {
  40536. _startP.subVectors( point, this.start );
  40537. _startEnd.subVectors( this.end, this.start );
  40538. const startEnd2 = _startEnd.dot( _startEnd );
  40539. const startEnd_startP = _startEnd.dot( _startP );
  40540. let t = startEnd_startP / startEnd2;
  40541. if ( clampToLine ) {
  40542. t = clamp( t, 0, 1 );
  40543. }
  40544. return t;
  40545. }
  40546. /**
  40547. * Returns the closest point on the line for a given point.
  40548. *
  40549. * @param {Vector3} point - The point to compute the closest point on the line for.
  40550. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40551. * @param {Vector3} target - The target vector that is used to store the method's result.
  40552. * @return {Vector3} The closest point on the line.
  40553. */
  40554. closestPointToPoint( point, clampToLine, target ) {
  40555. const t = this.closestPointToPointParameter( point, clampToLine );
  40556. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40557. }
  40558. /**
  40559. * Returns the closest squared distance between this line segment and the given one.
  40560. *
  40561. * @param {Line3} line - The line segment to compute the closest squared distance to.
  40562. * @param {Vector3} [c1] - The closest point on this line segment.
  40563. * @param {Vector3} [c2] - The closest point on the given line segment.
  40564. * @return {number} The squared distance between this line segment and the given one.
  40565. */
  40566. distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) {
  40567. // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9
  40568. // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
  40569. // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
  40570. // distance between between S1(s) and S2(t)
  40571. const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length
  40572. let s, t;
  40573. const p1 = this.start;
  40574. const p2 = line.start;
  40575. const q1 = this.end;
  40576. const q2 = line.end;
  40577. _d1.subVectors( q1, p1 ); // Direction vector of segment S1
  40578. _d2.subVectors( q2, p2 ); // Direction vector of segment S2
  40579. _r.subVectors( p1, p2 );
  40580. const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative
  40581. const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative
  40582. const f = _d2.dot( _r );
  40583. // Check if either or both segments degenerate into points
  40584. if ( a <= EPSILON && e <= EPSILON ) {
  40585. // Both segments degenerate into points
  40586. c1.copy( p1 );
  40587. c2.copy( p2 );
  40588. c1.sub( c2 );
  40589. return c1.dot( c1 );
  40590. }
  40591. if ( a <= EPSILON ) {
  40592. // First segment degenerates into a point
  40593. s = 0;
  40594. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  40595. t = clamp( t, 0, 1 );
  40596. } else {
  40597. const c = _d1.dot( _r );
  40598. if ( e <= EPSILON ) {
  40599. // Second segment degenerates into a point
  40600. t = 0;
  40601. s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a
  40602. } else {
  40603. // The general nondegenerate case starts here
  40604. const b = _d1.dot( _d2 );
  40605. const denom = a * e - b * b; // Always nonnegative
  40606. // If segments not parallel, compute closest point on L1 to L2 and
  40607. // clamp to segment S1. Else pick arbitrary s (here 0)
  40608. if ( denom !== 0 ) {
  40609. s = clamp( ( b * f - c * e ) / denom, 0, 1 );
  40610. } else {
  40611. s = 0;
  40612. }
  40613. // Compute point on L2 closest to S1(s) using
  40614. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  40615. t = ( b * s + f ) / e;
  40616. // If t in [0,1] done. Else clamp t, recompute s for the new value
  40617. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  40618. // and clamp s to [0, 1]
  40619. if ( t < 0 ) {
  40620. t = 0.;
  40621. s = clamp( - c / a, 0, 1 );
  40622. } else if ( t > 1 ) {
  40623. t = 1;
  40624. s = clamp( ( b - c ) / a, 0, 1 );
  40625. }
  40626. }
  40627. }
  40628. c1.copy( p1 ).add( _d1.multiplyScalar( s ) );
  40629. c2.copy( p2 ).add( _d2.multiplyScalar( t ) );
  40630. c1.sub( c2 );
  40631. return c1.dot( c1 );
  40632. }
  40633. /**
  40634. * Applies a 4x4 transformation matrix to this line segment.
  40635. *
  40636. * @param {Matrix4} matrix - The transformation matrix.
  40637. * @return {Line3} A reference to this line segment.
  40638. */
  40639. applyMatrix4( matrix ) {
  40640. this.start.applyMatrix4( matrix );
  40641. this.end.applyMatrix4( matrix );
  40642. return this;
  40643. }
  40644. /**
  40645. * Returns `true` if this line segment is equal with the given one.
  40646. *
  40647. * @param {Line3} line - The line segment to test for equality.
  40648. * @return {boolean} Whether this line segment is equal with the given one.
  40649. */
  40650. equals( line ) {
  40651. return line.start.equals( this.start ) && line.end.equals( this.end );
  40652. }
  40653. /**
  40654. * Returns a new line segment with copied values from this instance.
  40655. *
  40656. * @return {Line3} A clone of this instance.
  40657. */
  40658. clone() {
  40659. return new this.constructor().copy( this );
  40660. }
  40661. }
  40662. const _vector$3 = /*@__PURE__*/ new Vector3();
  40663. /**
  40664. * This displays a cone shaped helper object for a {@link SpotLight}.
  40665. *
  40666. * ```js
  40667. * const spotLight = new THREE.SpotLight( 0xffffff );
  40668. * spotLight.position.set( 10, 10, 10 );
  40669. * scene.add( spotLight );
  40670. *
  40671. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  40672. * scene.add( spotLightHelper );
  40673. * ```
  40674. *
  40675. * @augments Object3D
  40676. */
  40677. class SpotLightHelper extends Object3D {
  40678. /**
  40679. * Constructs a new spot light helper.
  40680. *
  40681. * @param {HemisphereLight} light - The light to be visualized.
  40682. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40683. * the color of the light.
  40684. */
  40685. constructor( light, color ) {
  40686. super();
  40687. /**
  40688. * The light being visualized.
  40689. *
  40690. * @type {SpotLight}
  40691. */
  40692. this.light = light;
  40693. this.matrixAutoUpdate = false;
  40694. /**
  40695. * The color parameter passed in the constructor.
  40696. * If not set, the helper will take the color of the light.
  40697. *
  40698. * @type {number|Color|string}
  40699. */
  40700. this.color = color;
  40701. this.type = 'SpotLightHelper';
  40702. const geometry = new BufferGeometry();
  40703. const positions = [
  40704. 0, 0, 0, 0, 0, 1,
  40705. 0, 0, 0, 1, 0, 1,
  40706. 0, 0, 0, -1, 0, 1,
  40707. 0, 0, 0, 0, 1, 1,
  40708. 0, 0, 0, 0, -1, 1
  40709. ];
  40710. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  40711. const p1 = ( i / l ) * Math.PI * 2;
  40712. const p2 = ( j / l ) * Math.PI * 2;
  40713. positions.push(
  40714. Math.cos( p1 ), Math.sin( p1 ), 1,
  40715. Math.cos( p2 ), Math.sin( p2 ), 1
  40716. );
  40717. }
  40718. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  40719. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  40720. this.cone = new LineSegments( geometry, material );
  40721. this.add( this.cone );
  40722. this.update();
  40723. }
  40724. /**
  40725. * Frees the GPU-related resources allocated by this instance. Call this
  40726. * method whenever this instance is no longer used in your app.
  40727. */
  40728. dispose() {
  40729. this.cone.geometry.dispose();
  40730. this.cone.material.dispose();
  40731. }
  40732. /**
  40733. * Updates the helper to match the position and direction of the
  40734. * light being visualized.
  40735. */
  40736. update() {
  40737. this.light.updateWorldMatrix( true, false );
  40738. this.light.target.updateWorldMatrix( true, false );
  40739. // update the local matrix based on the parent and light target transforms
  40740. if ( this.parent ) {
  40741. this.parent.updateWorldMatrix( true );
  40742. this.matrix
  40743. .copy( this.parent.matrixWorld )
  40744. .invert()
  40745. .multiply( this.light.matrixWorld );
  40746. } else {
  40747. this.matrix.copy( this.light.matrixWorld );
  40748. }
  40749. this.matrixWorld.copy( this.light.matrixWorld );
  40750. const coneLength = this.light.distance ? this.light.distance : 1000;
  40751. const coneWidth = coneLength * Math.tan( this.light.angle );
  40752. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  40753. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  40754. this.cone.lookAt( _vector$3 );
  40755. if ( this.color !== undefined ) {
  40756. this.cone.material.color.set( this.color );
  40757. } else {
  40758. this.cone.material.color.copy( this.light.color );
  40759. }
  40760. }
  40761. }
  40762. const _vector$2 = /*@__PURE__*/ new Vector3();
  40763. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  40764. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  40765. /**
  40766. * A helper object to assist with visualizing a {@link Skeleton}.
  40767. *
  40768. * ```js
  40769. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  40770. * scene.add( helper );
  40771. * ```
  40772. *
  40773. * @augments LineSegments
  40774. */
  40775. class SkeletonHelper extends LineSegments {
  40776. /**
  40777. * Constructs a new skeleton helper.
  40778. *
  40779. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  40780. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  40781. */
  40782. constructor( object ) {
  40783. const bones = getBoneList( object );
  40784. const geometry = new BufferGeometry();
  40785. const vertices = [];
  40786. const colors = [];
  40787. for ( let i = 0; i < bones.length; i ++ ) {
  40788. const bone = bones[ i ];
  40789. if ( bone.parent && bone.parent.isBone ) {
  40790. vertices.push( 0, 0, 0 );
  40791. vertices.push( 0, 0, 0 );
  40792. colors.push( 0, 0, 0 );
  40793. colors.push( 0, 0, 0 );
  40794. }
  40795. }
  40796. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40797. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  40798. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  40799. super( geometry, material );
  40800. /**
  40801. * This flag can be used for type testing.
  40802. *
  40803. * @type {boolean}
  40804. * @readonly
  40805. * @default true
  40806. */
  40807. this.isSkeletonHelper = true;
  40808. this.type = 'SkeletonHelper';
  40809. /**
  40810. * The object being visualized.
  40811. *
  40812. * @type {Object3D}
  40813. */
  40814. this.root = object;
  40815. /**
  40816. * The list of bones that the helper visualizes.
  40817. *
  40818. * @type {Array<Bone>}
  40819. */
  40820. this.bones = bones;
  40821. this.matrix = object.matrixWorld;
  40822. this.matrixAutoUpdate = false;
  40823. // colors
  40824. const color1 = new Color( 0x0000ff );
  40825. const color2 = new Color( 0x00ff00 );
  40826. this.setColors( color1, color2 );
  40827. }
  40828. updateMatrixWorld( force ) {
  40829. const bones = this.bones;
  40830. const geometry = this.geometry;
  40831. const position = geometry.getAttribute( 'position' );
  40832. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  40833. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  40834. const bone = bones[ i ];
  40835. if ( bone.parent && bone.parent.isBone ) {
  40836. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  40837. _vector$2.setFromMatrixPosition( _boneMatrix );
  40838. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  40839. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  40840. _vector$2.setFromMatrixPosition( _boneMatrix );
  40841. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  40842. j += 2;
  40843. }
  40844. }
  40845. geometry.getAttribute( 'position' ).needsUpdate = true;
  40846. super.updateMatrixWorld( force );
  40847. }
  40848. /**
  40849. * Defines the colors of the helper.
  40850. *
  40851. * @param {Color} color1 - The first line color for each bone.
  40852. * @param {Color} color2 - The second line color for each bone.
  40853. * @return {SkeletonHelper} A reference to this helper.
  40854. */
  40855. setColors( color1, color2 ) {
  40856. const geometry = this.geometry;
  40857. const colorAttribute = geometry.getAttribute( 'color' );
  40858. for ( let i = 0; i < colorAttribute.count; i += 2 ) {
  40859. colorAttribute.setXYZ( i, color1.r, color1.g, color1.b );
  40860. colorAttribute.setXYZ( i + 1, color2.r, color2.g, color2.b );
  40861. }
  40862. colorAttribute.needsUpdate = true;
  40863. return this;
  40864. }
  40865. /**
  40866. * Frees the GPU-related resources allocated by this instance. Call this
  40867. * method whenever this instance is no longer used in your app.
  40868. */
  40869. dispose() {
  40870. this.geometry.dispose();
  40871. this.material.dispose();
  40872. }
  40873. }
  40874. function getBoneList( object ) {
  40875. const boneList = [];
  40876. if ( object.isBone === true ) {
  40877. boneList.push( object );
  40878. }
  40879. for ( let i = 0; i < object.children.length; i ++ ) {
  40880. boneList.push( ...getBoneList( object.children[ i ] ) );
  40881. }
  40882. return boneList;
  40883. }
  40884. /**
  40885. * This displays a helper object consisting of a spherical mesh for
  40886. * visualizing an instance of {@link PointLight}.
  40887. *
  40888. * ```js
  40889. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  40890. * pointLight.position.set( 10, 10, 10 );
  40891. * scene.add( pointLight );
  40892. *
  40893. * const sphereSize = 1;
  40894. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  40895. * scene.add( pointLightHelper );
  40896. * ```
  40897. *
  40898. * @augments Mesh
  40899. */
  40900. class PointLightHelper extends Mesh {
  40901. /**
  40902. * Constructs a new point light helper.
  40903. *
  40904. * @param {PointLight} light - The light to be visualized.
  40905. * @param {number} [sphereSize=1] - The size of the sphere helper.
  40906. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40907. * the color of the light.
  40908. */
  40909. constructor( light, sphereSize, color ) {
  40910. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  40911. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  40912. super( geometry, material );
  40913. /**
  40914. * The light being visualized.
  40915. *
  40916. * @type {HemisphereLight}
  40917. */
  40918. this.light = light;
  40919. /**
  40920. * The color parameter passed in the constructor.
  40921. * If not set, the helper will take the color of the light.
  40922. *
  40923. * @type {number|Color|string}
  40924. */
  40925. this.color = color;
  40926. this.type = 'PointLightHelper';
  40927. this.matrix = this.light.matrixWorld;
  40928. this.matrixAutoUpdate = false;
  40929. this.update();
  40930. /*
  40931. // TODO: delete this comment?
  40932. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  40933. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  40934. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  40935. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  40936. const d = light.distance;
  40937. if ( d === 0.0 ) {
  40938. this.lightDistance.visible = false;
  40939. } else {
  40940. this.lightDistance.scale.set( d, d, d );
  40941. }
  40942. this.add( this.lightDistance );
  40943. */
  40944. }
  40945. /**
  40946. * Frees the GPU-related resources allocated by this instance. Call this
  40947. * method whenever this instance is no longer used in your app.
  40948. */
  40949. dispose() {
  40950. this.geometry.dispose();
  40951. this.material.dispose();
  40952. }
  40953. /**
  40954. * Updates the helper to match the position of the
  40955. * light being visualized.
  40956. */
  40957. update() {
  40958. this.light.updateWorldMatrix( true, false );
  40959. if ( this.color !== undefined ) {
  40960. this.material.color.set( this.color );
  40961. } else {
  40962. this.material.color.copy( this.light.color );
  40963. }
  40964. /*
  40965. const d = this.light.distance;
  40966. if ( d === 0.0 ) {
  40967. this.lightDistance.visible = false;
  40968. } else {
  40969. this.lightDistance.visible = true;
  40970. this.lightDistance.scale.set( d, d, d );
  40971. }
  40972. */
  40973. }
  40974. }
  40975. const _vector$1 = /*@__PURE__*/ new Vector3();
  40976. const _color1 = /*@__PURE__*/ new Color();
  40977. const _color2 = /*@__PURE__*/ new Color();
  40978. /**
  40979. * Creates a visual aid consisting of a spherical mesh for a
  40980. * given {@link HemisphereLight}.
  40981. *
  40982. * ```js
  40983. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  40984. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  40985. * scene.add( helper );
  40986. * ```
  40987. *
  40988. * @augments Object3D
  40989. */
  40990. class HemisphereLightHelper extends Object3D {
  40991. /**
  40992. * Constructs a new hemisphere light helper.
  40993. *
  40994. * @param {HemisphereLight} light - The light to be visualized.
  40995. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  40996. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40997. * the color of the light.
  40998. */
  40999. constructor( light, size, color ) {
  41000. super();
  41001. /**
  41002. * The light being visualized.
  41003. *
  41004. * @type {HemisphereLight}
  41005. */
  41006. this.light = light;
  41007. this.matrix = light.matrixWorld;
  41008. this.matrixAutoUpdate = false;
  41009. /**
  41010. * The color parameter passed in the constructor.
  41011. * If not set, the helper will take the color of the light.
  41012. *
  41013. * @type {number|Color|string}
  41014. */
  41015. this.color = color;
  41016. this.type = 'HemisphereLightHelper';
  41017. const geometry = new OctahedronGeometry( size );
  41018. geometry.rotateY( Math.PI * 0.5 );
  41019. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41020. if ( this.color === undefined ) this.material.vertexColors = true;
  41021. const position = geometry.getAttribute( 'position' );
  41022. const colors = new Float32Array( position.count * 3 );
  41023. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  41024. this.add( new Mesh( geometry, this.material ) );
  41025. this.update();
  41026. }
  41027. /**
  41028. * Frees the GPU-related resources allocated by this instance. Call this
  41029. * method whenever this instance is no longer used in your app.
  41030. */
  41031. dispose() {
  41032. this.children[ 0 ].geometry.dispose();
  41033. this.children[ 0 ].material.dispose();
  41034. }
  41035. /**
  41036. * Updates the helper to match the position and direction of the
  41037. * light being visualized.
  41038. */
  41039. update() {
  41040. const mesh = this.children[ 0 ];
  41041. if ( this.color !== undefined ) {
  41042. this.material.color.set( this.color );
  41043. } else {
  41044. const colors = mesh.geometry.getAttribute( 'color' );
  41045. _color1.copy( this.light.color );
  41046. _color2.copy( this.light.groundColor );
  41047. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  41048. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  41049. colors.setXYZ( i, color.r, color.g, color.b );
  41050. }
  41051. colors.needsUpdate = true;
  41052. }
  41053. this.light.updateWorldMatrix( true, false );
  41054. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  41055. }
  41056. }
  41057. /**
  41058. * The helper is an object to define grids. Grids are two-dimensional
  41059. * arrays of lines.
  41060. *
  41061. * ```js
  41062. * const size = 10;
  41063. * const divisions = 10;
  41064. *
  41065. * const gridHelper = new THREE.GridHelper( size, divisions );
  41066. * scene.add( gridHelper );
  41067. * ```
  41068. *
  41069. * @augments LineSegments
  41070. */
  41071. class GridHelper extends LineSegments {
  41072. /**
  41073. * Constructs a new grid helper.
  41074. *
  41075. * @param {number} [size=10] - The size of the grid.
  41076. * @param {number} [divisions=10] - The number of divisions across the grid.
  41077. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  41078. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  41079. */
  41080. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  41081. color1 = new Color( color1 );
  41082. color2 = new Color( color2 );
  41083. const center = divisions / 2;
  41084. const step = size / divisions;
  41085. const halfSize = size / 2;
  41086. const vertices = [], colors = [];
  41087. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  41088. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  41089. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  41090. const color = i === center ? color1 : color2;
  41091. color.toArray( colors, j ); j += 3;
  41092. color.toArray( colors, j ); j += 3;
  41093. color.toArray( colors, j ); j += 3;
  41094. color.toArray( colors, j ); j += 3;
  41095. }
  41096. const geometry = new BufferGeometry();
  41097. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41098. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41099. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41100. super( geometry, material );
  41101. this.type = 'GridHelper';
  41102. }
  41103. /**
  41104. * Frees the GPU-related resources allocated by this instance. Call this
  41105. * method whenever this instance is no longer used in your app.
  41106. */
  41107. dispose() {
  41108. this.geometry.dispose();
  41109. this.material.dispose();
  41110. }
  41111. }
  41112. /**
  41113. * This helper is an object to define polar grids. Grids are
  41114. * two-dimensional arrays of lines.
  41115. *
  41116. * ```js
  41117. * const radius = 10;
  41118. * const sectors = 16;
  41119. * const rings = 8;
  41120. * const divisions = 64;
  41121. *
  41122. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  41123. * scene.add( helper );
  41124. * ```
  41125. *
  41126. * @augments LineSegments
  41127. */
  41128. class PolarGridHelper extends LineSegments {
  41129. /**
  41130. * Constructs a new polar grid helper.
  41131. *
  41132. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  41133. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  41134. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  41135. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  41136. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  41137. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  41138. */
  41139. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  41140. color1 = new Color( color1 );
  41141. color2 = new Color( color2 );
  41142. const vertices = [];
  41143. const colors = [];
  41144. // create the sectors
  41145. if ( sectors > 1 ) {
  41146. for ( let i = 0; i < sectors; i ++ ) {
  41147. const v = ( i / sectors ) * ( Math.PI * 2 );
  41148. const x = Math.sin( v ) * radius;
  41149. const z = Math.cos( v ) * radius;
  41150. vertices.push( 0, 0, 0 );
  41151. vertices.push( x, 0, z );
  41152. const color = ( i & 1 ) ? color1 : color2;
  41153. colors.push( color.r, color.g, color.b );
  41154. colors.push( color.r, color.g, color.b );
  41155. }
  41156. }
  41157. // create the rings
  41158. for ( let i = 0; i < rings; i ++ ) {
  41159. const color = ( i & 1 ) ? color1 : color2;
  41160. const r = radius - ( radius / rings * i );
  41161. for ( let j = 0; j < divisions; j ++ ) {
  41162. // first vertex
  41163. let v = ( j / divisions ) * ( Math.PI * 2 );
  41164. let x = Math.sin( v ) * r;
  41165. let z = Math.cos( v ) * r;
  41166. vertices.push( x, 0, z );
  41167. colors.push( color.r, color.g, color.b );
  41168. // second vertex
  41169. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  41170. x = Math.sin( v ) * r;
  41171. z = Math.cos( v ) * r;
  41172. vertices.push( x, 0, z );
  41173. colors.push( color.r, color.g, color.b );
  41174. }
  41175. }
  41176. const geometry = new BufferGeometry();
  41177. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41178. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41179. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41180. super( geometry, material );
  41181. this.type = 'PolarGridHelper';
  41182. }
  41183. /**
  41184. * Frees the GPU-related resources allocated by this instance. Call this
  41185. * method whenever this instance is no longer used in your app.
  41186. */
  41187. dispose() {
  41188. this.geometry.dispose();
  41189. this.material.dispose();
  41190. }
  41191. }
  41192. const _v1 = /*@__PURE__*/ new Vector3();
  41193. const _v2 = /*@__PURE__*/ new Vector3();
  41194. const _v3 = /*@__PURE__*/ new Vector3();
  41195. /**
  41196. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  41197. * effect on the scene. This consists of plane and a line representing the
  41198. * light's position and direction.
  41199. *
  41200. * ```js
  41201. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  41202. * scene.add( light );
  41203. *
  41204. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  41205. * scene.add( helper );
  41206. * ```
  41207. *
  41208. * @augments Object3D
  41209. */
  41210. class DirectionalLightHelper extends Object3D {
  41211. /**
  41212. * Constructs a new directional light helper.
  41213. *
  41214. * @param {DirectionalLight} light - The light to be visualized.
  41215. * @param {number} [size=1] - The dimensions of the plane.
  41216. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41217. * the color of the light.
  41218. */
  41219. constructor( light, size, color ) {
  41220. super();
  41221. /**
  41222. * The light being visualized.
  41223. *
  41224. * @type {DirectionalLight}
  41225. */
  41226. this.light = light;
  41227. this.matrix = light.matrixWorld;
  41228. this.matrixAutoUpdate = false;
  41229. /**
  41230. * The color parameter passed in the constructor.
  41231. * If not set, the helper will take the color of the light.
  41232. *
  41233. * @type {number|Color|string}
  41234. */
  41235. this.color = color;
  41236. this.type = 'DirectionalLightHelper';
  41237. if ( size === undefined ) size = 1;
  41238. let geometry = new BufferGeometry();
  41239. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  41240. - size, size, 0,
  41241. size, size, 0,
  41242. size, - size, 0,
  41243. - size, - size, 0,
  41244. - size, size, 0
  41245. ], 3 ) );
  41246. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41247. /**
  41248. * Contains the line showing the location of the directional light.
  41249. *
  41250. * @type {Line}
  41251. */
  41252. this.lightPlane = new Line( geometry, material );
  41253. this.add( this.lightPlane );
  41254. geometry = new BufferGeometry();
  41255. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  41256. /**
  41257. * Represents the target line of the directional light.
  41258. *
  41259. * @type {Line}
  41260. */
  41261. this.targetLine = new Line( geometry, material );
  41262. this.add( this.targetLine );
  41263. this.update();
  41264. }
  41265. /**
  41266. * Frees the GPU-related resources allocated by this instance. Call this
  41267. * method whenever this instance is no longer used in your app.
  41268. */
  41269. dispose() {
  41270. this.lightPlane.geometry.dispose();
  41271. this.lightPlane.material.dispose();
  41272. this.targetLine.geometry.dispose();
  41273. this.targetLine.material.dispose();
  41274. }
  41275. /**
  41276. * Updates the helper to match the position and direction of the
  41277. * light being visualized.
  41278. */
  41279. update() {
  41280. this.light.updateWorldMatrix( true, false );
  41281. this.light.target.updateWorldMatrix( true, false );
  41282. _v1.setFromMatrixPosition( this.light.matrixWorld );
  41283. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  41284. _v3.subVectors( _v2, _v1 );
  41285. this.lightPlane.lookAt( _v2 );
  41286. if ( this.color !== undefined ) {
  41287. this.lightPlane.material.color.set( this.color );
  41288. this.targetLine.material.color.set( this.color );
  41289. } else {
  41290. this.lightPlane.material.color.copy( this.light.color );
  41291. this.targetLine.material.color.copy( this.light.color );
  41292. }
  41293. this.targetLine.lookAt( _v2 );
  41294. this.targetLine.scale.z = _v3.length();
  41295. }
  41296. }
  41297. const _vector = /*@__PURE__*/ new Vector3();
  41298. const _camera = /*@__PURE__*/ new Camera();
  41299. /**
  41300. * This helps with visualizing what a camera contains in its frustum. It
  41301. * visualizes the frustum of a camera using a line segments.
  41302. *
  41303. * Based on frustum visualization in [lightgl.js shadowmap example]{@link https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html}.
  41304. *
  41305. * `CameraHelper` must be a child of the scene.
  41306. *
  41307. * ```js
  41308. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  41309. * const helper = new THREE.CameraHelper( camera );
  41310. * scene.add( helper );
  41311. * ```
  41312. *
  41313. * @augments LineSegments
  41314. */
  41315. class CameraHelper extends LineSegments {
  41316. /**
  41317. * Constructs a new arrow helper.
  41318. *
  41319. * @param {Camera} camera - The camera to visualize.
  41320. */
  41321. constructor( camera ) {
  41322. const geometry = new BufferGeometry();
  41323. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  41324. const vertices = [];
  41325. const colors = [];
  41326. const pointMap = {};
  41327. // near
  41328. addLine( 'n1', 'n2' );
  41329. addLine( 'n2', 'n4' );
  41330. addLine( 'n4', 'n3' );
  41331. addLine( 'n3', 'n1' );
  41332. // far
  41333. addLine( 'f1', 'f2' );
  41334. addLine( 'f2', 'f4' );
  41335. addLine( 'f4', 'f3' );
  41336. addLine( 'f3', 'f1' );
  41337. // sides
  41338. addLine( 'n1', 'f1' );
  41339. addLine( 'n2', 'f2' );
  41340. addLine( 'n3', 'f3' );
  41341. addLine( 'n4', 'f4' );
  41342. // cone
  41343. addLine( 'p', 'n1' );
  41344. addLine( 'p', 'n2' );
  41345. addLine( 'p', 'n3' );
  41346. addLine( 'p', 'n4' );
  41347. // up
  41348. addLine( 'u1', 'u2' );
  41349. addLine( 'u2', 'u3' );
  41350. addLine( 'u3', 'u1' );
  41351. // target
  41352. addLine( 'c', 't' );
  41353. addLine( 'p', 'c' );
  41354. // cross
  41355. addLine( 'cn1', 'cn2' );
  41356. addLine( 'cn3', 'cn4' );
  41357. addLine( 'cf1', 'cf2' );
  41358. addLine( 'cf3', 'cf4' );
  41359. function addLine( a, b ) {
  41360. addPoint( a );
  41361. addPoint( b );
  41362. }
  41363. function addPoint( id ) {
  41364. vertices.push( 0, 0, 0 );
  41365. colors.push( 0, 0, 0 );
  41366. if ( pointMap[ id ] === undefined ) {
  41367. pointMap[ id ] = [];
  41368. }
  41369. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  41370. }
  41371. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41372. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41373. super( geometry, material );
  41374. this.type = 'CameraHelper';
  41375. /**
  41376. * The camera being visualized.
  41377. *
  41378. * @type {Camera}
  41379. */
  41380. this.camera = camera;
  41381. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  41382. this.matrix = camera.matrixWorld;
  41383. this.matrixAutoUpdate = false;
  41384. /**
  41385. * This contains the points used to visualize the camera.
  41386. *
  41387. * @type {Object<string,Array<number>>}
  41388. */
  41389. this.pointMap = pointMap;
  41390. this.update();
  41391. // colors
  41392. const colorFrustum = new Color( 0xffaa00 );
  41393. const colorCone = new Color( 0xff0000 );
  41394. const colorUp = new Color( 0x00aaff );
  41395. const colorTarget = new Color( 0xffffff );
  41396. const colorCross = new Color( 0x333333 );
  41397. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  41398. }
  41399. /**
  41400. * Defines the colors of the helper.
  41401. *
  41402. * @param {Color} frustum - The frustum line color.
  41403. * @param {Color} cone - The cone line color.
  41404. * @param {Color} up - The up line color.
  41405. * @param {Color} target - The target line color.
  41406. * @param {Color} cross - The cross line color.
  41407. * @return {CameraHelper} A reference to this helper.
  41408. */
  41409. setColors( frustum, cone, up, target, cross ) {
  41410. const geometry = this.geometry;
  41411. const colorAttribute = geometry.getAttribute( 'color' );
  41412. // near
  41413. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  41414. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  41415. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  41416. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  41417. // far
  41418. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  41419. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  41420. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  41421. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  41422. // sides
  41423. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  41424. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  41425. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  41426. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  41427. // cone
  41428. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  41429. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  41430. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  41431. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  41432. // up
  41433. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  41434. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  41435. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  41436. // target
  41437. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  41438. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  41439. // cross
  41440. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  41441. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  41442. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  41443. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  41444. colorAttribute.needsUpdate = true;
  41445. return this;
  41446. }
  41447. /**
  41448. * Updates the helper based on the projection matrix of the camera.
  41449. */
  41450. update() {
  41451. const geometry = this.geometry;
  41452. const pointMap = this.pointMap;
  41453. const w = 1, h = 1;
  41454. let nearZ, farZ;
  41455. // we need just camera projection matrix inverse
  41456. // world matrix must be identity
  41457. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  41458. // Adjust z values based on coordinate system
  41459. if ( this.camera.reversedDepth === true ) {
  41460. nearZ = 1;
  41461. farZ = 0;
  41462. } else {
  41463. if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) {
  41464. nearZ = -1;
  41465. farZ = 1;
  41466. } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) {
  41467. nearZ = 0;
  41468. farZ = 1;
  41469. } else {
  41470. throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem );
  41471. }
  41472. }
  41473. // center / target
  41474. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  41475. setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ );
  41476. // near
  41477. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  41478. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  41479. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  41480. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  41481. // far
  41482. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ );
  41483. setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ );
  41484. setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ );
  41485. setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ );
  41486. // up
  41487. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  41488. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  41489. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  41490. // cross
  41491. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ );
  41492. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ );
  41493. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ );
  41494. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ );
  41495. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  41496. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  41497. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  41498. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  41499. geometry.getAttribute( 'position' ).needsUpdate = true;
  41500. }
  41501. /**
  41502. * Frees the GPU-related resources allocated by this instance. Call this
  41503. * method whenever this instance is no longer used in your app.
  41504. */
  41505. dispose() {
  41506. this.geometry.dispose();
  41507. this.material.dispose();
  41508. }
  41509. }
  41510. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  41511. _vector.set( x, y, z ).unproject( camera );
  41512. const points = pointMap[ point ];
  41513. if ( points !== undefined ) {
  41514. const position = geometry.getAttribute( 'position' );
  41515. for ( let i = 0, l = points.length; i < l; i ++ ) {
  41516. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  41517. }
  41518. }
  41519. }
  41520. const _box = /*@__PURE__*/ new Box3();
  41521. /**
  41522. * Helper object to graphically show the world-axis-aligned bounding box
  41523. * around an object. The actual bounding box is handled with {@link Box3},
  41524. * this is just a visual helper for debugging. It can be automatically
  41525. * resized with {@link BoxHelper#update} when the object it's created from
  41526. * is transformed. Note that the object must have a geometry for this to work,
  41527. * so it won't work with sprites.
  41528. *
  41529. * ```js
  41530. * const sphere = new THREE.SphereGeometry();
  41531. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  41532. * const box = new THREE.BoxHelper( object, 0xffff00 );
  41533. * scene.add( box );
  41534. * ```
  41535. *
  41536. * @augments LineSegments
  41537. */
  41538. class BoxHelper extends LineSegments {
  41539. /**
  41540. * Constructs a new box helper.
  41541. *
  41542. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  41543. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41544. */
  41545. constructor( object, color = 0xffff00 ) {
  41546. 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 ] );
  41547. const positions = new Float32Array( 8 * 3 );
  41548. const geometry = new BufferGeometry();
  41549. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41550. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  41551. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41552. /**
  41553. * The 3D object being visualized.
  41554. *
  41555. * @type {Object3D}
  41556. */
  41557. this.object = object;
  41558. this.type = 'BoxHelper';
  41559. this.matrixAutoUpdate = false;
  41560. this.update();
  41561. }
  41562. /**
  41563. * Updates the helper's geometry to match the dimensions of the object,
  41564. * including any children.
  41565. */
  41566. update() {
  41567. if ( this.object !== undefined ) {
  41568. _box.setFromObject( this.object );
  41569. }
  41570. if ( _box.isEmpty() ) return;
  41571. const min = _box.min;
  41572. const max = _box.max;
  41573. /*
  41574. 5____4
  41575. 1/___0/|
  41576. | 6__|_7
  41577. 2/___3/
  41578. 0: max.x, max.y, max.z
  41579. 1: min.x, max.y, max.z
  41580. 2: min.x, min.y, max.z
  41581. 3: max.x, min.y, max.z
  41582. 4: max.x, max.y, min.z
  41583. 5: min.x, max.y, min.z
  41584. 6: min.x, min.y, min.z
  41585. 7: max.x, min.y, min.z
  41586. */
  41587. const position = this.geometry.attributes.position;
  41588. const array = position.array;
  41589. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  41590. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  41591. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  41592. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  41593. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  41594. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  41595. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  41596. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  41597. position.needsUpdate = true;
  41598. this.geometry.computeBoundingSphere();
  41599. }
  41600. /**
  41601. * Updates the wireframe box for the passed object.
  41602. *
  41603. * @param {Object3D} object - The 3D object to create the helper for.
  41604. * @return {BoxHelper} A reference to this instance.
  41605. */
  41606. setFromObject( object ) {
  41607. this.object = object;
  41608. this.update();
  41609. return this;
  41610. }
  41611. copy( source, recursive ) {
  41612. super.copy( source, recursive );
  41613. this.object = source.object;
  41614. return this;
  41615. }
  41616. /**
  41617. * Frees the GPU-related resources allocated by this instance. Call this
  41618. * method whenever this instance is no longer used in your app.
  41619. */
  41620. dispose() {
  41621. this.geometry.dispose();
  41622. this.material.dispose();
  41623. }
  41624. }
  41625. /**
  41626. * A helper object to visualize an instance of {@link Box3}.
  41627. *
  41628. * ```js
  41629. * const box = new THREE.Box3();
  41630. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  41631. *
  41632. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  41633. * scene.add( helper )
  41634. * ```
  41635. *
  41636. * @augments LineSegments
  41637. */
  41638. class Box3Helper extends LineSegments {
  41639. /**
  41640. * Constructs a new box3 helper.
  41641. *
  41642. * @param {Box3} box - The box to visualize.
  41643. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41644. */
  41645. constructor( box, color = 0xffff00 ) {
  41646. 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 ] );
  41647. 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 ];
  41648. const geometry = new BufferGeometry();
  41649. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41650. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41651. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41652. /**
  41653. * The box being visualized.
  41654. *
  41655. * @type {Box3}
  41656. */
  41657. this.box = box;
  41658. this.type = 'Box3Helper';
  41659. this.geometry.computeBoundingSphere();
  41660. }
  41661. updateMatrixWorld( force ) {
  41662. const box = this.box;
  41663. if ( box.isEmpty() ) return;
  41664. box.getCenter( this.position );
  41665. box.getSize( this.scale );
  41666. this.scale.multiplyScalar( 0.5 );
  41667. super.updateMatrixWorld( force );
  41668. }
  41669. /**
  41670. * Frees the GPU-related resources allocated by this instance. Call this
  41671. * method whenever this instance is no longer used in your app.
  41672. */
  41673. dispose() {
  41674. this.geometry.dispose();
  41675. this.material.dispose();
  41676. }
  41677. }
  41678. /**
  41679. * A helper object to visualize an instance of {@link Plane}.
  41680. *
  41681. * ```js
  41682. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  41683. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  41684. * scene.add( helper );
  41685. * ```
  41686. *
  41687. * @augments Line
  41688. */
  41689. class PlaneHelper extends Line {
  41690. /**
  41691. * Constructs a new plane helper.
  41692. *
  41693. * @param {Plane} plane - The plane to be visualized.
  41694. * @param {number} [size=1] - The side length of plane helper.
  41695. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  41696. */
  41697. constructor( plane, size = 1, hex = 0xffff00 ) {
  41698. const color = hex;
  41699. 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 ];
  41700. const geometry = new BufferGeometry();
  41701. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41702. geometry.computeBoundingSphere();
  41703. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41704. this.type = 'PlaneHelper';
  41705. /**
  41706. * The plane being visualized.
  41707. *
  41708. * @type {Plane}
  41709. */
  41710. this.plane = plane;
  41711. /**
  41712. * The side length of plane helper.
  41713. *
  41714. * @type {number}
  41715. * @default 1
  41716. */
  41717. this.size = size;
  41718. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  41719. const geometry2 = new BufferGeometry();
  41720. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  41721. geometry2.computeBoundingSphere();
  41722. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  41723. }
  41724. updateMatrixWorld( force ) {
  41725. this.position.set( 0, 0, 0 );
  41726. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  41727. this.lookAt( this.plane.normal );
  41728. this.translateZ( - this.plane.constant );
  41729. super.updateMatrixWorld( force );
  41730. }
  41731. /**
  41732. * Updates the helper to match the position and direction of the
  41733. * light being visualized.
  41734. */
  41735. dispose() {
  41736. this.geometry.dispose();
  41737. this.material.dispose();
  41738. this.children[ 0 ].geometry.dispose();
  41739. this.children[ 0 ].material.dispose();
  41740. }
  41741. }
  41742. const _axis = /*@__PURE__*/ new Vector3();
  41743. let _lineGeometry, _coneGeometry;
  41744. /**
  41745. * An 3D arrow object for visualizing directions.
  41746. *
  41747. * ```js
  41748. * const dir = new THREE.Vector3( 1, 2, 0 );
  41749. *
  41750. * //normalize the direction vector (convert to vector of length 1)
  41751. * dir.normalize();
  41752. *
  41753. * const origin = new THREE.Vector3( 0, 0, 0 );
  41754. * const length = 1;
  41755. * const hex = 0xffff00;
  41756. *
  41757. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  41758. * scene.add( arrowHelper );
  41759. * ```
  41760. *
  41761. * @augments Object3D
  41762. */
  41763. class ArrowHelper extends Object3D {
  41764. /**
  41765. * Constructs a new arrow helper.
  41766. *
  41767. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  41768. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  41769. * @param {number} [length=1] - Length of the arrow in world units.
  41770. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  41771. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  41772. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  41773. */
  41774. 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 ) {
  41775. super();
  41776. this.type = 'ArrowHelper';
  41777. if ( _lineGeometry === undefined ) {
  41778. _lineGeometry = new BufferGeometry();
  41779. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  41780. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  41781. _coneGeometry.translate( 0, -0.5, 0 );
  41782. }
  41783. this.position.copy( origin );
  41784. /**
  41785. * The line part of the arrow helper.
  41786. *
  41787. * @type {Line}
  41788. */
  41789. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41790. this.line.matrixAutoUpdate = false;
  41791. this.add( this.line );
  41792. /**
  41793. * The cone part of the arrow helper.
  41794. *
  41795. * @type {Mesh}
  41796. */
  41797. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  41798. this.cone.matrixAutoUpdate = false;
  41799. this.add( this.cone );
  41800. this.setDirection( dir );
  41801. this.setLength( length, headLength, headWidth );
  41802. }
  41803. /**
  41804. * Sets the direction of the helper.
  41805. *
  41806. * @param {Vector3} dir - The normalized direction vector.
  41807. */
  41808. setDirection( dir ) {
  41809. // dir is assumed to be normalized
  41810. if ( dir.y > 0.99999 ) {
  41811. this.quaternion.set( 0, 0, 0, 1 );
  41812. } else if ( dir.y < -0.99999 ) {
  41813. this.quaternion.set( 1, 0, 0, 0 );
  41814. } else {
  41815. _axis.set( dir.z, 0, - dir.x ).normalize();
  41816. const radians = Math.acos( dir.y );
  41817. this.quaternion.setFromAxisAngle( _axis, radians );
  41818. }
  41819. }
  41820. /**
  41821. * Sets the length of the helper.
  41822. *
  41823. * @param {number} length - Length of the arrow in world units.
  41824. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  41825. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  41826. */
  41827. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  41828. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  41829. this.line.updateMatrix();
  41830. this.cone.scale.set( headWidth, headLength, headWidth );
  41831. this.cone.position.y = length;
  41832. this.cone.updateMatrix();
  41833. }
  41834. /**
  41835. * Sets the color of the helper.
  41836. *
  41837. * @param {number|Color|string} color - The color to set.
  41838. */
  41839. setColor( color ) {
  41840. this.line.material.color.set( color );
  41841. this.cone.material.color.set( color );
  41842. }
  41843. copy( source ) {
  41844. super.copy( source, false );
  41845. this.line.copy( source.line );
  41846. this.cone.copy( source.cone );
  41847. return this;
  41848. }
  41849. /**
  41850. * Frees the GPU-related resources allocated by this instance. Call this
  41851. * method whenever this instance is no longer used in your app.
  41852. */
  41853. dispose() {
  41854. this.line.geometry.dispose();
  41855. this.line.material.dispose();
  41856. this.cone.geometry.dispose();
  41857. this.cone.material.dispose();
  41858. }
  41859. }
  41860. /**
  41861. * An axis object to visualize the 3 axes in a simple way.
  41862. * The X axis is red. The Y axis is green. The Z axis is blue.
  41863. *
  41864. * ```js
  41865. * const axesHelper = new THREE.AxesHelper( 5 );
  41866. * scene.add( axesHelper );
  41867. * ```
  41868. *
  41869. * @augments LineSegments
  41870. */
  41871. class AxesHelper extends LineSegments {
  41872. /**
  41873. * Constructs a new axes helper.
  41874. *
  41875. * @param {number} [size=1] - Size of the lines representing the axes.
  41876. */
  41877. constructor( size = 1 ) {
  41878. const vertices = [
  41879. 0, 0, 0, size, 0, 0,
  41880. 0, 0, 0, 0, size, 0,
  41881. 0, 0, 0, 0, 0, size
  41882. ];
  41883. const colors = [
  41884. 1, 0, 0, 1, 0.6, 0,
  41885. 0, 1, 0, 0.6, 1, 0,
  41886. 0, 0, 1, 0, 0.6, 1
  41887. ];
  41888. const geometry = new BufferGeometry();
  41889. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41890. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41891. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41892. super( geometry, material );
  41893. this.type = 'AxesHelper';
  41894. }
  41895. /**
  41896. * Defines the colors of the axes helper.
  41897. *
  41898. * @param {number|Color|string} xAxisColor - The color for the x axis.
  41899. * @param {number|Color|string} yAxisColor - The color for the y axis.
  41900. * @param {number|Color|string} zAxisColor - The color for the z axis.
  41901. * @return {AxesHelper} A reference to this axes helper.
  41902. */
  41903. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  41904. const color = new Color();
  41905. const array = this.geometry.attributes.color.array;
  41906. color.set( xAxisColor );
  41907. color.toArray( array, 0 );
  41908. color.toArray( array, 3 );
  41909. color.set( yAxisColor );
  41910. color.toArray( array, 6 );
  41911. color.toArray( array, 9 );
  41912. color.set( zAxisColor );
  41913. color.toArray( array, 12 );
  41914. color.toArray( array, 15 );
  41915. this.geometry.attributes.color.needsUpdate = true;
  41916. return this;
  41917. }
  41918. /**
  41919. * Frees the GPU-related resources allocated by this instance. Call this
  41920. * method whenever this instance is no longer used in your app.
  41921. */
  41922. dispose() {
  41923. this.geometry.dispose();
  41924. this.material.dispose();
  41925. }
  41926. }
  41927. /**
  41928. * This class is used to convert a series of paths to an array of
  41929. * shapes. It is specifically used in context of fonts and SVG.
  41930. */
  41931. class ShapePath {
  41932. /**
  41933. * Constructs a new shape path.
  41934. */
  41935. constructor() {
  41936. this.type = 'ShapePath';
  41937. /**
  41938. * The color of the shape.
  41939. *
  41940. * @type {Color}
  41941. */
  41942. this.color = new Color();
  41943. /**
  41944. * The paths that have been generated for this shape.
  41945. *
  41946. * @type {Array<Path>}
  41947. * @default null
  41948. */
  41949. this.subPaths = [];
  41950. /**
  41951. * The current path that is being generated.
  41952. *
  41953. * @type {?Path}
  41954. * @default null
  41955. */
  41956. this.currentPath = null;
  41957. }
  41958. /**
  41959. * Creates a new path and moves it current point to the given one.
  41960. *
  41961. * @param {number} x - The x coordinate.
  41962. * @param {number} y - The y coordinate.
  41963. * @return {ShapePath} A reference to this shape path.
  41964. */
  41965. moveTo( x, y ) {
  41966. this.currentPath = new Path();
  41967. this.subPaths.push( this.currentPath );
  41968. this.currentPath.moveTo( x, y );
  41969. return this;
  41970. }
  41971. /**
  41972. * Adds an instance of {@link LineCurve} to the path by connecting
  41973. * the current point with the given one.
  41974. *
  41975. * @param {number} x - The x coordinate of the end point.
  41976. * @param {number} y - The y coordinate of the end point.
  41977. * @return {ShapePath} A reference to this shape path.
  41978. */
  41979. lineTo( x, y ) {
  41980. this.currentPath.lineTo( x, y );
  41981. return this;
  41982. }
  41983. /**
  41984. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  41985. * the current point with the given one.
  41986. *
  41987. * @param {number} aCPx - The x coordinate of the control point.
  41988. * @param {number} aCPy - The y coordinate of the control point.
  41989. * @param {number} aX - The x coordinate of the end point.
  41990. * @param {number} aY - The y coordinate of the end point.
  41991. * @return {ShapePath} A reference to this shape path.
  41992. */
  41993. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  41994. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  41995. return this;
  41996. }
  41997. /**
  41998. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  41999. * the current point with the given one.
  42000. *
  42001. * @param {number} aCP1x - The x coordinate of the first control point.
  42002. * @param {number} aCP1y - The y coordinate of the first control point.
  42003. * @param {number} aCP2x - The x coordinate of the second control point.
  42004. * @param {number} aCP2y - The y coordinate of the second control point.
  42005. * @param {number} aX - The x coordinate of the end point.
  42006. * @param {number} aY - The y coordinate of the end point.
  42007. * @return {ShapePath} A reference to this shape path.
  42008. */
  42009. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  42010. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  42011. return this;
  42012. }
  42013. /**
  42014. * Adds an instance of {@link SplineCurve} to the path by connecting
  42015. * the current point with the given list of points.
  42016. *
  42017. * @param {Array<Vector2>} pts - An array of points in 2D space.
  42018. * @return {ShapePath} A reference to this shape path.
  42019. */
  42020. splineThru( pts ) {
  42021. this.currentPath.splineThru( pts );
  42022. return this;
  42023. }
  42024. /**
  42025. * Converts the paths into an array of shapes.
  42026. *
  42027. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  42028. * If this flag is set to `true`, then those are flipped.
  42029. * @return {Array<Shape>} An array of shapes.
  42030. */
  42031. toShapes( isCCW ) {
  42032. function toShapesNoHoles( inSubpaths ) {
  42033. const shapes = [];
  42034. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  42035. const tmpPath = inSubpaths[ i ];
  42036. const tmpShape = new Shape();
  42037. tmpShape.curves = tmpPath.curves;
  42038. shapes.push( tmpShape );
  42039. }
  42040. return shapes;
  42041. }
  42042. function isPointInsidePolygon( inPt, inPolygon ) {
  42043. const polyLen = inPolygon.length;
  42044. // inPt on polygon contour => immediate success or
  42045. // toggling of inside/outside at every single! intersection point of an edge
  42046. // with the horizontal line through inPt, left of inPt
  42047. // not counting lowerY endpoints of edges and whole edges on that line
  42048. let inside = false;
  42049. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  42050. let edgeLowPt = inPolygon[ p ];
  42051. let edgeHighPt = inPolygon[ q ];
  42052. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  42053. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  42054. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  42055. // not parallel
  42056. if ( edgeDy < 0 ) {
  42057. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  42058. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  42059. }
  42060. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  42061. if ( inPt.y === edgeLowPt.y ) {
  42062. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  42063. // continue; // no intersection or edgeLowPt => doesn't count !!!
  42064. } else {
  42065. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  42066. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  42067. if ( perpEdge < 0 ) continue;
  42068. inside = ! inside; // true intersection left of inPt
  42069. }
  42070. } else {
  42071. // parallel or collinear
  42072. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  42073. // edge lies on the same horizontal line as inPt
  42074. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  42075. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  42076. // continue;
  42077. }
  42078. }
  42079. return inside;
  42080. }
  42081. const isClockWise = ShapeUtils.isClockWise;
  42082. const subPaths = this.subPaths;
  42083. if ( subPaths.length === 0 ) return [];
  42084. let solid, tmpPath, tmpShape;
  42085. const shapes = [];
  42086. if ( subPaths.length === 1 ) {
  42087. tmpPath = subPaths[ 0 ];
  42088. tmpShape = new Shape();
  42089. tmpShape.curves = tmpPath.curves;
  42090. shapes.push( tmpShape );
  42091. return shapes;
  42092. }
  42093. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  42094. holesFirst = isCCW ? ! holesFirst : holesFirst;
  42095. // console.log("Holes first", holesFirst);
  42096. const betterShapeHoles = [];
  42097. const newShapes = [];
  42098. let newShapeHoles = [];
  42099. let mainIdx = 0;
  42100. let tmpPoints;
  42101. newShapes[ mainIdx ] = undefined;
  42102. newShapeHoles[ mainIdx ] = [];
  42103. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  42104. tmpPath = subPaths[ i ];
  42105. tmpPoints = tmpPath.getPoints();
  42106. solid = isClockWise( tmpPoints );
  42107. solid = isCCW ? ! solid : solid;
  42108. if ( solid ) {
  42109. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  42110. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  42111. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  42112. if ( holesFirst ) mainIdx ++;
  42113. newShapeHoles[ mainIdx ] = [];
  42114. //console.log('cw', i);
  42115. } else {
  42116. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  42117. //console.log('ccw', i);
  42118. }
  42119. }
  42120. // only Holes? -> probably all Shapes with wrong orientation
  42121. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  42122. if ( newShapes.length > 1 ) {
  42123. let ambiguous = false;
  42124. let toChange = 0;
  42125. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42126. betterShapeHoles[ sIdx ] = [];
  42127. }
  42128. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42129. const sho = newShapeHoles[ sIdx ];
  42130. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  42131. const ho = sho[ hIdx ];
  42132. let hole_unassigned = true;
  42133. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  42134. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  42135. if ( sIdx !== s2Idx ) toChange ++;
  42136. if ( hole_unassigned ) {
  42137. hole_unassigned = false;
  42138. betterShapeHoles[ s2Idx ].push( ho );
  42139. } else {
  42140. ambiguous = true;
  42141. }
  42142. }
  42143. }
  42144. if ( hole_unassigned ) {
  42145. betterShapeHoles[ sIdx ].push( ho );
  42146. }
  42147. }
  42148. }
  42149. if ( toChange > 0 && ambiguous === false ) {
  42150. newShapeHoles = betterShapeHoles;
  42151. }
  42152. }
  42153. let tmpHoles;
  42154. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  42155. tmpShape = newShapes[ i ].s;
  42156. shapes.push( tmpShape );
  42157. tmpHoles = newShapeHoles[ i ];
  42158. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  42159. tmpShape.holes.push( tmpHoles[ j ].h );
  42160. }
  42161. }
  42162. //console.log("shape", shapes);
  42163. return shapes;
  42164. }
  42165. }
  42166. /**
  42167. * Abstract base class for controls.
  42168. *
  42169. * @abstract
  42170. * @augments EventDispatcher
  42171. */
  42172. class Controls extends EventDispatcher {
  42173. /**
  42174. * Constructs a new controls instance.
  42175. *
  42176. * @param {Object3D} object - The object that is managed by the controls.
  42177. * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
  42178. */
  42179. constructor( object, domElement = null ) {
  42180. super();
  42181. /**
  42182. * The object that is managed by the controls.
  42183. *
  42184. * @type {Object3D}
  42185. */
  42186. this.object = object;
  42187. /**
  42188. * The HTML element used for event listeners.
  42189. *
  42190. * @type {?HTMLDOMElement}
  42191. * @default null
  42192. */
  42193. this.domElement = domElement;
  42194. /**
  42195. * Whether the controls responds to user input or not.
  42196. *
  42197. * @type {boolean}
  42198. * @default true
  42199. */
  42200. this.enabled = true;
  42201. /**
  42202. * The internal state of the controls.
  42203. *
  42204. * @type {number}
  42205. * @default -1
  42206. */
  42207. this.state = -1;
  42208. /**
  42209. * This object defines the keyboard input of the controls.
  42210. *
  42211. * @type {Object}
  42212. */
  42213. this.keys = {};
  42214. /**
  42215. * This object defines what type of actions are assigned to the available mouse buttons.
  42216. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  42217. *
  42218. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  42219. */
  42220. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  42221. /**
  42222. * This object defines what type of actions are assigned to what kind of touch interaction.
  42223. * It depends on the control implementation what kind of touch interaction and actions are supported.
  42224. *
  42225. * @type {{ONE: ?number, TWO: ?number}}
  42226. */
  42227. this.touches = { ONE: null, TWO: null };
  42228. }
  42229. /**
  42230. * Connects the controls to the DOM. This method has so called "side effects" since
  42231. * it adds the module's event listeners to the DOM.
  42232. *
  42233. * @param {HTMLDOMElement} element - The DOM element to connect to.
  42234. */
  42235. connect( element ) {
  42236. if ( element === undefined ) {
  42237. console.warn( 'THREE.Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  42238. return;
  42239. }
  42240. if ( this.domElement !== null ) this.disconnect();
  42241. this.domElement = element;
  42242. }
  42243. /**
  42244. * Disconnects the controls from the DOM.
  42245. */
  42246. disconnect() {}
  42247. /**
  42248. * Call this method if you no longer want use to the controls. It frees all internal
  42249. * resources and removes all event listeners.
  42250. */
  42251. dispose() {}
  42252. /**
  42253. * Controls should implement this method if they have to update their internal state
  42254. * per simulation step.
  42255. *
  42256. * @param {number} [delta] - The time delta in seconds.
  42257. */
  42258. update( /* delta */ ) {}
  42259. }
  42260. /**
  42261. * Scales the texture as large as possible within its surface without cropping
  42262. * or stretching the texture. The method preserves the original aspect ratio of
  42263. * the texture. Akin to CSS `object-fit: contain`
  42264. *
  42265. * @param {Texture} texture - The texture.
  42266. * @param {number} aspect - The texture's aspect ratio.
  42267. * @return {Texture} The updated texture.
  42268. */
  42269. function contain( texture, aspect ) {
  42270. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42271. if ( imageAspect > aspect ) {
  42272. texture.repeat.x = 1;
  42273. texture.repeat.y = imageAspect / aspect;
  42274. texture.offset.x = 0;
  42275. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42276. } else {
  42277. texture.repeat.x = aspect / imageAspect;
  42278. texture.repeat.y = 1;
  42279. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42280. texture.offset.y = 0;
  42281. }
  42282. return texture;
  42283. }
  42284. /**
  42285. * Scales the texture to the smallest possible size to fill the surface, leaving
  42286. * no empty space. The method preserves the original aspect ratio of the texture.
  42287. * Akin to CSS `object-fit: cover`.
  42288. *
  42289. * @param {Texture} texture - The texture.
  42290. * @param {number} aspect - The texture's aspect ratio.
  42291. * @return {Texture} The updated texture.
  42292. */
  42293. function cover( texture, aspect ) {
  42294. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42295. if ( imageAspect > aspect ) {
  42296. texture.repeat.x = aspect / imageAspect;
  42297. texture.repeat.y = 1;
  42298. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42299. texture.offset.y = 0;
  42300. } else {
  42301. texture.repeat.x = 1;
  42302. texture.repeat.y = imageAspect / aspect;
  42303. texture.offset.x = 0;
  42304. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42305. }
  42306. return texture;
  42307. }
  42308. /**
  42309. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42310. *
  42311. * @param {Texture} texture - The texture.
  42312. * @return {Texture} The updated texture.
  42313. */
  42314. function fill( texture ) {
  42315. texture.repeat.x = 1;
  42316. texture.repeat.y = 1;
  42317. texture.offset.x = 0;
  42318. texture.offset.y = 0;
  42319. return texture;
  42320. }
  42321. /**
  42322. * Determines how many bytes must be used to represent the texture.
  42323. *
  42324. * @param {number} width - The width of the texture.
  42325. * @param {number} height - The height of the texture.
  42326. * @param {number} format - The texture's format.
  42327. * @param {number} type - The texture's type.
  42328. * @return {number} The byte length.
  42329. */
  42330. function getByteLength( width, height, format, type ) {
  42331. const typeByteLength = getTextureTypeByteLength( type );
  42332. switch ( format ) {
  42333. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  42334. case AlphaFormat:
  42335. return width * height;
  42336. case RedFormat:
  42337. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42338. case RedIntegerFormat:
  42339. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42340. case RGFormat:
  42341. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42342. case RGIntegerFormat:
  42343. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42344. case RGBFormat:
  42345. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42346. case RGBAFormat:
  42347. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42348. case RGBAIntegerFormat:
  42349. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42350. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  42351. case RGB_S3TC_DXT1_Format:
  42352. case RGBA_S3TC_DXT1_Format:
  42353. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42354. case RGBA_S3TC_DXT3_Format:
  42355. case RGBA_S3TC_DXT5_Format:
  42356. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42357. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  42358. case RGB_PVRTC_2BPPV1_Format:
  42359. case RGBA_PVRTC_2BPPV1_Format:
  42360. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  42361. case RGB_PVRTC_4BPPV1_Format:
  42362. case RGBA_PVRTC_4BPPV1_Format:
  42363. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  42364. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  42365. case RGB_ETC1_Format:
  42366. case RGB_ETC2_Format:
  42367. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42368. case RGBA_ETC2_EAC_Format:
  42369. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42370. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  42371. case RGBA_ASTC_4x4_Format:
  42372. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42373. case RGBA_ASTC_5x4_Format:
  42374. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42375. case RGBA_ASTC_5x5_Format:
  42376. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42377. case RGBA_ASTC_6x5_Format:
  42378. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42379. case RGBA_ASTC_6x6_Format:
  42380. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42381. case RGBA_ASTC_8x5_Format:
  42382. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42383. case RGBA_ASTC_8x6_Format:
  42384. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42385. case RGBA_ASTC_8x8_Format:
  42386. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42387. case RGBA_ASTC_10x5_Format:
  42388. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42389. case RGBA_ASTC_10x6_Format:
  42390. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42391. case RGBA_ASTC_10x8_Format:
  42392. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42393. case RGBA_ASTC_10x10_Format:
  42394. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42395. case RGBA_ASTC_12x10_Format:
  42396. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42397. case RGBA_ASTC_12x12_Format:
  42398. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  42399. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  42400. case RGBA_BPTC_Format:
  42401. case RGB_BPTC_SIGNED_Format:
  42402. case RGB_BPTC_UNSIGNED_Format:
  42403. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42404. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  42405. case RED_RGTC1_Format:
  42406. case SIGNED_RED_RGTC1_Format:
  42407. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  42408. case RED_GREEN_RGTC2_Format:
  42409. case SIGNED_RED_GREEN_RGTC2_Format:
  42410. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42411. }
  42412. throw new Error(
  42413. `Unable to determine texture byte length for ${format} format.`,
  42414. );
  42415. }
  42416. function getTextureTypeByteLength( type ) {
  42417. switch ( type ) {
  42418. case UnsignedByteType:
  42419. case ByteType:
  42420. return { byteLength: 1, components: 1 };
  42421. case UnsignedShortType:
  42422. case ShortType:
  42423. case HalfFloatType:
  42424. return { byteLength: 2, components: 1 };
  42425. case UnsignedShort4444Type:
  42426. case UnsignedShort5551Type:
  42427. return { byteLength: 2, components: 4 };
  42428. case UnsignedIntType:
  42429. case IntType:
  42430. case FloatType:
  42431. return { byteLength: 4, components: 1 };
  42432. case UnsignedInt5999Type:
  42433. return { byteLength: 4, components: 3 };
  42434. }
  42435. throw new Error( `Unknown texture type ${type}.` );
  42436. }
  42437. /**
  42438. * A class containing utility functions for textures.
  42439. *
  42440. * @hideconstructor
  42441. */
  42442. class TextureUtils {
  42443. /**
  42444. * Scales the texture as large as possible within its surface without cropping
  42445. * or stretching the texture. The method preserves the original aspect ratio of
  42446. * the texture. Akin to CSS `object-fit: contain`
  42447. *
  42448. * @param {Texture} texture - The texture.
  42449. * @param {number} aspect - The texture's aspect ratio.
  42450. * @return {Texture} The updated texture.
  42451. */
  42452. static contain( texture, aspect ) {
  42453. return contain( texture, aspect );
  42454. }
  42455. /**
  42456. * Scales the texture to the smallest possible size to fill the surface, leaving
  42457. * no empty space. The method preserves the original aspect ratio of the texture.
  42458. * Akin to CSS `object-fit: cover`.
  42459. *
  42460. * @param {Texture} texture - The texture.
  42461. * @param {number} aspect - The texture's aspect ratio.
  42462. * @return {Texture} The updated texture.
  42463. */
  42464. static cover( texture, aspect ) {
  42465. return cover( texture, aspect );
  42466. }
  42467. /**
  42468. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42469. *
  42470. * @param {Texture} texture - The texture.
  42471. * @return {Texture} The updated texture.
  42472. */
  42473. static fill( texture ) {
  42474. return fill( texture );
  42475. }
  42476. /**
  42477. * Determines how many bytes must be used to represent the texture.
  42478. *
  42479. * @param {number} width - The width of the texture.
  42480. * @param {number} height - The height of the texture.
  42481. * @param {number} format - The texture's format.
  42482. * @param {number} type - The texture's type.
  42483. * @return {number} The byte length.
  42484. */
  42485. static getByteLength( width, height, format, type ) {
  42486. return getByteLength( width, height, format, type );
  42487. }
  42488. }
  42489. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  42490. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  42491. revision: REVISION,
  42492. } } ) );
  42493. }
  42494. if ( typeof window !== 'undefined' ) {
  42495. if ( window.__THREE__ ) {
  42496. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  42497. } else {
  42498. window.__THREE__ = REVISION;
  42499. }
  42500. }
  42501. function WebGLAnimation() {
  42502. let context = null;
  42503. let isAnimating = false;
  42504. let animationLoop = null;
  42505. let requestId = null;
  42506. function onAnimationFrame( time, frame ) {
  42507. animationLoop( time, frame );
  42508. requestId = context.requestAnimationFrame( onAnimationFrame );
  42509. }
  42510. return {
  42511. start: function () {
  42512. if ( isAnimating === true ) return;
  42513. if ( animationLoop === null ) return;
  42514. requestId = context.requestAnimationFrame( onAnimationFrame );
  42515. isAnimating = true;
  42516. },
  42517. stop: function () {
  42518. context.cancelAnimationFrame( requestId );
  42519. isAnimating = false;
  42520. },
  42521. setAnimationLoop: function ( callback ) {
  42522. animationLoop = callback;
  42523. },
  42524. setContext: function ( value ) {
  42525. context = value;
  42526. }
  42527. };
  42528. }
  42529. function WebGLAttributes( gl ) {
  42530. const buffers = new WeakMap();
  42531. function createBuffer( attribute, bufferType ) {
  42532. const array = attribute.array;
  42533. const usage = attribute.usage;
  42534. const size = array.byteLength;
  42535. const buffer = gl.createBuffer();
  42536. gl.bindBuffer( bufferType, buffer );
  42537. gl.bufferData( bufferType, array, usage );
  42538. attribute.onUploadCallback();
  42539. let type;
  42540. if ( array instanceof Float32Array ) {
  42541. type = gl.FLOAT;
  42542. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  42543. type = gl.HALF_FLOAT;
  42544. } else if ( array instanceof Uint16Array ) {
  42545. if ( attribute.isFloat16BufferAttribute ) {
  42546. type = gl.HALF_FLOAT;
  42547. } else {
  42548. type = gl.UNSIGNED_SHORT;
  42549. }
  42550. } else if ( array instanceof Int16Array ) {
  42551. type = gl.SHORT;
  42552. } else if ( array instanceof Uint32Array ) {
  42553. type = gl.UNSIGNED_INT;
  42554. } else if ( array instanceof Int32Array ) {
  42555. type = gl.INT;
  42556. } else if ( array instanceof Int8Array ) {
  42557. type = gl.BYTE;
  42558. } else if ( array instanceof Uint8Array ) {
  42559. type = gl.UNSIGNED_BYTE;
  42560. } else if ( array instanceof Uint8ClampedArray ) {
  42561. type = gl.UNSIGNED_BYTE;
  42562. } else {
  42563. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  42564. }
  42565. return {
  42566. buffer: buffer,
  42567. type: type,
  42568. bytesPerElement: array.BYTES_PER_ELEMENT,
  42569. version: attribute.version,
  42570. size: size
  42571. };
  42572. }
  42573. function updateBuffer( buffer, attribute, bufferType ) {
  42574. const array = attribute.array;
  42575. const updateRanges = attribute.updateRanges;
  42576. gl.bindBuffer( bufferType, buffer );
  42577. if ( updateRanges.length === 0 ) {
  42578. // Not using update ranges
  42579. gl.bufferSubData( bufferType, 0, array );
  42580. } else {
  42581. // Before applying update ranges, we merge any adjacent / overlapping
  42582. // ranges to reduce load on `gl.bufferSubData`. Empirically, this has led
  42583. // to performance improvements for applications which make heavy use of
  42584. // update ranges. Likely due to GPU command overhead.
  42585. //
  42586. // Note that to reduce garbage collection between frames, we merge the
  42587. // update ranges in-place. This is safe because this method will clear the
  42588. // update ranges once updated.
  42589. updateRanges.sort( ( a, b ) => a.start - b.start );
  42590. // To merge the update ranges in-place, we work from left to right in the
  42591. // existing updateRanges array, merging ranges. This may result in a final
  42592. // array which is smaller than the original. This index tracks the last
  42593. // index representing a merged range, any data after this index can be
  42594. // trimmed once the merge algorithm is completed.
  42595. let mergeIndex = 0;
  42596. for ( let i = 1; i < updateRanges.length; i ++ ) {
  42597. const previousRange = updateRanges[ mergeIndex ];
  42598. const range = updateRanges[ i ];
  42599. // We add one here to merge adjacent ranges. This is safe because ranges
  42600. // operate over positive integers.
  42601. if ( range.start <= previousRange.start + previousRange.count + 1 ) {
  42602. previousRange.count = Math.max(
  42603. previousRange.count,
  42604. range.start + range.count - previousRange.start
  42605. );
  42606. } else {
  42607. ++ mergeIndex;
  42608. updateRanges[ mergeIndex ] = range;
  42609. }
  42610. }
  42611. // Trim the array to only contain the merged ranges.
  42612. updateRanges.length = mergeIndex + 1;
  42613. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  42614. const range = updateRanges[ i ];
  42615. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  42616. array, range.start, range.count );
  42617. }
  42618. attribute.clearUpdateRanges();
  42619. }
  42620. attribute.onUploadCallback();
  42621. }
  42622. //
  42623. function get( attribute ) {
  42624. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42625. return buffers.get( attribute );
  42626. }
  42627. function remove( attribute ) {
  42628. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42629. const data = buffers.get( attribute );
  42630. if ( data ) {
  42631. gl.deleteBuffer( data.buffer );
  42632. buffers.delete( attribute );
  42633. }
  42634. }
  42635. function update( attribute, bufferType ) {
  42636. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42637. if ( attribute.isGLBufferAttribute ) {
  42638. const cached = buffers.get( attribute );
  42639. if ( ! cached || cached.version < attribute.version ) {
  42640. buffers.set( attribute, {
  42641. buffer: attribute.buffer,
  42642. type: attribute.type,
  42643. bytesPerElement: attribute.elementSize,
  42644. version: attribute.version
  42645. } );
  42646. }
  42647. return;
  42648. }
  42649. const data = buffers.get( attribute );
  42650. if ( data === undefined ) {
  42651. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  42652. } else if ( data.version < attribute.version ) {
  42653. if ( data.size !== attribute.array.byteLength ) {
  42654. 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.' );
  42655. }
  42656. updateBuffer( data.buffer, attribute, bufferType );
  42657. data.version = attribute.version;
  42658. }
  42659. }
  42660. return {
  42661. get: get,
  42662. remove: remove,
  42663. update: update
  42664. };
  42665. }
  42666. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  42667. 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";
  42668. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  42669. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  42670. 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";
  42671. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  42672. 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";
  42673. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  42674. 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";
  42675. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif";
  42676. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  42677. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  42678. 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";
  42679. 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";
  42680. 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";
  42681. 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";
  42682. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  42683. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  42684. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  42685. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  42686. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  42687. 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";
  42688. 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";
  42689. 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";
  42690. 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";
  42691. 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";
  42692. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  42693. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  42694. 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";
  42695. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  42696. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  42697. 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}";
  42698. 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";
  42699. 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";
  42700. 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";
  42701. 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";
  42702. 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";
  42703. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  42704. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  42705. 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";
  42706. 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";
  42707. 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}";
  42708. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  42709. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  42710. 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";
  42711. 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";
  42712. 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";
  42713. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  42714. 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";
  42715. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  42716. 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";
  42717. 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";
  42718. 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}";
  42719. 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";
  42720. 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";
  42721. 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";
  42722. 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";
  42723. var logdepthbuf_pars_fragment = "#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  42724. var logdepthbuf_pars_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  42725. var logdepthbuf_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif";
  42726. 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";
  42727. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  42728. 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";
  42729. 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";
  42730. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  42731. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  42732. 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";
  42733. 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";
  42734. 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";
  42735. 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";
  42736. 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";
  42737. 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;";
  42738. 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";
  42739. 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";
  42740. 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";
  42741. 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";
  42742. 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";
  42743. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  42744. 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";
  42745. 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";
  42746. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  42747. 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 );";
  42748. 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}";
  42749. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  42750. 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;";
  42751. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  42752. 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";
  42753. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  42754. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  42755. 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";
  42756. 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";
  42757. 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";
  42758. 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}";
  42759. 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";
  42760. 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";
  42761. 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";
  42762. 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";
  42763. 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";
  42764. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  42765. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  42766. 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; }";
  42767. 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";
  42768. 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";
  42769. 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";
  42770. 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";
  42771. 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";
  42772. 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";
  42773. 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}";
  42774. 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}";
  42775. 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}";
  42776. 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}";
  42777. 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}";
  42778. 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}";
  42779. 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}";
  42780. 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}";
  42781. 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}";
  42782. 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}";
  42783. 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}";
  42784. 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}";
  42785. 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}";
  42786. 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}";
  42787. 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}";
  42788. 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}";
  42789. 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}";
  42790. 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}";
  42791. 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}";
  42792. 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}";
  42793. 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}";
  42794. 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}";
  42795. 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}";
  42796. 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}";
  42797. 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}";
  42798. 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}";
  42799. 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}";
  42800. 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}";
  42801. 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}";
  42802. 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}";
  42803. 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}";
  42804. 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}";
  42805. 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}";
  42806. 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}";
  42807. const ShaderChunk = {
  42808. alphahash_fragment: alphahash_fragment,
  42809. alphahash_pars_fragment: alphahash_pars_fragment,
  42810. alphamap_fragment: alphamap_fragment,
  42811. alphamap_pars_fragment: alphamap_pars_fragment,
  42812. alphatest_fragment: alphatest_fragment,
  42813. alphatest_pars_fragment: alphatest_pars_fragment,
  42814. aomap_fragment: aomap_fragment,
  42815. aomap_pars_fragment: aomap_pars_fragment,
  42816. batching_pars_vertex: batching_pars_vertex,
  42817. batching_vertex: batching_vertex,
  42818. begin_vertex: begin_vertex,
  42819. beginnormal_vertex: beginnormal_vertex,
  42820. bsdfs: bsdfs,
  42821. iridescence_fragment: iridescence_fragment,
  42822. bumpmap_pars_fragment: bumpmap_pars_fragment,
  42823. clipping_planes_fragment: clipping_planes_fragment,
  42824. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  42825. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  42826. clipping_planes_vertex: clipping_planes_vertex,
  42827. color_fragment: color_fragment,
  42828. color_pars_fragment: color_pars_fragment,
  42829. color_pars_vertex: color_pars_vertex,
  42830. color_vertex: color_vertex,
  42831. common: common,
  42832. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  42833. defaultnormal_vertex: defaultnormal_vertex,
  42834. displacementmap_pars_vertex: displacementmap_pars_vertex,
  42835. displacementmap_vertex: displacementmap_vertex,
  42836. emissivemap_fragment: emissivemap_fragment,
  42837. emissivemap_pars_fragment: emissivemap_pars_fragment,
  42838. colorspace_fragment: colorspace_fragment,
  42839. colorspace_pars_fragment: colorspace_pars_fragment,
  42840. envmap_fragment: envmap_fragment,
  42841. envmap_common_pars_fragment: envmap_common_pars_fragment,
  42842. envmap_pars_fragment: envmap_pars_fragment,
  42843. envmap_pars_vertex: envmap_pars_vertex,
  42844. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  42845. envmap_vertex: envmap_vertex,
  42846. fog_vertex: fog_vertex,
  42847. fog_pars_vertex: fog_pars_vertex,
  42848. fog_fragment: fog_fragment,
  42849. fog_pars_fragment: fog_pars_fragment,
  42850. gradientmap_pars_fragment: gradientmap_pars_fragment,
  42851. lightmap_pars_fragment: lightmap_pars_fragment,
  42852. lights_lambert_fragment: lights_lambert_fragment,
  42853. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  42854. lights_pars_begin: lights_pars_begin,
  42855. lights_toon_fragment: lights_toon_fragment,
  42856. lights_toon_pars_fragment: lights_toon_pars_fragment,
  42857. lights_phong_fragment: lights_phong_fragment,
  42858. lights_phong_pars_fragment: lights_phong_pars_fragment,
  42859. lights_physical_fragment: lights_physical_fragment,
  42860. lights_physical_pars_fragment: lights_physical_pars_fragment,
  42861. lights_fragment_begin: lights_fragment_begin,
  42862. lights_fragment_maps: lights_fragment_maps,
  42863. lights_fragment_end: lights_fragment_end,
  42864. logdepthbuf_fragment: logdepthbuf_fragment,
  42865. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  42866. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  42867. logdepthbuf_vertex: logdepthbuf_vertex,
  42868. map_fragment: map_fragment,
  42869. map_pars_fragment: map_pars_fragment,
  42870. map_particle_fragment: map_particle_fragment,
  42871. map_particle_pars_fragment: map_particle_pars_fragment,
  42872. metalnessmap_fragment: metalnessmap_fragment,
  42873. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  42874. morphinstance_vertex: morphinstance_vertex,
  42875. morphcolor_vertex: morphcolor_vertex,
  42876. morphnormal_vertex: morphnormal_vertex,
  42877. morphtarget_pars_vertex: morphtarget_pars_vertex,
  42878. morphtarget_vertex: morphtarget_vertex,
  42879. normal_fragment_begin: normal_fragment_begin,
  42880. normal_fragment_maps: normal_fragment_maps,
  42881. normal_pars_fragment: normal_pars_fragment,
  42882. normal_pars_vertex: normal_pars_vertex,
  42883. normal_vertex: normal_vertex,
  42884. normalmap_pars_fragment: normalmap_pars_fragment,
  42885. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  42886. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  42887. clearcoat_pars_fragment: clearcoat_pars_fragment,
  42888. iridescence_pars_fragment: iridescence_pars_fragment,
  42889. opaque_fragment: opaque_fragment,
  42890. packing: packing,
  42891. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  42892. project_vertex: project_vertex,
  42893. dithering_fragment: dithering_fragment,
  42894. dithering_pars_fragment: dithering_pars_fragment,
  42895. roughnessmap_fragment: roughnessmap_fragment,
  42896. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  42897. shadowmap_pars_fragment: shadowmap_pars_fragment,
  42898. shadowmap_pars_vertex: shadowmap_pars_vertex,
  42899. shadowmap_vertex: shadowmap_vertex,
  42900. shadowmask_pars_fragment: shadowmask_pars_fragment,
  42901. skinbase_vertex: skinbase_vertex,
  42902. skinning_pars_vertex: skinning_pars_vertex,
  42903. skinning_vertex: skinning_vertex,
  42904. skinnormal_vertex: skinnormal_vertex,
  42905. specularmap_fragment: specularmap_fragment,
  42906. specularmap_pars_fragment: specularmap_pars_fragment,
  42907. tonemapping_fragment: tonemapping_fragment,
  42908. tonemapping_pars_fragment: tonemapping_pars_fragment,
  42909. transmission_fragment: transmission_fragment,
  42910. transmission_pars_fragment: transmission_pars_fragment,
  42911. uv_pars_fragment: uv_pars_fragment,
  42912. uv_pars_vertex: uv_pars_vertex,
  42913. uv_vertex: uv_vertex,
  42914. worldpos_vertex: worldpos_vertex,
  42915. background_vert: vertex$h,
  42916. background_frag: fragment$h,
  42917. backgroundCube_vert: vertex$g,
  42918. backgroundCube_frag: fragment$g,
  42919. cube_vert: vertex$f,
  42920. cube_frag: fragment$f,
  42921. depth_vert: vertex$e,
  42922. depth_frag: fragment$e,
  42923. distanceRGBA_vert: vertex$d,
  42924. distanceRGBA_frag: fragment$d,
  42925. equirect_vert: vertex$c,
  42926. equirect_frag: fragment$c,
  42927. linedashed_vert: vertex$b,
  42928. linedashed_frag: fragment$b,
  42929. meshbasic_vert: vertex$a,
  42930. meshbasic_frag: fragment$a,
  42931. meshlambert_vert: vertex$9,
  42932. meshlambert_frag: fragment$9,
  42933. meshmatcap_vert: vertex$8,
  42934. meshmatcap_frag: fragment$8,
  42935. meshnormal_vert: vertex$7,
  42936. meshnormal_frag: fragment$7,
  42937. meshphong_vert: vertex$6,
  42938. meshphong_frag: fragment$6,
  42939. meshphysical_vert: vertex$5,
  42940. meshphysical_frag: fragment$5,
  42941. meshtoon_vert: vertex$4,
  42942. meshtoon_frag: fragment$4,
  42943. points_vert: vertex$3,
  42944. points_frag: fragment$3,
  42945. shadow_vert: vertex$2,
  42946. shadow_frag: fragment$2,
  42947. sprite_vert: vertex$1,
  42948. sprite_frag: fragment$1
  42949. };
  42950. // Uniforms library for shared webgl shaders
  42951. const UniformsLib = {
  42952. common: {
  42953. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  42954. opacity: { value: 1.0 },
  42955. map: { value: null },
  42956. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42957. alphaMap: { value: null },
  42958. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42959. alphaTest: { value: 0 }
  42960. },
  42961. specularmap: {
  42962. specularMap: { value: null },
  42963. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  42964. },
  42965. envmap: {
  42966. envMap: { value: null },
  42967. envMapRotation: { value: /*@__PURE__*/ new Matrix3() },
  42968. flipEnvMap: { value: -1 },
  42969. reflectivity: { value: 1.0 }, // basic, lambert, phong
  42970. ior: { value: 1.5 }, // physical
  42971. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  42972. },
  42973. aomap: {
  42974. aoMap: { value: null },
  42975. aoMapIntensity: { value: 1 },
  42976. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  42977. },
  42978. lightmap: {
  42979. lightMap: { value: null },
  42980. lightMapIntensity: { value: 1 },
  42981. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  42982. },
  42983. bumpmap: {
  42984. bumpMap: { value: null },
  42985. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42986. bumpScale: { value: 1 }
  42987. },
  42988. normalmap: {
  42989. normalMap: { value: null },
  42990. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42991. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  42992. },
  42993. displacementmap: {
  42994. displacementMap: { value: null },
  42995. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42996. displacementScale: { value: 1 },
  42997. displacementBias: { value: 0 }
  42998. },
  42999. emissivemap: {
  43000. emissiveMap: { value: null },
  43001. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43002. },
  43003. metalnessmap: {
  43004. metalnessMap: { value: null },
  43005. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43006. },
  43007. roughnessmap: {
  43008. roughnessMap: { value: null },
  43009. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43010. },
  43011. gradientmap: {
  43012. gradientMap: { value: null }
  43013. },
  43014. fog: {
  43015. fogDensity: { value: 0.00025 },
  43016. fogNear: { value: 1 },
  43017. fogFar: { value: 2000 },
  43018. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  43019. },
  43020. lights: {
  43021. ambientLightColor: { value: [] },
  43022. lightProbe: { value: [] },
  43023. directionalLights: { value: [], properties: {
  43024. direction: {},
  43025. color: {}
  43026. } },
  43027. directionalLightShadows: { value: [], properties: {
  43028. shadowIntensity: 1,
  43029. shadowBias: {},
  43030. shadowNormalBias: {},
  43031. shadowRadius: {},
  43032. shadowMapSize: {}
  43033. } },
  43034. directionalShadowMap: { value: [] },
  43035. directionalShadowMatrix: { value: [] },
  43036. spotLights: { value: [], properties: {
  43037. color: {},
  43038. position: {},
  43039. direction: {},
  43040. distance: {},
  43041. coneCos: {},
  43042. penumbraCos: {},
  43043. decay: {}
  43044. } },
  43045. spotLightShadows: { value: [], properties: {
  43046. shadowIntensity: 1,
  43047. shadowBias: {},
  43048. shadowNormalBias: {},
  43049. shadowRadius: {},
  43050. shadowMapSize: {}
  43051. } },
  43052. spotLightMap: { value: [] },
  43053. spotShadowMap: { value: [] },
  43054. spotLightMatrix: { value: [] },
  43055. pointLights: { value: [], properties: {
  43056. color: {},
  43057. position: {},
  43058. decay: {},
  43059. distance: {}
  43060. } },
  43061. pointLightShadows: { value: [], properties: {
  43062. shadowIntensity: 1,
  43063. shadowBias: {},
  43064. shadowNormalBias: {},
  43065. shadowRadius: {},
  43066. shadowMapSize: {},
  43067. shadowCameraNear: {},
  43068. shadowCameraFar: {}
  43069. } },
  43070. pointShadowMap: { value: [] },
  43071. pointShadowMatrix: { value: [] },
  43072. hemisphereLights: { value: [], properties: {
  43073. direction: {},
  43074. skyColor: {},
  43075. groundColor: {}
  43076. } },
  43077. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  43078. rectAreaLights: { value: [], properties: {
  43079. color: {},
  43080. position: {},
  43081. width: {},
  43082. height: {}
  43083. } },
  43084. ltc_1: { value: null },
  43085. ltc_2: { value: null }
  43086. },
  43087. points: {
  43088. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43089. opacity: { value: 1.0 },
  43090. size: { value: 1.0 },
  43091. scale: { value: 1.0 },
  43092. map: { value: null },
  43093. alphaMap: { value: null },
  43094. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43095. alphaTest: { value: 0 },
  43096. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  43097. },
  43098. sprite: {
  43099. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43100. opacity: { value: 1.0 },
  43101. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  43102. rotation: { value: 0.0 },
  43103. map: { value: null },
  43104. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43105. alphaMap: { value: null },
  43106. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43107. alphaTest: { value: 0 }
  43108. }
  43109. };
  43110. const ShaderLib = {
  43111. basic: {
  43112. uniforms: /*@__PURE__*/ mergeUniforms( [
  43113. UniformsLib.common,
  43114. UniformsLib.specularmap,
  43115. UniformsLib.envmap,
  43116. UniformsLib.aomap,
  43117. UniformsLib.lightmap,
  43118. UniformsLib.fog
  43119. ] ),
  43120. vertexShader: ShaderChunk.meshbasic_vert,
  43121. fragmentShader: ShaderChunk.meshbasic_frag
  43122. },
  43123. lambert: {
  43124. uniforms: /*@__PURE__*/ mergeUniforms( [
  43125. UniformsLib.common,
  43126. UniformsLib.specularmap,
  43127. UniformsLib.envmap,
  43128. UniformsLib.aomap,
  43129. UniformsLib.lightmap,
  43130. UniformsLib.emissivemap,
  43131. UniformsLib.bumpmap,
  43132. UniformsLib.normalmap,
  43133. UniformsLib.displacementmap,
  43134. UniformsLib.fog,
  43135. UniformsLib.lights,
  43136. {
  43137. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  43138. }
  43139. ] ),
  43140. vertexShader: ShaderChunk.meshlambert_vert,
  43141. fragmentShader: ShaderChunk.meshlambert_frag
  43142. },
  43143. phong: {
  43144. uniforms: /*@__PURE__*/ mergeUniforms( [
  43145. UniformsLib.common,
  43146. UniformsLib.specularmap,
  43147. UniformsLib.envmap,
  43148. UniformsLib.aomap,
  43149. UniformsLib.lightmap,
  43150. UniformsLib.emissivemap,
  43151. UniformsLib.bumpmap,
  43152. UniformsLib.normalmap,
  43153. UniformsLib.displacementmap,
  43154. UniformsLib.fog,
  43155. UniformsLib.lights,
  43156. {
  43157. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43158. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  43159. shininess: { value: 30 }
  43160. }
  43161. ] ),
  43162. vertexShader: ShaderChunk.meshphong_vert,
  43163. fragmentShader: ShaderChunk.meshphong_frag
  43164. },
  43165. standard: {
  43166. uniforms: /*@__PURE__*/ mergeUniforms( [
  43167. UniformsLib.common,
  43168. UniformsLib.envmap,
  43169. UniformsLib.aomap,
  43170. UniformsLib.lightmap,
  43171. UniformsLib.emissivemap,
  43172. UniformsLib.bumpmap,
  43173. UniformsLib.normalmap,
  43174. UniformsLib.displacementmap,
  43175. UniformsLib.roughnessmap,
  43176. UniformsLib.metalnessmap,
  43177. UniformsLib.fog,
  43178. UniformsLib.lights,
  43179. {
  43180. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43181. roughness: { value: 1.0 },
  43182. metalness: { value: 0.0 },
  43183. envMapIntensity: { value: 1 }
  43184. }
  43185. ] ),
  43186. vertexShader: ShaderChunk.meshphysical_vert,
  43187. fragmentShader: ShaderChunk.meshphysical_frag
  43188. },
  43189. toon: {
  43190. uniforms: /*@__PURE__*/ mergeUniforms( [
  43191. UniformsLib.common,
  43192. UniformsLib.aomap,
  43193. UniformsLib.lightmap,
  43194. UniformsLib.emissivemap,
  43195. UniformsLib.bumpmap,
  43196. UniformsLib.normalmap,
  43197. UniformsLib.displacementmap,
  43198. UniformsLib.gradientmap,
  43199. UniformsLib.fog,
  43200. UniformsLib.lights,
  43201. {
  43202. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  43203. }
  43204. ] ),
  43205. vertexShader: ShaderChunk.meshtoon_vert,
  43206. fragmentShader: ShaderChunk.meshtoon_frag
  43207. },
  43208. matcap: {
  43209. uniforms: /*@__PURE__*/ mergeUniforms( [
  43210. UniformsLib.common,
  43211. UniformsLib.bumpmap,
  43212. UniformsLib.normalmap,
  43213. UniformsLib.displacementmap,
  43214. UniformsLib.fog,
  43215. {
  43216. matcap: { value: null }
  43217. }
  43218. ] ),
  43219. vertexShader: ShaderChunk.meshmatcap_vert,
  43220. fragmentShader: ShaderChunk.meshmatcap_frag
  43221. },
  43222. points: {
  43223. uniforms: /*@__PURE__*/ mergeUniforms( [
  43224. UniformsLib.points,
  43225. UniformsLib.fog
  43226. ] ),
  43227. vertexShader: ShaderChunk.points_vert,
  43228. fragmentShader: ShaderChunk.points_frag
  43229. },
  43230. dashed: {
  43231. uniforms: /*@__PURE__*/ mergeUniforms( [
  43232. UniformsLib.common,
  43233. UniformsLib.fog,
  43234. {
  43235. scale: { value: 1 },
  43236. dashSize: { value: 1 },
  43237. totalSize: { value: 2 }
  43238. }
  43239. ] ),
  43240. vertexShader: ShaderChunk.linedashed_vert,
  43241. fragmentShader: ShaderChunk.linedashed_frag
  43242. },
  43243. depth: {
  43244. uniforms: /*@__PURE__*/ mergeUniforms( [
  43245. UniformsLib.common,
  43246. UniformsLib.displacementmap
  43247. ] ),
  43248. vertexShader: ShaderChunk.depth_vert,
  43249. fragmentShader: ShaderChunk.depth_frag
  43250. },
  43251. normal: {
  43252. uniforms: /*@__PURE__*/ mergeUniforms( [
  43253. UniformsLib.common,
  43254. UniformsLib.bumpmap,
  43255. UniformsLib.normalmap,
  43256. UniformsLib.displacementmap,
  43257. {
  43258. opacity: { value: 1.0 }
  43259. }
  43260. ] ),
  43261. vertexShader: ShaderChunk.meshnormal_vert,
  43262. fragmentShader: ShaderChunk.meshnormal_frag
  43263. },
  43264. sprite: {
  43265. uniforms: /*@__PURE__*/ mergeUniforms( [
  43266. UniformsLib.sprite,
  43267. UniformsLib.fog
  43268. ] ),
  43269. vertexShader: ShaderChunk.sprite_vert,
  43270. fragmentShader: ShaderChunk.sprite_frag
  43271. },
  43272. background: {
  43273. uniforms: {
  43274. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  43275. t2D: { value: null },
  43276. backgroundIntensity: { value: 1 }
  43277. },
  43278. vertexShader: ShaderChunk.background_vert,
  43279. fragmentShader: ShaderChunk.background_frag
  43280. },
  43281. backgroundCube: {
  43282. uniforms: {
  43283. envMap: { value: null },
  43284. flipEnvMap: { value: -1 },
  43285. backgroundBlurriness: { value: 0 },
  43286. backgroundIntensity: { value: 1 },
  43287. backgroundRotation: { value: /*@__PURE__*/ new Matrix3() }
  43288. },
  43289. vertexShader: ShaderChunk.backgroundCube_vert,
  43290. fragmentShader: ShaderChunk.backgroundCube_frag
  43291. },
  43292. cube: {
  43293. uniforms: {
  43294. tCube: { value: null },
  43295. tFlip: { value: -1 },
  43296. opacity: { value: 1.0 }
  43297. },
  43298. vertexShader: ShaderChunk.cube_vert,
  43299. fragmentShader: ShaderChunk.cube_frag
  43300. },
  43301. equirect: {
  43302. uniforms: {
  43303. tEquirect: { value: null },
  43304. },
  43305. vertexShader: ShaderChunk.equirect_vert,
  43306. fragmentShader: ShaderChunk.equirect_frag
  43307. },
  43308. distanceRGBA: {
  43309. uniforms: /*@__PURE__*/ mergeUniforms( [
  43310. UniformsLib.common,
  43311. UniformsLib.displacementmap,
  43312. {
  43313. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  43314. nearDistance: { value: 1 },
  43315. farDistance: { value: 1000 }
  43316. }
  43317. ] ),
  43318. vertexShader: ShaderChunk.distanceRGBA_vert,
  43319. fragmentShader: ShaderChunk.distanceRGBA_frag
  43320. },
  43321. shadow: {
  43322. uniforms: /*@__PURE__*/ mergeUniforms( [
  43323. UniformsLib.lights,
  43324. UniformsLib.fog,
  43325. {
  43326. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  43327. opacity: { value: 1.0 }
  43328. },
  43329. ] ),
  43330. vertexShader: ShaderChunk.shadow_vert,
  43331. fragmentShader: ShaderChunk.shadow_frag
  43332. }
  43333. };
  43334. ShaderLib.physical = {
  43335. uniforms: /*@__PURE__*/ mergeUniforms( [
  43336. ShaderLib.standard.uniforms,
  43337. {
  43338. clearcoat: { value: 0 },
  43339. clearcoatMap: { value: null },
  43340. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43341. clearcoatNormalMap: { value: null },
  43342. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43343. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  43344. clearcoatRoughness: { value: 0 },
  43345. clearcoatRoughnessMap: { value: null },
  43346. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43347. dispersion: { value: 0 },
  43348. iridescence: { value: 0 },
  43349. iridescenceMap: { value: null },
  43350. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43351. iridescenceIOR: { value: 1.3 },
  43352. iridescenceThicknessMinimum: { value: 100 },
  43353. iridescenceThicknessMaximum: { value: 400 },
  43354. iridescenceThicknessMap: { value: null },
  43355. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43356. sheen: { value: 0 },
  43357. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43358. sheenColorMap: { value: null },
  43359. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43360. sheenRoughness: { value: 1 },
  43361. sheenRoughnessMap: { value: null },
  43362. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43363. transmission: { value: 0 },
  43364. transmissionMap: { value: null },
  43365. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43366. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  43367. transmissionSamplerMap: { value: null },
  43368. thickness: { value: 0 },
  43369. thicknessMap: { value: null },
  43370. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43371. attenuationDistance: { value: 0 },
  43372. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43373. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  43374. specularColorMap: { value: null },
  43375. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43376. specularIntensity: { value: 1 },
  43377. specularIntensityMap: { value: null },
  43378. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43379. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  43380. anisotropyMap: { value: null },
  43381. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43382. }
  43383. ] ),
  43384. vertexShader: ShaderChunk.meshphysical_vert,
  43385. fragmentShader: ShaderChunk.meshphysical_frag
  43386. };
  43387. const _rgb = { r: 0, b: 0, g: 0 };
  43388. const _e1$1 = /*@__PURE__*/ new Euler();
  43389. const _m1$1 = /*@__PURE__*/ new Matrix4();
  43390. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  43391. const clearColor = new Color( 0x000000 );
  43392. let clearAlpha = alpha === true ? 0 : 1;
  43393. let planeMesh;
  43394. let boxMesh;
  43395. let currentBackground = null;
  43396. let currentBackgroundVersion = 0;
  43397. let currentTonemapping = null;
  43398. function getBackground( scene ) {
  43399. let background = scene.isScene === true ? scene.background : null;
  43400. if ( background && background.isTexture ) {
  43401. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  43402. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  43403. }
  43404. return background;
  43405. }
  43406. function render( scene ) {
  43407. let forceClear = false;
  43408. const background = getBackground( scene );
  43409. if ( background === null ) {
  43410. setClear( clearColor, clearAlpha );
  43411. } else if ( background && background.isColor ) {
  43412. setClear( background, 1 );
  43413. forceClear = true;
  43414. }
  43415. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  43416. if ( environmentBlendMode === 'additive' ) {
  43417. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  43418. } else if ( environmentBlendMode === 'alpha-blend' ) {
  43419. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  43420. }
  43421. if ( renderer.autoClear || forceClear ) {
  43422. // buffers might not be writable which is required to ensure a correct clear
  43423. state.buffers.depth.setTest( true );
  43424. state.buffers.depth.setMask( true );
  43425. state.buffers.color.setMask( true );
  43426. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  43427. }
  43428. }
  43429. function addToRenderList( renderList, scene ) {
  43430. const background = getBackground( scene );
  43431. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  43432. if ( boxMesh === undefined ) {
  43433. boxMesh = new Mesh(
  43434. new BoxGeometry( 1, 1, 1 ),
  43435. new ShaderMaterial( {
  43436. name: 'BackgroundCubeMaterial',
  43437. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  43438. vertexShader: ShaderLib.backgroundCube.vertexShader,
  43439. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  43440. side: BackSide,
  43441. depthTest: false,
  43442. depthWrite: false,
  43443. fog: false,
  43444. allowOverride: false
  43445. } )
  43446. );
  43447. boxMesh.geometry.deleteAttribute( 'normal' );
  43448. boxMesh.geometry.deleteAttribute( 'uv' );
  43449. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  43450. this.matrixWorld.copyPosition( camera.matrixWorld );
  43451. };
  43452. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  43453. Object.defineProperty( boxMesh.material, 'envMap', {
  43454. get: function () {
  43455. return this.uniforms.envMap.value;
  43456. }
  43457. } );
  43458. objects.update( boxMesh );
  43459. }
  43460. _e1$1.copy( scene.backgroundRotation );
  43461. // accommodate left-handed frame
  43462. _e1$1.x *= -1; _e1$1.y *= -1; _e1$1.z *= -1;
  43463. if ( background.isCubeTexture && background.isRenderTargetTexture === false ) {
  43464. // environment maps which are not cube render targets or PMREMs follow a different convention
  43465. _e1$1.y *= -1;
  43466. _e1$1.z *= -1;
  43467. }
  43468. boxMesh.material.uniforms.envMap.value = background;
  43469. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? -1 : 1;
  43470. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  43471. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  43472. boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) );
  43473. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  43474. if ( currentBackground !== background ||
  43475. currentBackgroundVersion !== background.version ||
  43476. currentTonemapping !== renderer.toneMapping ) {
  43477. boxMesh.material.needsUpdate = true;
  43478. currentBackground = background;
  43479. currentBackgroundVersion = background.version;
  43480. currentTonemapping = renderer.toneMapping;
  43481. }
  43482. boxMesh.layers.enableAll();
  43483. // push to the pre-sorted opaque render list
  43484. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  43485. } else if ( background && background.isTexture ) {
  43486. if ( planeMesh === undefined ) {
  43487. planeMesh = new Mesh(
  43488. new PlaneGeometry( 2, 2 ),
  43489. new ShaderMaterial( {
  43490. name: 'BackgroundMaterial',
  43491. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  43492. vertexShader: ShaderLib.background.vertexShader,
  43493. fragmentShader: ShaderLib.background.fragmentShader,
  43494. side: FrontSide,
  43495. depthTest: false,
  43496. depthWrite: false,
  43497. fog: false,
  43498. allowOverride: false
  43499. } )
  43500. );
  43501. planeMesh.geometry.deleteAttribute( 'normal' );
  43502. // add "map" material property so the renderer can evaluate it like for built-in materials
  43503. Object.defineProperty( planeMesh.material, 'map', {
  43504. get: function () {
  43505. return this.uniforms.t2D.value;
  43506. }
  43507. } );
  43508. objects.update( planeMesh );
  43509. }
  43510. planeMesh.material.uniforms.t2D.value = background;
  43511. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  43512. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  43513. if ( background.matrixAutoUpdate === true ) {
  43514. background.updateMatrix();
  43515. }
  43516. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  43517. if ( currentBackground !== background ||
  43518. currentBackgroundVersion !== background.version ||
  43519. currentTonemapping !== renderer.toneMapping ) {
  43520. planeMesh.material.needsUpdate = true;
  43521. currentBackground = background;
  43522. currentBackgroundVersion = background.version;
  43523. currentTonemapping = renderer.toneMapping;
  43524. }
  43525. planeMesh.layers.enableAll();
  43526. // push to the pre-sorted opaque render list
  43527. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  43528. }
  43529. }
  43530. function setClear( color, alpha ) {
  43531. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  43532. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  43533. }
  43534. function dispose() {
  43535. if ( boxMesh !== undefined ) {
  43536. boxMesh.geometry.dispose();
  43537. boxMesh.material.dispose();
  43538. boxMesh = undefined;
  43539. }
  43540. if ( planeMesh !== undefined ) {
  43541. planeMesh.geometry.dispose();
  43542. planeMesh.material.dispose();
  43543. planeMesh = undefined;
  43544. }
  43545. }
  43546. return {
  43547. getClearColor: function () {
  43548. return clearColor;
  43549. },
  43550. setClearColor: function ( color, alpha = 1 ) {
  43551. clearColor.set( color );
  43552. clearAlpha = alpha;
  43553. setClear( clearColor, clearAlpha );
  43554. },
  43555. getClearAlpha: function () {
  43556. return clearAlpha;
  43557. },
  43558. setClearAlpha: function ( alpha ) {
  43559. clearAlpha = alpha;
  43560. setClear( clearColor, clearAlpha );
  43561. },
  43562. render: render,
  43563. addToRenderList: addToRenderList,
  43564. dispose: dispose
  43565. };
  43566. }
  43567. function WebGLBindingStates( gl, attributes ) {
  43568. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  43569. const bindingStates = {};
  43570. const defaultState = createBindingState( null );
  43571. let currentState = defaultState;
  43572. let forceUpdate = false;
  43573. function setup( object, material, program, geometry, index ) {
  43574. let updateBuffers = false;
  43575. const state = getBindingState( geometry, program, material );
  43576. if ( currentState !== state ) {
  43577. currentState = state;
  43578. bindVertexArrayObject( currentState.object );
  43579. }
  43580. updateBuffers = needsUpdate( object, geometry, program, index );
  43581. if ( updateBuffers ) saveCache( object, geometry, program, index );
  43582. if ( index !== null ) {
  43583. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  43584. }
  43585. if ( updateBuffers || forceUpdate ) {
  43586. forceUpdate = false;
  43587. setupVertexAttributes( object, material, program, geometry );
  43588. if ( index !== null ) {
  43589. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  43590. }
  43591. }
  43592. }
  43593. function createVertexArrayObject() {
  43594. return gl.createVertexArray();
  43595. }
  43596. function bindVertexArrayObject( vao ) {
  43597. return gl.bindVertexArray( vao );
  43598. }
  43599. function deleteVertexArrayObject( vao ) {
  43600. return gl.deleteVertexArray( vao );
  43601. }
  43602. function getBindingState( geometry, program, material ) {
  43603. const wireframe = ( material.wireframe === true );
  43604. let programMap = bindingStates[ geometry.id ];
  43605. if ( programMap === undefined ) {
  43606. programMap = {};
  43607. bindingStates[ geometry.id ] = programMap;
  43608. }
  43609. let stateMap = programMap[ program.id ];
  43610. if ( stateMap === undefined ) {
  43611. stateMap = {};
  43612. programMap[ program.id ] = stateMap;
  43613. }
  43614. let state = stateMap[ wireframe ];
  43615. if ( state === undefined ) {
  43616. state = createBindingState( createVertexArrayObject() );
  43617. stateMap[ wireframe ] = state;
  43618. }
  43619. return state;
  43620. }
  43621. function createBindingState( vao ) {
  43622. const newAttributes = [];
  43623. const enabledAttributes = [];
  43624. const attributeDivisors = [];
  43625. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  43626. newAttributes[ i ] = 0;
  43627. enabledAttributes[ i ] = 0;
  43628. attributeDivisors[ i ] = 0;
  43629. }
  43630. return {
  43631. // for backward compatibility on non-VAO support browser
  43632. geometry: null,
  43633. program: null,
  43634. wireframe: false,
  43635. newAttributes: newAttributes,
  43636. enabledAttributes: enabledAttributes,
  43637. attributeDivisors: attributeDivisors,
  43638. object: vao,
  43639. attributes: {},
  43640. index: null
  43641. };
  43642. }
  43643. function needsUpdate( object, geometry, program, index ) {
  43644. const cachedAttributes = currentState.attributes;
  43645. const geometryAttributes = geometry.attributes;
  43646. let attributesNum = 0;
  43647. const programAttributes = program.getAttributes();
  43648. for ( const name in programAttributes ) {
  43649. const programAttribute = programAttributes[ name ];
  43650. if ( programAttribute.location >= 0 ) {
  43651. const cachedAttribute = cachedAttributes[ name ];
  43652. let geometryAttribute = geometryAttributes[ name ];
  43653. if ( geometryAttribute === undefined ) {
  43654. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  43655. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  43656. }
  43657. if ( cachedAttribute === undefined ) return true;
  43658. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  43659. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  43660. attributesNum ++;
  43661. }
  43662. }
  43663. if ( currentState.attributesNum !== attributesNum ) return true;
  43664. if ( currentState.index !== index ) return true;
  43665. return false;
  43666. }
  43667. function saveCache( object, geometry, program, index ) {
  43668. const cache = {};
  43669. const attributes = geometry.attributes;
  43670. let attributesNum = 0;
  43671. const programAttributes = program.getAttributes();
  43672. for ( const name in programAttributes ) {
  43673. const programAttribute = programAttributes[ name ];
  43674. if ( programAttribute.location >= 0 ) {
  43675. let attribute = attributes[ name ];
  43676. if ( attribute === undefined ) {
  43677. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  43678. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  43679. }
  43680. const data = {};
  43681. data.attribute = attribute;
  43682. if ( attribute && attribute.data ) {
  43683. data.data = attribute.data;
  43684. }
  43685. cache[ name ] = data;
  43686. attributesNum ++;
  43687. }
  43688. }
  43689. currentState.attributes = cache;
  43690. currentState.attributesNum = attributesNum;
  43691. currentState.index = index;
  43692. }
  43693. function initAttributes() {
  43694. const newAttributes = currentState.newAttributes;
  43695. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  43696. newAttributes[ i ] = 0;
  43697. }
  43698. }
  43699. function enableAttribute( attribute ) {
  43700. enableAttributeAndDivisor( attribute, 0 );
  43701. }
  43702. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  43703. const newAttributes = currentState.newAttributes;
  43704. const enabledAttributes = currentState.enabledAttributes;
  43705. const attributeDivisors = currentState.attributeDivisors;
  43706. newAttributes[ attribute ] = 1;
  43707. if ( enabledAttributes[ attribute ] === 0 ) {
  43708. gl.enableVertexAttribArray( attribute );
  43709. enabledAttributes[ attribute ] = 1;
  43710. }
  43711. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  43712. gl.vertexAttribDivisor( attribute, meshPerAttribute );
  43713. attributeDivisors[ attribute ] = meshPerAttribute;
  43714. }
  43715. }
  43716. function disableUnusedAttributes() {
  43717. const newAttributes = currentState.newAttributes;
  43718. const enabledAttributes = currentState.enabledAttributes;
  43719. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  43720. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  43721. gl.disableVertexAttribArray( i );
  43722. enabledAttributes[ i ] = 0;
  43723. }
  43724. }
  43725. }
  43726. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  43727. if ( integer === true ) {
  43728. gl.vertexAttribIPointer( index, size, type, stride, offset );
  43729. } else {
  43730. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  43731. }
  43732. }
  43733. function setupVertexAttributes( object, material, program, geometry ) {
  43734. initAttributes();
  43735. const geometryAttributes = geometry.attributes;
  43736. const programAttributes = program.getAttributes();
  43737. const materialDefaultAttributeValues = material.defaultAttributeValues;
  43738. for ( const name in programAttributes ) {
  43739. const programAttribute = programAttributes[ name ];
  43740. if ( programAttribute.location >= 0 ) {
  43741. let geometryAttribute = geometryAttributes[ name ];
  43742. if ( geometryAttribute === undefined ) {
  43743. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  43744. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  43745. }
  43746. if ( geometryAttribute !== undefined ) {
  43747. const normalized = geometryAttribute.normalized;
  43748. const size = geometryAttribute.itemSize;
  43749. const attribute = attributes.get( geometryAttribute );
  43750. // TODO Attribute may not be available on context restore
  43751. if ( attribute === undefined ) continue;
  43752. const buffer = attribute.buffer;
  43753. const type = attribute.type;
  43754. const bytesPerElement = attribute.bytesPerElement;
  43755. // check for integer attributes
  43756. const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType );
  43757. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  43758. const data = geometryAttribute.data;
  43759. const stride = data.stride;
  43760. const offset = geometryAttribute.offset;
  43761. if ( data.isInstancedInterleavedBuffer ) {
  43762. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43763. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  43764. }
  43765. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  43766. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  43767. }
  43768. } else {
  43769. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43770. enableAttribute( programAttribute.location + i );
  43771. }
  43772. }
  43773. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  43774. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43775. vertexAttribPointer(
  43776. programAttribute.location + i,
  43777. size / programAttribute.locationSize,
  43778. type,
  43779. normalized,
  43780. stride * bytesPerElement,
  43781. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  43782. integer
  43783. );
  43784. }
  43785. } else {
  43786. if ( geometryAttribute.isInstancedBufferAttribute ) {
  43787. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43788. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  43789. }
  43790. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  43791. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  43792. }
  43793. } else {
  43794. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43795. enableAttribute( programAttribute.location + i );
  43796. }
  43797. }
  43798. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  43799. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43800. vertexAttribPointer(
  43801. programAttribute.location + i,
  43802. size / programAttribute.locationSize,
  43803. type,
  43804. normalized,
  43805. size * bytesPerElement,
  43806. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  43807. integer
  43808. );
  43809. }
  43810. }
  43811. } else if ( materialDefaultAttributeValues !== undefined ) {
  43812. const value = materialDefaultAttributeValues[ name ];
  43813. if ( value !== undefined ) {
  43814. switch ( value.length ) {
  43815. case 2:
  43816. gl.vertexAttrib2fv( programAttribute.location, value );
  43817. break;
  43818. case 3:
  43819. gl.vertexAttrib3fv( programAttribute.location, value );
  43820. break;
  43821. case 4:
  43822. gl.vertexAttrib4fv( programAttribute.location, value );
  43823. break;
  43824. default:
  43825. gl.vertexAttrib1fv( programAttribute.location, value );
  43826. }
  43827. }
  43828. }
  43829. }
  43830. }
  43831. disableUnusedAttributes();
  43832. }
  43833. function dispose() {
  43834. reset();
  43835. for ( const geometryId in bindingStates ) {
  43836. const programMap = bindingStates[ geometryId ];
  43837. for ( const programId in programMap ) {
  43838. const stateMap = programMap[ programId ];
  43839. for ( const wireframe in stateMap ) {
  43840. deleteVertexArrayObject( stateMap[ wireframe ].object );
  43841. delete stateMap[ wireframe ];
  43842. }
  43843. delete programMap[ programId ];
  43844. }
  43845. delete bindingStates[ geometryId ];
  43846. }
  43847. }
  43848. function releaseStatesOfGeometry( geometry ) {
  43849. if ( bindingStates[ geometry.id ] === undefined ) return;
  43850. const programMap = bindingStates[ geometry.id ];
  43851. for ( const programId in programMap ) {
  43852. const stateMap = programMap[ programId ];
  43853. for ( const wireframe in stateMap ) {
  43854. deleteVertexArrayObject( stateMap[ wireframe ].object );
  43855. delete stateMap[ wireframe ];
  43856. }
  43857. delete programMap[ programId ];
  43858. }
  43859. delete bindingStates[ geometry.id ];
  43860. }
  43861. function releaseStatesOfProgram( program ) {
  43862. for ( const geometryId in bindingStates ) {
  43863. const programMap = bindingStates[ geometryId ];
  43864. if ( programMap[ program.id ] === undefined ) continue;
  43865. const stateMap = programMap[ program.id ];
  43866. for ( const wireframe in stateMap ) {
  43867. deleteVertexArrayObject( stateMap[ wireframe ].object );
  43868. delete stateMap[ wireframe ];
  43869. }
  43870. delete programMap[ program.id ];
  43871. }
  43872. }
  43873. function reset() {
  43874. resetDefaultState();
  43875. forceUpdate = true;
  43876. if ( currentState === defaultState ) return;
  43877. currentState = defaultState;
  43878. bindVertexArrayObject( currentState.object );
  43879. }
  43880. // for backward-compatibility
  43881. function resetDefaultState() {
  43882. defaultState.geometry = null;
  43883. defaultState.program = null;
  43884. defaultState.wireframe = false;
  43885. }
  43886. return {
  43887. setup: setup,
  43888. reset: reset,
  43889. resetDefaultState: resetDefaultState,
  43890. dispose: dispose,
  43891. releaseStatesOfGeometry: releaseStatesOfGeometry,
  43892. releaseStatesOfProgram: releaseStatesOfProgram,
  43893. initAttributes: initAttributes,
  43894. enableAttribute: enableAttribute,
  43895. disableUnusedAttributes: disableUnusedAttributes
  43896. };
  43897. }
  43898. function WebGLBufferRenderer( gl, extensions, info ) {
  43899. let mode;
  43900. function setMode( value ) {
  43901. mode = value;
  43902. }
  43903. function render( start, count ) {
  43904. gl.drawArrays( mode, start, count );
  43905. info.update( count, mode, 1 );
  43906. }
  43907. function renderInstances( start, count, primcount ) {
  43908. if ( primcount === 0 ) return;
  43909. gl.drawArraysInstanced( mode, start, count, primcount );
  43910. info.update( count, mode, primcount );
  43911. }
  43912. function renderMultiDraw( starts, counts, drawCount ) {
  43913. if ( drawCount === 0 ) return;
  43914. const extension = extensions.get( 'WEBGL_multi_draw' );
  43915. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  43916. let elementCount = 0;
  43917. for ( let i = 0; i < drawCount; i ++ ) {
  43918. elementCount += counts[ i ];
  43919. }
  43920. info.update( elementCount, mode, 1 );
  43921. }
  43922. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  43923. if ( drawCount === 0 ) return;
  43924. const extension = extensions.get( 'WEBGL_multi_draw' );
  43925. if ( extension === null ) {
  43926. for ( let i = 0; i < starts.length; i ++ ) {
  43927. renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  43928. }
  43929. } else {
  43930. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  43931. let elementCount = 0;
  43932. for ( let i = 0; i < drawCount; i ++ ) {
  43933. elementCount += counts[ i ] * primcount[ i ];
  43934. }
  43935. info.update( elementCount, mode, 1 );
  43936. }
  43937. }
  43938. //
  43939. this.setMode = setMode;
  43940. this.render = render;
  43941. this.renderInstances = renderInstances;
  43942. this.renderMultiDraw = renderMultiDraw;
  43943. this.renderMultiDrawInstances = renderMultiDrawInstances;
  43944. }
  43945. function WebGLCapabilities( gl, extensions, parameters, utils ) {
  43946. let maxAnisotropy;
  43947. function getMaxAnisotropy() {
  43948. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  43949. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  43950. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  43951. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  43952. } else {
  43953. maxAnisotropy = 0;
  43954. }
  43955. return maxAnisotropy;
  43956. }
  43957. function textureFormatReadable( textureFormat ) {
  43958. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  43959. return false;
  43960. }
  43961. return true;
  43962. }
  43963. function textureTypeReadable( textureType ) {
  43964. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) );
  43965. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  43966. textureType !== FloatType && ! halfFloatSupportedByExt ) {
  43967. return false;
  43968. }
  43969. return true;
  43970. }
  43971. function getMaxPrecision( precision ) {
  43972. if ( precision === 'highp' ) {
  43973. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  43974. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  43975. return 'highp';
  43976. }
  43977. precision = 'mediump';
  43978. }
  43979. if ( precision === 'mediump' ) {
  43980. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  43981. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  43982. return 'mediump';
  43983. }
  43984. }
  43985. return 'lowp';
  43986. }
  43987. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  43988. const maxPrecision = getMaxPrecision( precision );
  43989. if ( maxPrecision !== precision ) {
  43990. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  43991. precision = maxPrecision;
  43992. }
  43993. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  43994. const reversedDepthBuffer = parameters.reversedDepthBuffer === true && extensions.has( 'EXT_clip_control' );
  43995. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  43996. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  43997. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  43998. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  43999. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  44000. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  44001. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  44002. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  44003. const vertexTextures = maxVertexTextures > 0;
  44004. const maxSamples = gl.getParameter( gl.MAX_SAMPLES );
  44005. return {
  44006. isWebGL2: true, // keeping this for backwards compatibility
  44007. getMaxAnisotropy: getMaxAnisotropy,
  44008. getMaxPrecision: getMaxPrecision,
  44009. textureFormatReadable: textureFormatReadable,
  44010. textureTypeReadable: textureTypeReadable,
  44011. precision: precision,
  44012. logarithmicDepthBuffer: logarithmicDepthBuffer,
  44013. reversedDepthBuffer: reversedDepthBuffer,
  44014. maxTextures: maxTextures,
  44015. maxVertexTextures: maxVertexTextures,
  44016. maxTextureSize: maxTextureSize,
  44017. maxCubemapSize: maxCubemapSize,
  44018. maxAttributes: maxAttributes,
  44019. maxVertexUniforms: maxVertexUniforms,
  44020. maxVaryings: maxVaryings,
  44021. maxFragmentUniforms: maxFragmentUniforms,
  44022. vertexTextures: vertexTextures,
  44023. maxSamples: maxSamples
  44024. };
  44025. }
  44026. function WebGLClipping( properties ) {
  44027. const scope = this;
  44028. let globalState = null,
  44029. numGlobalPlanes = 0,
  44030. localClippingEnabled = false,
  44031. renderingShadows = false;
  44032. const plane = new Plane(),
  44033. viewNormalMatrix = new Matrix3(),
  44034. uniform = { value: null, needsUpdate: false };
  44035. this.uniform = uniform;
  44036. this.numPlanes = 0;
  44037. this.numIntersection = 0;
  44038. this.init = function ( planes, enableLocalClipping ) {
  44039. const enabled =
  44040. planes.length !== 0 ||
  44041. enableLocalClipping ||
  44042. // enable state of previous frame - the clipping code has to
  44043. // run another frame in order to reset the state:
  44044. numGlobalPlanes !== 0 ||
  44045. localClippingEnabled;
  44046. localClippingEnabled = enableLocalClipping;
  44047. numGlobalPlanes = planes.length;
  44048. return enabled;
  44049. };
  44050. this.beginShadows = function () {
  44051. renderingShadows = true;
  44052. projectPlanes( null );
  44053. };
  44054. this.endShadows = function () {
  44055. renderingShadows = false;
  44056. };
  44057. this.setGlobalState = function ( planes, camera ) {
  44058. globalState = projectPlanes( planes, camera, 0 );
  44059. };
  44060. this.setState = function ( material, camera, useCache ) {
  44061. const planes = material.clippingPlanes,
  44062. clipIntersection = material.clipIntersection,
  44063. clipShadows = material.clipShadows;
  44064. const materialProperties = properties.get( material );
  44065. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  44066. // there's no local clipping
  44067. if ( renderingShadows ) {
  44068. // there's no global clipping
  44069. projectPlanes( null );
  44070. } else {
  44071. resetGlobalState();
  44072. }
  44073. } else {
  44074. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  44075. lGlobal = nGlobal * 4;
  44076. let dstArray = materialProperties.clippingState || null;
  44077. uniform.value = dstArray; // ensure unique state
  44078. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  44079. for ( let i = 0; i !== lGlobal; ++ i ) {
  44080. dstArray[ i ] = globalState[ i ];
  44081. }
  44082. materialProperties.clippingState = dstArray;
  44083. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  44084. this.numPlanes += nGlobal;
  44085. }
  44086. };
  44087. function resetGlobalState() {
  44088. if ( uniform.value !== globalState ) {
  44089. uniform.value = globalState;
  44090. uniform.needsUpdate = numGlobalPlanes > 0;
  44091. }
  44092. scope.numPlanes = numGlobalPlanes;
  44093. scope.numIntersection = 0;
  44094. }
  44095. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  44096. const nPlanes = planes !== null ? planes.length : 0;
  44097. let dstArray = null;
  44098. if ( nPlanes !== 0 ) {
  44099. dstArray = uniform.value;
  44100. if ( skipTransform !== true || dstArray === null ) {
  44101. const flatSize = dstOffset + nPlanes * 4,
  44102. viewMatrix = camera.matrixWorldInverse;
  44103. viewNormalMatrix.getNormalMatrix( viewMatrix );
  44104. if ( dstArray === null || dstArray.length < flatSize ) {
  44105. dstArray = new Float32Array( flatSize );
  44106. }
  44107. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  44108. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  44109. plane.normal.toArray( dstArray, i4 );
  44110. dstArray[ i4 + 3 ] = plane.constant;
  44111. }
  44112. }
  44113. uniform.value = dstArray;
  44114. uniform.needsUpdate = true;
  44115. }
  44116. scope.numPlanes = nPlanes;
  44117. scope.numIntersection = 0;
  44118. return dstArray;
  44119. }
  44120. }
  44121. function WebGLCubeMaps( renderer ) {
  44122. let cubemaps = new WeakMap();
  44123. function mapTextureMapping( texture, mapping ) {
  44124. if ( mapping === EquirectangularReflectionMapping ) {
  44125. texture.mapping = CubeReflectionMapping;
  44126. } else if ( mapping === EquirectangularRefractionMapping ) {
  44127. texture.mapping = CubeRefractionMapping;
  44128. }
  44129. return texture;
  44130. }
  44131. function get( texture ) {
  44132. if ( texture && texture.isTexture ) {
  44133. const mapping = texture.mapping;
  44134. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  44135. if ( cubemaps.has( texture ) ) {
  44136. const cubemap = cubemaps.get( texture ).texture;
  44137. return mapTextureMapping( cubemap, texture.mapping );
  44138. } else {
  44139. const image = texture.image;
  44140. if ( image && image.height > 0 ) {
  44141. const renderTarget = new WebGLCubeRenderTarget( image.height );
  44142. renderTarget.fromEquirectangularTexture( renderer, texture );
  44143. cubemaps.set( texture, renderTarget );
  44144. texture.addEventListener( 'dispose', onTextureDispose );
  44145. return mapTextureMapping( renderTarget.texture, texture.mapping );
  44146. } else {
  44147. // image not yet ready. try the conversion next frame
  44148. return null;
  44149. }
  44150. }
  44151. }
  44152. }
  44153. return texture;
  44154. }
  44155. function onTextureDispose( event ) {
  44156. const texture = event.target;
  44157. texture.removeEventListener( 'dispose', onTextureDispose );
  44158. const cubemap = cubemaps.get( texture );
  44159. if ( cubemap !== undefined ) {
  44160. cubemaps.delete( texture );
  44161. cubemap.dispose();
  44162. }
  44163. }
  44164. function dispose() {
  44165. cubemaps = new WeakMap();
  44166. }
  44167. return {
  44168. get: get,
  44169. dispose: dispose
  44170. };
  44171. }
  44172. const LOD_MIN = 4;
  44173. // The standard deviations (radians) associated with the extra mips. These are
  44174. // chosen to approximate a Trowbridge-Reitz distribution function times the
  44175. // geometric shadowing function. These sigma values squared must match the
  44176. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  44177. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  44178. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  44179. // samples and exit early, but not recompile the shader.
  44180. const MAX_SAMPLES = 20;
  44181. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  44182. const _clearColor = /*@__PURE__*/ new Color();
  44183. let _oldTarget = null;
  44184. let _oldActiveCubeFace = 0;
  44185. let _oldActiveMipmapLevel = 0;
  44186. let _oldXrEnabled = false;
  44187. // Golden Ratio
  44188. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  44189. const INV_PHI = 1 / PHI;
  44190. // Vertices of a dodecahedron (except the opposites, which represent the
  44191. // same axis), used as axis directions evenly spread on a sphere.
  44192. const _axisDirections = [
  44193. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  44194. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  44195. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  44196. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  44197. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  44198. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  44199. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  44200. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  44201. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  44202. /*@__PURE__*/ new Vector3( 1, 1, 1 ) ];
  44203. const _origin = /*@__PURE__*/ new Vector3();
  44204. /**
  44205. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  44206. * (PMREM) from a cubeMap environment texture. This allows different levels of
  44207. * blur to be quickly accessed based on material roughness. It is packed into a
  44208. * special CubeUV format that allows us to perform custom interpolation so that
  44209. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  44210. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  44211. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  44212. * higher roughness levels. In this way we maintain resolution to smoothly
  44213. * interpolate diffuse lighting while limiting sampling computation.
  44214. *
  44215. * Paper: Fast, Accurate Image-Based Lighting:
  44216. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  44217. */
  44218. class PMREMGenerator {
  44219. /**
  44220. * Constructs a new PMREM generator.
  44221. *
  44222. * @param {WebGLRenderer} renderer - The renderer.
  44223. */
  44224. constructor( renderer ) {
  44225. this._renderer = renderer;
  44226. this._pingPongRenderTarget = null;
  44227. this._lodMax = 0;
  44228. this._cubeSize = 0;
  44229. this._lodPlanes = [];
  44230. this._sizeLods = [];
  44231. this._sigmas = [];
  44232. this._blurMaterial = null;
  44233. this._cubemapMaterial = null;
  44234. this._equirectMaterial = null;
  44235. this._compileMaterial( this._blurMaterial );
  44236. }
  44237. /**
  44238. * Generates a PMREM from a supplied Scene, which can be faster than using an
  44239. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  44240. * in radians to be applied to the scene before PMREM generation. Optional near
  44241. * and far planes ensure the scene is rendered in its entirety.
  44242. *
  44243. * @param {Scene} scene - The scene to be captured.
  44244. * @param {number} [sigma=0] - The blur radius in radians.
  44245. * @param {number} [near=0.1] - The near plane distance.
  44246. * @param {number} [far=100] - The far plane distance.
  44247. * @param {Object} [options={}] - The configuration options.
  44248. * @param {number} [options.size=256] - The texture size of the PMREM.
  44249. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  44250. * @return {WebGLRenderTarget} The resulting PMREM.
  44251. */
  44252. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  44253. const {
  44254. size = 256,
  44255. position = _origin,
  44256. } = options;
  44257. _oldTarget = this._renderer.getRenderTarget();
  44258. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  44259. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  44260. _oldXrEnabled = this._renderer.xr.enabled;
  44261. this._renderer.xr.enabled = false;
  44262. this._setSize( size );
  44263. const cubeUVRenderTarget = this._allocateTargets();
  44264. cubeUVRenderTarget.depthBuffer = true;
  44265. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  44266. if ( sigma > 0 ) {
  44267. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  44268. }
  44269. this._applyPMREM( cubeUVRenderTarget );
  44270. this._cleanup( cubeUVRenderTarget );
  44271. return cubeUVRenderTarget;
  44272. }
  44273. /**
  44274. * Generates a PMREM from an equirectangular texture, which can be either LDR
  44275. * or HDR. The ideal input image size is 1k (1024 x 512),
  44276. * as this matches best with the 256 x 256 cubemap output.
  44277. *
  44278. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  44279. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  44280. * @return {WebGLRenderTarget} The resulting PMREM.
  44281. */
  44282. fromEquirectangular( equirectangular, renderTarget = null ) {
  44283. return this._fromTexture( equirectangular, renderTarget );
  44284. }
  44285. /**
  44286. * Generates a PMREM from an cubemap texture, which can be either LDR
  44287. * or HDR. The ideal input cube size is 256 x 256,
  44288. * as this matches best with the 256 x 256 cubemap output.
  44289. *
  44290. * @param {Texture} cubemap - The cubemap texture to be converted.
  44291. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  44292. * @return {WebGLRenderTarget} The resulting PMREM.
  44293. */
  44294. fromCubemap( cubemap, renderTarget = null ) {
  44295. return this._fromTexture( cubemap, renderTarget );
  44296. }
  44297. /**
  44298. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  44299. * your texture's network fetch for increased concurrency.
  44300. */
  44301. compileCubemapShader() {
  44302. if ( this._cubemapMaterial === null ) {
  44303. this._cubemapMaterial = _getCubemapMaterial();
  44304. this._compileMaterial( this._cubemapMaterial );
  44305. }
  44306. }
  44307. /**
  44308. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  44309. * your texture's network fetch for increased concurrency.
  44310. */
  44311. compileEquirectangularShader() {
  44312. if ( this._equirectMaterial === null ) {
  44313. this._equirectMaterial = _getEquirectMaterial();
  44314. this._compileMaterial( this._equirectMaterial );
  44315. }
  44316. }
  44317. /**
  44318. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  44319. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  44320. * one of them will cause any others to also become unusable.
  44321. */
  44322. dispose() {
  44323. this._dispose();
  44324. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  44325. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  44326. }
  44327. // private interface
  44328. _setSize( cubeSize ) {
  44329. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  44330. this._cubeSize = Math.pow( 2, this._lodMax );
  44331. }
  44332. _dispose() {
  44333. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  44334. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  44335. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  44336. this._lodPlanes[ i ].dispose();
  44337. }
  44338. }
  44339. _cleanup( outputTarget ) {
  44340. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  44341. this._renderer.xr.enabled = _oldXrEnabled;
  44342. outputTarget.scissorTest = false;
  44343. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  44344. }
  44345. _fromTexture( texture, renderTarget ) {
  44346. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  44347. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  44348. } else { // Equirectangular
  44349. this._setSize( texture.image.width / 4 );
  44350. }
  44351. _oldTarget = this._renderer.getRenderTarget();
  44352. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  44353. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  44354. _oldXrEnabled = this._renderer.xr.enabled;
  44355. this._renderer.xr.enabled = false;
  44356. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  44357. this._textureToCubeUV( texture, cubeUVRenderTarget );
  44358. this._applyPMREM( cubeUVRenderTarget );
  44359. this._cleanup( cubeUVRenderTarget );
  44360. return cubeUVRenderTarget;
  44361. }
  44362. _allocateTargets() {
  44363. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  44364. const height = 4 * this._cubeSize;
  44365. const params = {
  44366. magFilter: LinearFilter,
  44367. minFilter: LinearFilter,
  44368. generateMipmaps: false,
  44369. type: HalfFloatType,
  44370. format: RGBAFormat,
  44371. colorSpace: LinearSRGBColorSpace,
  44372. depthBuffer: false
  44373. };
  44374. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  44375. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  44376. if ( this._pingPongRenderTarget !== null ) {
  44377. this._dispose();
  44378. }
  44379. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  44380. const { _lodMax } = this;
  44381. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  44382. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  44383. }
  44384. return cubeUVRenderTarget;
  44385. }
  44386. _compileMaterial( material ) {
  44387. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  44388. this._renderer.compile( tmpMesh, _flatCamera );
  44389. }
  44390. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  44391. const fov = 90;
  44392. const aspect = 1;
  44393. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  44394. const upSign = [ 1, -1, 1, 1, 1, 1 ];
  44395. const forwardSign = [ 1, 1, 1, -1, -1, -1 ];
  44396. const renderer = this._renderer;
  44397. const originalAutoClear = renderer.autoClear;
  44398. const toneMapping = renderer.toneMapping;
  44399. renderer.getClearColor( _clearColor );
  44400. renderer.toneMapping = NoToneMapping;
  44401. renderer.autoClear = false;
  44402. // https://github.com/mrdoob/three.js/issues/31413#issuecomment-3095966812
  44403. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  44404. if ( reversedDepthBuffer ) {
  44405. renderer.setRenderTarget( cubeUVRenderTarget );
  44406. renderer.clearDepth();
  44407. renderer.setRenderTarget( null );
  44408. }
  44409. const backgroundMaterial = new MeshBasicMaterial( {
  44410. name: 'PMREM.Background',
  44411. side: BackSide,
  44412. depthWrite: false,
  44413. depthTest: false,
  44414. } );
  44415. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  44416. let useSolidColor = false;
  44417. const background = scene.background;
  44418. if ( background ) {
  44419. if ( background.isColor ) {
  44420. backgroundMaterial.color.copy( background );
  44421. scene.background = null;
  44422. useSolidColor = true;
  44423. }
  44424. } else {
  44425. backgroundMaterial.color.copy( _clearColor );
  44426. useSolidColor = true;
  44427. }
  44428. for ( let i = 0; i < 6; i ++ ) {
  44429. const col = i % 3;
  44430. if ( col === 0 ) {
  44431. cubeCamera.up.set( 0, upSign[ i ], 0 );
  44432. cubeCamera.position.set( position.x, position.y, position.z );
  44433. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  44434. } else if ( col === 1 ) {
  44435. cubeCamera.up.set( 0, 0, upSign[ i ] );
  44436. cubeCamera.position.set( position.x, position.y, position.z );
  44437. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  44438. } else {
  44439. cubeCamera.up.set( 0, upSign[ i ], 0 );
  44440. cubeCamera.position.set( position.x, position.y, position.z );
  44441. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  44442. }
  44443. const size = this._cubeSize;
  44444. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  44445. renderer.setRenderTarget( cubeUVRenderTarget );
  44446. if ( useSolidColor ) {
  44447. renderer.render( backgroundBox, cubeCamera );
  44448. }
  44449. renderer.render( scene, cubeCamera );
  44450. }
  44451. backgroundBox.geometry.dispose();
  44452. backgroundBox.material.dispose();
  44453. renderer.toneMapping = toneMapping;
  44454. renderer.autoClear = originalAutoClear;
  44455. scene.background = background;
  44456. }
  44457. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  44458. const renderer = this._renderer;
  44459. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  44460. if ( isCubeTexture ) {
  44461. if ( this._cubemapMaterial === null ) {
  44462. this._cubemapMaterial = _getCubemapMaterial();
  44463. }
  44464. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? -1 : 1;
  44465. } else {
  44466. if ( this._equirectMaterial === null ) {
  44467. this._equirectMaterial = _getEquirectMaterial();
  44468. }
  44469. }
  44470. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  44471. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  44472. const uniforms = material.uniforms;
  44473. uniforms[ 'envMap' ].value = texture;
  44474. const size = this._cubeSize;
  44475. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  44476. renderer.setRenderTarget( cubeUVRenderTarget );
  44477. renderer.render( mesh, _flatCamera );
  44478. }
  44479. _applyPMREM( cubeUVRenderTarget ) {
  44480. const renderer = this._renderer;
  44481. const autoClear = renderer.autoClear;
  44482. renderer.autoClear = false;
  44483. const n = this._lodPlanes.length;
  44484. for ( let i = 1; i < n; i ++ ) {
  44485. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  44486. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  44487. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  44488. }
  44489. renderer.autoClear = autoClear;
  44490. }
  44491. /**
  44492. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  44493. * vertically and horizontally, but this breaks down on a cube. Here we apply
  44494. * the blur latitudinally (around the poles), and then longitudinally (towards
  44495. * the poles) to approximate the orthogonally-separable blur. It is least
  44496. * accurate at the poles, but still does a decent job.
  44497. *
  44498. * @private
  44499. * @param {WebGLRenderTarget} cubeUVRenderTarget
  44500. * @param {number} lodIn
  44501. * @param {number} lodOut
  44502. * @param {number} sigma
  44503. * @param {Vector3} [poleAxis]
  44504. */
  44505. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  44506. const pingPongRenderTarget = this._pingPongRenderTarget;
  44507. this._halfBlur(
  44508. cubeUVRenderTarget,
  44509. pingPongRenderTarget,
  44510. lodIn,
  44511. lodOut,
  44512. sigma,
  44513. 'latitudinal',
  44514. poleAxis );
  44515. this._halfBlur(
  44516. pingPongRenderTarget,
  44517. cubeUVRenderTarget,
  44518. lodOut,
  44519. lodOut,
  44520. sigma,
  44521. 'longitudinal',
  44522. poleAxis );
  44523. }
  44524. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  44525. const renderer = this._renderer;
  44526. const blurMaterial = this._blurMaterial;
  44527. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  44528. console.error(
  44529. 'blur direction must be either latitudinal or longitudinal!' );
  44530. }
  44531. // Number of standard deviations at which to cut off the discrete approximation.
  44532. const STANDARD_DEVIATIONS = 3;
  44533. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  44534. const blurUniforms = blurMaterial.uniforms;
  44535. const pixels = this._sizeLods[ lodIn ] - 1;
  44536. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  44537. const sigmaPixels = sigmaRadians / radiansPerPixel;
  44538. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  44539. if ( samples > MAX_SAMPLES ) {
  44540. console.warn( `sigmaRadians, ${
  44541. sigmaRadians}, is too large and will clip, as it requested ${
  44542. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  44543. }
  44544. const weights = [];
  44545. let sum = 0;
  44546. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  44547. const x = i / sigmaPixels;
  44548. const weight = Math.exp( - x * x / 2 );
  44549. weights.push( weight );
  44550. if ( i === 0 ) {
  44551. sum += weight;
  44552. } else if ( i < samples ) {
  44553. sum += 2 * weight;
  44554. }
  44555. }
  44556. for ( let i = 0; i < weights.length; i ++ ) {
  44557. weights[ i ] = weights[ i ] / sum;
  44558. }
  44559. blurUniforms[ 'envMap' ].value = targetIn.texture;
  44560. blurUniforms[ 'samples' ].value = samples;
  44561. blurUniforms[ 'weights' ].value = weights;
  44562. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  44563. if ( poleAxis ) {
  44564. blurUniforms[ 'poleAxis' ].value = poleAxis;
  44565. }
  44566. const { _lodMax } = this;
  44567. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  44568. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  44569. const outputSize = this._sizeLods[ lodOut ];
  44570. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  44571. const y = 4 * ( this._cubeSize - outputSize );
  44572. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  44573. renderer.setRenderTarget( targetOut );
  44574. renderer.render( blurMesh, _flatCamera );
  44575. }
  44576. }
  44577. function _createPlanes( lodMax ) {
  44578. const lodPlanes = [];
  44579. const sizeLods = [];
  44580. const sigmas = [];
  44581. let lod = lodMax;
  44582. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  44583. for ( let i = 0; i < totalLods; i ++ ) {
  44584. const sizeLod = Math.pow( 2, lod );
  44585. sizeLods.push( sizeLod );
  44586. let sigma = 1.0 / sizeLod;
  44587. if ( i > lodMax - LOD_MIN ) {
  44588. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  44589. } else if ( i === 0 ) {
  44590. sigma = 0;
  44591. }
  44592. sigmas.push( sigma );
  44593. const texelSize = 1.0 / ( sizeLod - 2 );
  44594. const min = - texelSize;
  44595. const max = 1 + texelSize;
  44596. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  44597. const cubeFaces = 6;
  44598. const vertices = 6;
  44599. const positionSize = 3;
  44600. const uvSize = 2;
  44601. const faceIndexSize = 1;
  44602. const position = new Float32Array( positionSize * vertices * cubeFaces );
  44603. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  44604. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  44605. for ( let face = 0; face < cubeFaces; face ++ ) {
  44606. const x = ( face % 3 ) * 2 / 3 - 1;
  44607. const y = face > 2 ? 0 : -1;
  44608. const coordinates = [
  44609. x, y, 0,
  44610. x + 2 / 3, y, 0,
  44611. x + 2 / 3, y + 1, 0,
  44612. x, y, 0,
  44613. x + 2 / 3, y + 1, 0,
  44614. x, y + 1, 0
  44615. ];
  44616. position.set( coordinates, positionSize * vertices * face );
  44617. uv.set( uv1, uvSize * vertices * face );
  44618. const fill = [ face, face, face, face, face, face ];
  44619. faceIndex.set( fill, faceIndexSize * vertices * face );
  44620. }
  44621. const planes = new BufferGeometry();
  44622. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  44623. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  44624. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  44625. lodPlanes.push( planes );
  44626. if ( lod > LOD_MIN ) {
  44627. lod --;
  44628. }
  44629. }
  44630. return { lodPlanes, sizeLods, sigmas };
  44631. }
  44632. function _createRenderTarget( width, height, params ) {
  44633. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  44634. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  44635. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  44636. cubeUVRenderTarget.scissorTest = true;
  44637. return cubeUVRenderTarget;
  44638. }
  44639. function _setViewport( target, x, y, width, height ) {
  44640. target.viewport.set( x, y, width, height );
  44641. target.scissor.set( x, y, width, height );
  44642. }
  44643. function _getBlurShader( lodMax, width, height ) {
  44644. const weights = new Float32Array( MAX_SAMPLES );
  44645. const poleAxis = new Vector3( 0, 1, 0 );
  44646. const shaderMaterial = new ShaderMaterial( {
  44647. name: 'SphericalGaussianBlur',
  44648. defines: {
  44649. 'n': MAX_SAMPLES,
  44650. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  44651. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  44652. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  44653. },
  44654. uniforms: {
  44655. 'envMap': { value: null },
  44656. 'samples': { value: 1 },
  44657. 'weights': { value: weights },
  44658. 'latitudinal': { value: false },
  44659. 'dTheta': { value: 0 },
  44660. 'mipInt': { value: 0 },
  44661. 'poleAxis': { value: poleAxis }
  44662. },
  44663. vertexShader: _getCommonVertexShader(),
  44664. fragmentShader: /* glsl */`
  44665. precision mediump float;
  44666. precision mediump int;
  44667. varying vec3 vOutputDirection;
  44668. uniform sampler2D envMap;
  44669. uniform int samples;
  44670. uniform float weights[ n ];
  44671. uniform bool latitudinal;
  44672. uniform float dTheta;
  44673. uniform float mipInt;
  44674. uniform vec3 poleAxis;
  44675. #define ENVMAP_TYPE_CUBE_UV
  44676. #include <cube_uv_reflection_fragment>
  44677. vec3 getSample( float theta, vec3 axis ) {
  44678. float cosTheta = cos( theta );
  44679. // Rodrigues' axis-angle rotation
  44680. vec3 sampleDirection = vOutputDirection * cosTheta
  44681. + cross( axis, vOutputDirection ) * sin( theta )
  44682. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  44683. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  44684. }
  44685. void main() {
  44686. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  44687. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  44688. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  44689. }
  44690. axis = normalize( axis );
  44691. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  44692. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  44693. for ( int i = 1; i < n; i++ ) {
  44694. if ( i >= samples ) {
  44695. break;
  44696. }
  44697. float theta = dTheta * float( i );
  44698. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  44699. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  44700. }
  44701. }
  44702. `,
  44703. blending: NoBlending,
  44704. depthTest: false,
  44705. depthWrite: false
  44706. } );
  44707. return shaderMaterial;
  44708. }
  44709. function _getEquirectMaterial() {
  44710. return new ShaderMaterial( {
  44711. name: 'EquirectangularToCubeUV',
  44712. uniforms: {
  44713. 'envMap': { value: null }
  44714. },
  44715. vertexShader: _getCommonVertexShader(),
  44716. fragmentShader: /* glsl */`
  44717. precision mediump float;
  44718. precision mediump int;
  44719. varying vec3 vOutputDirection;
  44720. uniform sampler2D envMap;
  44721. #include <common>
  44722. void main() {
  44723. vec3 outputDirection = normalize( vOutputDirection );
  44724. vec2 uv = equirectUv( outputDirection );
  44725. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  44726. }
  44727. `,
  44728. blending: NoBlending,
  44729. depthTest: false,
  44730. depthWrite: false
  44731. } );
  44732. }
  44733. function _getCubemapMaterial() {
  44734. return new ShaderMaterial( {
  44735. name: 'CubemapToCubeUV',
  44736. uniforms: {
  44737. 'envMap': { value: null },
  44738. 'flipEnvMap': { value: -1 }
  44739. },
  44740. vertexShader: _getCommonVertexShader(),
  44741. fragmentShader: /* glsl */`
  44742. precision mediump float;
  44743. precision mediump int;
  44744. uniform float flipEnvMap;
  44745. varying vec3 vOutputDirection;
  44746. uniform samplerCube envMap;
  44747. void main() {
  44748. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  44749. }
  44750. `,
  44751. blending: NoBlending,
  44752. depthTest: false,
  44753. depthWrite: false
  44754. } );
  44755. }
  44756. function _getCommonVertexShader() {
  44757. return /* glsl */`
  44758. precision mediump float;
  44759. precision mediump int;
  44760. attribute float faceIndex;
  44761. varying vec3 vOutputDirection;
  44762. // RH coordinate system; PMREM face-indexing convention
  44763. vec3 getDirection( vec2 uv, float face ) {
  44764. uv = 2.0 * uv - 1.0;
  44765. vec3 direction = vec3( uv, 1.0 );
  44766. if ( face == 0.0 ) {
  44767. direction = direction.zyx; // ( 1, v, u ) pos x
  44768. } else if ( face == 1.0 ) {
  44769. direction = direction.xzy;
  44770. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  44771. } else if ( face == 2.0 ) {
  44772. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  44773. } else if ( face == 3.0 ) {
  44774. direction = direction.zyx;
  44775. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  44776. } else if ( face == 4.0 ) {
  44777. direction = direction.xzy;
  44778. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  44779. } else if ( face == 5.0 ) {
  44780. direction.z *= -1.0; // ( u, v, -1 ) neg z
  44781. }
  44782. return direction;
  44783. }
  44784. void main() {
  44785. vOutputDirection = getDirection( uv, faceIndex );
  44786. gl_Position = vec4( position, 1.0 );
  44787. }
  44788. `;
  44789. }
  44790. function WebGLCubeUVMaps( renderer ) {
  44791. let cubeUVmaps = new WeakMap();
  44792. let pmremGenerator = null;
  44793. function get( texture ) {
  44794. if ( texture && texture.isTexture ) {
  44795. const mapping = texture.mapping;
  44796. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  44797. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  44798. // equirect/cube map to cubeUV conversion
  44799. if ( isEquirectMap || isCubeMap ) {
  44800. let renderTarget = cubeUVmaps.get( texture );
  44801. const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0;
  44802. if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) {
  44803. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  44804. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  44805. renderTarget.texture.pmremVersion = texture.pmremVersion;
  44806. cubeUVmaps.set( texture, renderTarget );
  44807. return renderTarget.texture;
  44808. } else {
  44809. if ( renderTarget !== undefined ) {
  44810. return renderTarget.texture;
  44811. } else {
  44812. const image = texture.image;
  44813. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  44814. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  44815. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  44816. renderTarget.texture.pmremVersion = texture.pmremVersion;
  44817. cubeUVmaps.set( texture, renderTarget );
  44818. texture.addEventListener( 'dispose', onTextureDispose );
  44819. return renderTarget.texture;
  44820. } else {
  44821. // image not yet ready. try the conversion next frame
  44822. return null;
  44823. }
  44824. }
  44825. }
  44826. }
  44827. }
  44828. return texture;
  44829. }
  44830. function isCubeTextureComplete( image ) {
  44831. let count = 0;
  44832. const length = 6;
  44833. for ( let i = 0; i < length; i ++ ) {
  44834. if ( image[ i ] !== undefined ) count ++;
  44835. }
  44836. return count === length;
  44837. }
  44838. function onTextureDispose( event ) {
  44839. const texture = event.target;
  44840. texture.removeEventListener( 'dispose', onTextureDispose );
  44841. const cubemapUV = cubeUVmaps.get( texture );
  44842. if ( cubemapUV !== undefined ) {
  44843. cubeUVmaps.delete( texture );
  44844. cubemapUV.dispose();
  44845. }
  44846. }
  44847. function dispose() {
  44848. cubeUVmaps = new WeakMap();
  44849. if ( pmremGenerator !== null ) {
  44850. pmremGenerator.dispose();
  44851. pmremGenerator = null;
  44852. }
  44853. }
  44854. return {
  44855. get: get,
  44856. dispose: dispose
  44857. };
  44858. }
  44859. function WebGLExtensions( gl ) {
  44860. const extensions = {};
  44861. function getExtension( name ) {
  44862. if ( extensions[ name ] !== undefined ) {
  44863. return extensions[ name ];
  44864. }
  44865. let extension;
  44866. switch ( name ) {
  44867. case 'WEBGL_depth_texture':
  44868. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  44869. break;
  44870. case 'EXT_texture_filter_anisotropic':
  44871. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  44872. break;
  44873. case 'WEBGL_compressed_texture_s3tc':
  44874. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  44875. break;
  44876. case 'WEBGL_compressed_texture_pvrtc':
  44877. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  44878. break;
  44879. default:
  44880. extension = gl.getExtension( name );
  44881. }
  44882. extensions[ name ] = extension;
  44883. return extension;
  44884. }
  44885. return {
  44886. has: function ( name ) {
  44887. return getExtension( name ) !== null;
  44888. },
  44889. init: function () {
  44890. getExtension( 'EXT_color_buffer_float' );
  44891. getExtension( 'WEBGL_clip_cull_distance' );
  44892. getExtension( 'OES_texture_float_linear' );
  44893. getExtension( 'EXT_color_buffer_half_float' );
  44894. getExtension( 'WEBGL_multisampled_render_to_texture' );
  44895. getExtension( 'WEBGL_render_shared_exponent' );
  44896. },
  44897. get: function ( name ) {
  44898. const extension = getExtension( name );
  44899. if ( extension === null ) {
  44900. warnOnce( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  44901. }
  44902. return extension;
  44903. }
  44904. };
  44905. }
  44906. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  44907. const geometries = {};
  44908. const wireframeAttributes = new WeakMap();
  44909. function onGeometryDispose( event ) {
  44910. const geometry = event.target;
  44911. if ( geometry.index !== null ) {
  44912. attributes.remove( geometry.index );
  44913. }
  44914. for ( const name in geometry.attributes ) {
  44915. attributes.remove( geometry.attributes[ name ] );
  44916. }
  44917. geometry.removeEventListener( 'dispose', onGeometryDispose );
  44918. delete geometries[ geometry.id ];
  44919. const attribute = wireframeAttributes.get( geometry );
  44920. if ( attribute ) {
  44921. attributes.remove( attribute );
  44922. wireframeAttributes.delete( geometry );
  44923. }
  44924. bindingStates.releaseStatesOfGeometry( geometry );
  44925. if ( geometry.isInstancedBufferGeometry === true ) {
  44926. delete geometry._maxInstanceCount;
  44927. }
  44928. //
  44929. info.memory.geometries --;
  44930. }
  44931. function get( object, geometry ) {
  44932. if ( geometries[ geometry.id ] === true ) return geometry;
  44933. geometry.addEventListener( 'dispose', onGeometryDispose );
  44934. geometries[ geometry.id ] = true;
  44935. info.memory.geometries ++;
  44936. return geometry;
  44937. }
  44938. function update( geometry ) {
  44939. const geometryAttributes = geometry.attributes;
  44940. // Updating index buffer in VAO now. See WebGLBindingStates.
  44941. for ( const name in geometryAttributes ) {
  44942. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  44943. }
  44944. }
  44945. function updateWireframeAttribute( geometry ) {
  44946. const indices = [];
  44947. const geometryIndex = geometry.index;
  44948. const geometryPosition = geometry.attributes.position;
  44949. let version = 0;
  44950. if ( geometryIndex !== null ) {
  44951. const array = geometryIndex.array;
  44952. version = geometryIndex.version;
  44953. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  44954. const a = array[ i + 0 ];
  44955. const b = array[ i + 1 ];
  44956. const c = array[ i + 2 ];
  44957. indices.push( a, b, b, c, c, a );
  44958. }
  44959. } else if ( geometryPosition !== undefined ) {
  44960. const array = geometryPosition.array;
  44961. version = geometryPosition.version;
  44962. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  44963. const a = i + 0;
  44964. const b = i + 1;
  44965. const c = i + 2;
  44966. indices.push( a, b, b, c, c, a );
  44967. }
  44968. } else {
  44969. return;
  44970. }
  44971. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  44972. attribute.version = version;
  44973. // Updating index buffer in VAO now. See WebGLBindingStates
  44974. //
  44975. const previousAttribute = wireframeAttributes.get( geometry );
  44976. if ( previousAttribute ) attributes.remove( previousAttribute );
  44977. //
  44978. wireframeAttributes.set( geometry, attribute );
  44979. }
  44980. function getWireframeAttribute( geometry ) {
  44981. const currentAttribute = wireframeAttributes.get( geometry );
  44982. if ( currentAttribute ) {
  44983. const geometryIndex = geometry.index;
  44984. if ( geometryIndex !== null ) {
  44985. // if the attribute is obsolete, create a new one
  44986. if ( currentAttribute.version < geometryIndex.version ) {
  44987. updateWireframeAttribute( geometry );
  44988. }
  44989. }
  44990. } else {
  44991. updateWireframeAttribute( geometry );
  44992. }
  44993. return wireframeAttributes.get( geometry );
  44994. }
  44995. return {
  44996. get: get,
  44997. update: update,
  44998. getWireframeAttribute: getWireframeAttribute
  44999. };
  45000. }
  45001. function WebGLIndexedBufferRenderer( gl, extensions, info ) {
  45002. let mode;
  45003. function setMode( value ) {
  45004. mode = value;
  45005. }
  45006. let type, bytesPerElement;
  45007. function setIndex( value ) {
  45008. type = value.type;
  45009. bytesPerElement = value.bytesPerElement;
  45010. }
  45011. function render( start, count ) {
  45012. gl.drawElements( mode, count, type, start * bytesPerElement );
  45013. info.update( count, mode, 1 );
  45014. }
  45015. function renderInstances( start, count, primcount ) {
  45016. if ( primcount === 0 ) return;
  45017. gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount );
  45018. info.update( count, mode, primcount );
  45019. }
  45020. function renderMultiDraw( starts, counts, drawCount ) {
  45021. if ( drawCount === 0 ) return;
  45022. const extension = extensions.get( 'WEBGL_multi_draw' );
  45023. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  45024. let elementCount = 0;
  45025. for ( let i = 0; i < drawCount; i ++ ) {
  45026. elementCount += counts[ i ];
  45027. }
  45028. info.update( elementCount, mode, 1 );
  45029. }
  45030. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  45031. if ( drawCount === 0 ) return;
  45032. const extension = extensions.get( 'WEBGL_multi_draw' );
  45033. if ( extension === null ) {
  45034. for ( let i = 0; i < starts.length; i ++ ) {
  45035. renderInstances( starts[ i ] / bytesPerElement, counts[ i ], primcount[ i ] );
  45036. }
  45037. } else {
  45038. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, type, starts, 0, primcount, 0, drawCount );
  45039. let elementCount = 0;
  45040. for ( let i = 0; i < drawCount; i ++ ) {
  45041. elementCount += counts[ i ] * primcount[ i ];
  45042. }
  45043. info.update( elementCount, mode, 1 );
  45044. }
  45045. }
  45046. //
  45047. this.setMode = setMode;
  45048. this.setIndex = setIndex;
  45049. this.render = render;
  45050. this.renderInstances = renderInstances;
  45051. this.renderMultiDraw = renderMultiDraw;
  45052. this.renderMultiDrawInstances = renderMultiDrawInstances;
  45053. }
  45054. function WebGLInfo( gl ) {
  45055. const memory = {
  45056. geometries: 0,
  45057. textures: 0
  45058. };
  45059. const render = {
  45060. frame: 0,
  45061. calls: 0,
  45062. triangles: 0,
  45063. points: 0,
  45064. lines: 0
  45065. };
  45066. function update( count, mode, instanceCount ) {
  45067. render.calls ++;
  45068. switch ( mode ) {
  45069. case gl.TRIANGLES:
  45070. render.triangles += instanceCount * ( count / 3 );
  45071. break;
  45072. case gl.LINES:
  45073. render.lines += instanceCount * ( count / 2 );
  45074. break;
  45075. case gl.LINE_STRIP:
  45076. render.lines += instanceCount * ( count - 1 );
  45077. break;
  45078. case gl.LINE_LOOP:
  45079. render.lines += instanceCount * count;
  45080. break;
  45081. case gl.POINTS:
  45082. render.points += instanceCount * count;
  45083. break;
  45084. default:
  45085. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  45086. break;
  45087. }
  45088. }
  45089. function reset() {
  45090. render.calls = 0;
  45091. render.triangles = 0;
  45092. render.points = 0;
  45093. render.lines = 0;
  45094. }
  45095. return {
  45096. memory: memory,
  45097. render: render,
  45098. programs: null,
  45099. autoReset: true,
  45100. reset: reset,
  45101. update: update
  45102. };
  45103. }
  45104. function WebGLMorphtargets( gl, capabilities, textures ) {
  45105. const morphTextures = new WeakMap();
  45106. const morph = new Vector4();
  45107. function update( object, geometry, program ) {
  45108. const objectInfluences = object.morphTargetInfluences;
  45109. // the following encodes morph targets into an array of data textures. Each layer represents a single morph target.
  45110. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  45111. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  45112. let entry = morphTextures.get( geometry );
  45113. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  45114. if ( entry !== undefined ) entry.texture.dispose();
  45115. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  45116. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  45117. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  45118. const morphTargets = geometry.morphAttributes.position || [];
  45119. const morphNormals = geometry.morphAttributes.normal || [];
  45120. const morphColors = geometry.morphAttributes.color || [];
  45121. let vertexDataCount = 0;
  45122. if ( hasMorphPosition === true ) vertexDataCount = 1;
  45123. if ( hasMorphNormals === true ) vertexDataCount = 2;
  45124. if ( hasMorphColors === true ) vertexDataCount = 3;
  45125. let width = geometry.attributes.position.count * vertexDataCount;
  45126. let height = 1;
  45127. if ( width > capabilities.maxTextureSize ) {
  45128. height = Math.ceil( width / capabilities.maxTextureSize );
  45129. width = capabilities.maxTextureSize;
  45130. }
  45131. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  45132. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  45133. texture.type = FloatType;
  45134. texture.needsUpdate = true;
  45135. // fill buffer
  45136. const vertexDataStride = vertexDataCount * 4;
  45137. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  45138. const morphTarget = morphTargets[ i ];
  45139. const morphNormal = morphNormals[ i ];
  45140. const morphColor = morphColors[ i ];
  45141. const offset = width * height * 4 * i;
  45142. for ( let j = 0; j < morphTarget.count; j ++ ) {
  45143. const stride = j * vertexDataStride;
  45144. if ( hasMorphPosition === true ) {
  45145. morph.fromBufferAttribute( morphTarget, j );
  45146. buffer[ offset + stride + 0 ] = morph.x;
  45147. buffer[ offset + stride + 1 ] = morph.y;
  45148. buffer[ offset + stride + 2 ] = morph.z;
  45149. buffer[ offset + stride + 3 ] = 0;
  45150. }
  45151. if ( hasMorphNormals === true ) {
  45152. morph.fromBufferAttribute( morphNormal, j );
  45153. buffer[ offset + stride + 4 ] = morph.x;
  45154. buffer[ offset + stride + 5 ] = morph.y;
  45155. buffer[ offset + stride + 6 ] = morph.z;
  45156. buffer[ offset + stride + 7 ] = 0;
  45157. }
  45158. if ( hasMorphColors === true ) {
  45159. morph.fromBufferAttribute( morphColor, j );
  45160. buffer[ offset + stride + 8 ] = morph.x;
  45161. buffer[ offset + stride + 9 ] = morph.y;
  45162. buffer[ offset + stride + 10 ] = morph.z;
  45163. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  45164. }
  45165. }
  45166. }
  45167. entry = {
  45168. count: morphTargetsCount,
  45169. texture: texture,
  45170. size: new Vector2( width, height )
  45171. };
  45172. morphTextures.set( geometry, entry );
  45173. function disposeTexture() {
  45174. texture.dispose();
  45175. morphTextures.delete( geometry );
  45176. geometry.removeEventListener( 'dispose', disposeTexture );
  45177. }
  45178. geometry.addEventListener( 'dispose', disposeTexture );
  45179. }
  45180. //
  45181. if ( object.isInstancedMesh === true && object.morphTexture !== null ) {
  45182. program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures );
  45183. } else {
  45184. let morphInfluencesSum = 0;
  45185. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  45186. morphInfluencesSum += objectInfluences[ i ];
  45187. }
  45188. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  45189. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  45190. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  45191. }
  45192. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  45193. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  45194. }
  45195. return {
  45196. update: update
  45197. };
  45198. }
  45199. function WebGLObjects( gl, geometries, attributes, info ) {
  45200. let updateMap = new WeakMap();
  45201. function update( object ) {
  45202. const frame = info.render.frame;
  45203. const geometry = object.geometry;
  45204. const buffergeometry = geometries.get( object, geometry );
  45205. // Update once per frame
  45206. if ( updateMap.get( buffergeometry ) !== frame ) {
  45207. geometries.update( buffergeometry );
  45208. updateMap.set( buffergeometry, frame );
  45209. }
  45210. if ( object.isInstancedMesh ) {
  45211. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  45212. object.addEventListener( 'dispose', onInstancedMeshDispose );
  45213. }
  45214. if ( updateMap.get( object ) !== frame ) {
  45215. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  45216. if ( object.instanceColor !== null ) {
  45217. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  45218. }
  45219. updateMap.set( object, frame );
  45220. }
  45221. }
  45222. if ( object.isSkinnedMesh ) {
  45223. const skeleton = object.skeleton;
  45224. if ( updateMap.get( skeleton ) !== frame ) {
  45225. skeleton.update();
  45226. updateMap.set( skeleton, frame );
  45227. }
  45228. }
  45229. return buffergeometry;
  45230. }
  45231. function dispose() {
  45232. updateMap = new WeakMap();
  45233. }
  45234. function onInstancedMeshDispose( event ) {
  45235. const instancedMesh = event.target;
  45236. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  45237. attributes.remove( instancedMesh.instanceMatrix );
  45238. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  45239. }
  45240. return {
  45241. update: update,
  45242. dispose: dispose
  45243. };
  45244. }
  45245. /**
  45246. * Uniforms of a program.
  45247. * Those form a tree structure with a special top-level container for the root,
  45248. * which you get by calling 'new WebGLUniforms( gl, program )'.
  45249. *
  45250. *
  45251. * Properties of inner nodes including the top-level container:
  45252. *
  45253. * .seq - array of nested uniforms
  45254. * .map - nested uniforms by name
  45255. *
  45256. *
  45257. * Methods of all nodes except the top-level container:
  45258. *
  45259. * .setValue( gl, value, [textures] )
  45260. *
  45261. * uploads a uniform value(s)
  45262. * the 'textures' parameter is needed for sampler uniforms
  45263. *
  45264. *
  45265. * Static methods of the top-level container (textures factorizations):
  45266. *
  45267. * .upload( gl, seq, values, textures )
  45268. *
  45269. * sets uniforms in 'seq' to 'values[id].value'
  45270. *
  45271. * .seqWithValue( seq, values ) : filteredSeq
  45272. *
  45273. * filters 'seq' entries with corresponding entry in values
  45274. *
  45275. *
  45276. * Methods of the top-level container (textures factorizations):
  45277. *
  45278. * .setValue( gl, name, value, textures )
  45279. *
  45280. * sets uniform with name 'name' to 'value'
  45281. *
  45282. * .setOptional( gl, obj, prop )
  45283. *
  45284. * like .set for an optional property of the object
  45285. *
  45286. */
  45287. const emptyTexture = /*@__PURE__*/ new Texture();
  45288. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  45289. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  45290. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  45291. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  45292. // --- Utilities ---
  45293. // Array Caches (provide typed arrays for temporary by size)
  45294. const arrayCacheF32 = [];
  45295. const arrayCacheI32 = [];
  45296. // Float32Array caches used for uploading Matrix uniforms
  45297. const mat4array = new Float32Array( 16 );
  45298. const mat3array = new Float32Array( 9 );
  45299. const mat2array = new Float32Array( 4 );
  45300. // Flattening for arrays of vectors and matrices
  45301. function flatten( array, nBlocks, blockSize ) {
  45302. const firstElem = array[ 0 ];
  45303. if ( firstElem <= 0 || firstElem > 0 ) return array;
  45304. // unoptimized: ! isNaN( firstElem )
  45305. // see http://jacksondunstan.com/articles/983
  45306. const n = nBlocks * blockSize;
  45307. let r = arrayCacheF32[ n ];
  45308. if ( r === undefined ) {
  45309. r = new Float32Array( n );
  45310. arrayCacheF32[ n ] = r;
  45311. }
  45312. if ( nBlocks !== 0 ) {
  45313. firstElem.toArray( r, 0 );
  45314. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  45315. offset += blockSize;
  45316. array[ i ].toArray( r, offset );
  45317. }
  45318. }
  45319. return r;
  45320. }
  45321. function arraysEqual( a, b ) {
  45322. if ( a.length !== b.length ) return false;
  45323. for ( let i = 0, l = a.length; i < l; i ++ ) {
  45324. if ( a[ i ] !== b[ i ] ) return false;
  45325. }
  45326. return true;
  45327. }
  45328. function copyArray( a, b ) {
  45329. for ( let i = 0, l = b.length; i < l; i ++ ) {
  45330. a[ i ] = b[ i ];
  45331. }
  45332. }
  45333. // Texture unit allocation
  45334. function allocTexUnits( textures, n ) {
  45335. let r = arrayCacheI32[ n ];
  45336. if ( r === undefined ) {
  45337. r = new Int32Array( n );
  45338. arrayCacheI32[ n ] = r;
  45339. }
  45340. for ( let i = 0; i !== n; ++ i ) {
  45341. r[ i ] = textures.allocateTextureUnit();
  45342. }
  45343. return r;
  45344. }
  45345. // --- Setters ---
  45346. // Note: Defining these methods externally, because they come in a bunch
  45347. // and this way their names minify.
  45348. // Single scalar
  45349. function setValueV1f( gl, v ) {
  45350. const cache = this.cache;
  45351. if ( cache[ 0 ] === v ) return;
  45352. gl.uniform1f( this.addr, v );
  45353. cache[ 0 ] = v;
  45354. }
  45355. // Single float vector (from flat array or THREE.VectorN)
  45356. function setValueV2f( gl, v ) {
  45357. const cache = this.cache;
  45358. if ( v.x !== undefined ) {
  45359. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  45360. gl.uniform2f( this.addr, v.x, v.y );
  45361. cache[ 0 ] = v.x;
  45362. cache[ 1 ] = v.y;
  45363. }
  45364. } else {
  45365. if ( arraysEqual( cache, v ) ) return;
  45366. gl.uniform2fv( this.addr, v );
  45367. copyArray( cache, v );
  45368. }
  45369. }
  45370. function setValueV3f( gl, v ) {
  45371. const cache = this.cache;
  45372. if ( v.x !== undefined ) {
  45373. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  45374. gl.uniform3f( this.addr, v.x, v.y, v.z );
  45375. cache[ 0 ] = v.x;
  45376. cache[ 1 ] = v.y;
  45377. cache[ 2 ] = v.z;
  45378. }
  45379. } else if ( v.r !== undefined ) {
  45380. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  45381. gl.uniform3f( this.addr, v.r, v.g, v.b );
  45382. cache[ 0 ] = v.r;
  45383. cache[ 1 ] = v.g;
  45384. cache[ 2 ] = v.b;
  45385. }
  45386. } else {
  45387. if ( arraysEqual( cache, v ) ) return;
  45388. gl.uniform3fv( this.addr, v );
  45389. copyArray( cache, v );
  45390. }
  45391. }
  45392. function setValueV4f( gl, v ) {
  45393. const cache = this.cache;
  45394. if ( v.x !== undefined ) {
  45395. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  45396. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  45397. cache[ 0 ] = v.x;
  45398. cache[ 1 ] = v.y;
  45399. cache[ 2 ] = v.z;
  45400. cache[ 3 ] = v.w;
  45401. }
  45402. } else {
  45403. if ( arraysEqual( cache, v ) ) return;
  45404. gl.uniform4fv( this.addr, v );
  45405. copyArray( cache, v );
  45406. }
  45407. }
  45408. // Single matrix (from flat array or THREE.MatrixN)
  45409. function setValueM2( gl, v ) {
  45410. const cache = this.cache;
  45411. const elements = v.elements;
  45412. if ( elements === undefined ) {
  45413. if ( arraysEqual( cache, v ) ) return;
  45414. gl.uniformMatrix2fv( this.addr, false, v );
  45415. copyArray( cache, v );
  45416. } else {
  45417. if ( arraysEqual( cache, elements ) ) return;
  45418. mat2array.set( elements );
  45419. gl.uniformMatrix2fv( this.addr, false, mat2array );
  45420. copyArray( cache, elements );
  45421. }
  45422. }
  45423. function setValueM3( gl, v ) {
  45424. const cache = this.cache;
  45425. const elements = v.elements;
  45426. if ( elements === undefined ) {
  45427. if ( arraysEqual( cache, v ) ) return;
  45428. gl.uniformMatrix3fv( this.addr, false, v );
  45429. copyArray( cache, v );
  45430. } else {
  45431. if ( arraysEqual( cache, elements ) ) return;
  45432. mat3array.set( elements );
  45433. gl.uniformMatrix3fv( this.addr, false, mat3array );
  45434. copyArray( cache, elements );
  45435. }
  45436. }
  45437. function setValueM4( gl, v ) {
  45438. const cache = this.cache;
  45439. const elements = v.elements;
  45440. if ( elements === undefined ) {
  45441. if ( arraysEqual( cache, v ) ) return;
  45442. gl.uniformMatrix4fv( this.addr, false, v );
  45443. copyArray( cache, v );
  45444. } else {
  45445. if ( arraysEqual( cache, elements ) ) return;
  45446. mat4array.set( elements );
  45447. gl.uniformMatrix4fv( this.addr, false, mat4array );
  45448. copyArray( cache, elements );
  45449. }
  45450. }
  45451. // Single integer / boolean
  45452. function setValueV1i( gl, v ) {
  45453. const cache = this.cache;
  45454. if ( cache[ 0 ] === v ) return;
  45455. gl.uniform1i( this.addr, v );
  45456. cache[ 0 ] = v;
  45457. }
  45458. // Single integer / boolean vector (from flat array or THREE.VectorN)
  45459. function setValueV2i( gl, v ) {
  45460. const cache = this.cache;
  45461. if ( v.x !== undefined ) {
  45462. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  45463. gl.uniform2i( this.addr, v.x, v.y );
  45464. cache[ 0 ] = v.x;
  45465. cache[ 1 ] = v.y;
  45466. }
  45467. } else {
  45468. if ( arraysEqual( cache, v ) ) return;
  45469. gl.uniform2iv( this.addr, v );
  45470. copyArray( cache, v );
  45471. }
  45472. }
  45473. function setValueV3i( gl, v ) {
  45474. const cache = this.cache;
  45475. if ( v.x !== undefined ) {
  45476. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  45477. gl.uniform3i( this.addr, v.x, v.y, v.z );
  45478. cache[ 0 ] = v.x;
  45479. cache[ 1 ] = v.y;
  45480. cache[ 2 ] = v.z;
  45481. }
  45482. } else {
  45483. if ( arraysEqual( cache, v ) ) return;
  45484. gl.uniform3iv( this.addr, v );
  45485. copyArray( cache, v );
  45486. }
  45487. }
  45488. function setValueV4i( gl, v ) {
  45489. const cache = this.cache;
  45490. if ( v.x !== undefined ) {
  45491. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  45492. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  45493. cache[ 0 ] = v.x;
  45494. cache[ 1 ] = v.y;
  45495. cache[ 2 ] = v.z;
  45496. cache[ 3 ] = v.w;
  45497. }
  45498. } else {
  45499. if ( arraysEqual( cache, v ) ) return;
  45500. gl.uniform4iv( this.addr, v );
  45501. copyArray( cache, v );
  45502. }
  45503. }
  45504. // Single unsigned integer
  45505. function setValueV1ui( gl, v ) {
  45506. const cache = this.cache;
  45507. if ( cache[ 0 ] === v ) return;
  45508. gl.uniform1ui( this.addr, v );
  45509. cache[ 0 ] = v;
  45510. }
  45511. // Single unsigned integer vector (from flat array or THREE.VectorN)
  45512. function setValueV2ui( gl, v ) {
  45513. const cache = this.cache;
  45514. if ( v.x !== undefined ) {
  45515. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  45516. gl.uniform2ui( this.addr, v.x, v.y );
  45517. cache[ 0 ] = v.x;
  45518. cache[ 1 ] = v.y;
  45519. }
  45520. } else {
  45521. if ( arraysEqual( cache, v ) ) return;
  45522. gl.uniform2uiv( this.addr, v );
  45523. copyArray( cache, v );
  45524. }
  45525. }
  45526. function setValueV3ui( gl, v ) {
  45527. const cache = this.cache;
  45528. if ( v.x !== undefined ) {
  45529. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  45530. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  45531. cache[ 0 ] = v.x;
  45532. cache[ 1 ] = v.y;
  45533. cache[ 2 ] = v.z;
  45534. }
  45535. } else {
  45536. if ( arraysEqual( cache, v ) ) return;
  45537. gl.uniform3uiv( this.addr, v );
  45538. copyArray( cache, v );
  45539. }
  45540. }
  45541. function setValueV4ui( gl, v ) {
  45542. const cache = this.cache;
  45543. if ( v.x !== undefined ) {
  45544. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  45545. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  45546. cache[ 0 ] = v.x;
  45547. cache[ 1 ] = v.y;
  45548. cache[ 2 ] = v.z;
  45549. cache[ 3 ] = v.w;
  45550. }
  45551. } else {
  45552. if ( arraysEqual( cache, v ) ) return;
  45553. gl.uniform4uiv( this.addr, v );
  45554. copyArray( cache, v );
  45555. }
  45556. }
  45557. // Single texture (2D / Cube)
  45558. function setValueT1( gl, v, textures ) {
  45559. const cache = this.cache;
  45560. const unit = textures.allocateTextureUnit();
  45561. if ( cache[ 0 ] !== unit ) {
  45562. gl.uniform1i( this.addr, unit );
  45563. cache[ 0 ] = unit;
  45564. }
  45565. let emptyTexture2D;
  45566. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  45567. emptyShadowTexture.compareFunction = LessEqualCompare; // #28670
  45568. emptyTexture2D = emptyShadowTexture;
  45569. } else {
  45570. emptyTexture2D = emptyTexture;
  45571. }
  45572. textures.setTexture2D( v || emptyTexture2D, unit );
  45573. }
  45574. function setValueT3D1( gl, v, textures ) {
  45575. const cache = this.cache;
  45576. const unit = textures.allocateTextureUnit();
  45577. if ( cache[ 0 ] !== unit ) {
  45578. gl.uniform1i( this.addr, unit );
  45579. cache[ 0 ] = unit;
  45580. }
  45581. textures.setTexture3D( v || empty3dTexture, unit );
  45582. }
  45583. function setValueT6( gl, v, textures ) {
  45584. const cache = this.cache;
  45585. const unit = textures.allocateTextureUnit();
  45586. if ( cache[ 0 ] !== unit ) {
  45587. gl.uniform1i( this.addr, unit );
  45588. cache[ 0 ] = unit;
  45589. }
  45590. textures.setTextureCube( v || emptyCubeTexture, unit );
  45591. }
  45592. function setValueT2DArray1( gl, v, textures ) {
  45593. const cache = this.cache;
  45594. const unit = textures.allocateTextureUnit();
  45595. if ( cache[ 0 ] !== unit ) {
  45596. gl.uniform1i( this.addr, unit );
  45597. cache[ 0 ] = unit;
  45598. }
  45599. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  45600. }
  45601. // Helper to pick the right setter for the singular case
  45602. function getSingularSetter( type ) {
  45603. switch ( type ) {
  45604. case 0x1406: return setValueV1f; // FLOAT
  45605. case 0x8b50: return setValueV2f; // _VEC2
  45606. case 0x8b51: return setValueV3f; // _VEC3
  45607. case 0x8b52: return setValueV4f; // _VEC4
  45608. case 0x8b5a: return setValueM2; // _MAT2
  45609. case 0x8b5b: return setValueM3; // _MAT3
  45610. case 0x8b5c: return setValueM4; // _MAT4
  45611. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  45612. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  45613. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  45614. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  45615. case 0x1405: return setValueV1ui; // UINT
  45616. case 0x8dc6: return setValueV2ui; // _VEC2
  45617. case 0x8dc7: return setValueV3ui; // _VEC3
  45618. case 0x8dc8: return setValueV4ui; // _VEC4
  45619. case 0x8b5e: // SAMPLER_2D
  45620. case 0x8d66: // SAMPLER_EXTERNAL_OES
  45621. case 0x8dca: // INT_SAMPLER_2D
  45622. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  45623. case 0x8b62: // SAMPLER_2D_SHADOW
  45624. return setValueT1;
  45625. case 0x8b5f: // SAMPLER_3D
  45626. case 0x8dcb: // INT_SAMPLER_3D
  45627. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  45628. return setValueT3D1;
  45629. case 0x8b60: // SAMPLER_CUBE
  45630. case 0x8dcc: // INT_SAMPLER_CUBE
  45631. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  45632. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  45633. return setValueT6;
  45634. case 0x8dc1: // SAMPLER_2D_ARRAY
  45635. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  45636. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  45637. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  45638. return setValueT2DArray1;
  45639. }
  45640. }
  45641. // Array of scalars
  45642. function setValueV1fArray( gl, v ) {
  45643. gl.uniform1fv( this.addr, v );
  45644. }
  45645. // Array of vectors (from flat array or array of THREE.VectorN)
  45646. function setValueV2fArray( gl, v ) {
  45647. const data = flatten( v, this.size, 2 );
  45648. gl.uniform2fv( this.addr, data );
  45649. }
  45650. function setValueV3fArray( gl, v ) {
  45651. const data = flatten( v, this.size, 3 );
  45652. gl.uniform3fv( this.addr, data );
  45653. }
  45654. function setValueV4fArray( gl, v ) {
  45655. const data = flatten( v, this.size, 4 );
  45656. gl.uniform4fv( this.addr, data );
  45657. }
  45658. // Array of matrices (from flat array or array of THREE.MatrixN)
  45659. function setValueM2Array( gl, v ) {
  45660. const data = flatten( v, this.size, 4 );
  45661. gl.uniformMatrix2fv( this.addr, false, data );
  45662. }
  45663. function setValueM3Array( gl, v ) {
  45664. const data = flatten( v, this.size, 9 );
  45665. gl.uniformMatrix3fv( this.addr, false, data );
  45666. }
  45667. function setValueM4Array( gl, v ) {
  45668. const data = flatten( v, this.size, 16 );
  45669. gl.uniformMatrix4fv( this.addr, false, data );
  45670. }
  45671. // Array of integer / boolean
  45672. function setValueV1iArray( gl, v ) {
  45673. gl.uniform1iv( this.addr, v );
  45674. }
  45675. // Array of integer / boolean vectors (from flat array)
  45676. function setValueV2iArray( gl, v ) {
  45677. gl.uniform2iv( this.addr, v );
  45678. }
  45679. function setValueV3iArray( gl, v ) {
  45680. gl.uniform3iv( this.addr, v );
  45681. }
  45682. function setValueV4iArray( gl, v ) {
  45683. gl.uniform4iv( this.addr, v );
  45684. }
  45685. // Array of unsigned integer
  45686. function setValueV1uiArray( gl, v ) {
  45687. gl.uniform1uiv( this.addr, v );
  45688. }
  45689. // Array of unsigned integer vectors (from flat array)
  45690. function setValueV2uiArray( gl, v ) {
  45691. gl.uniform2uiv( this.addr, v );
  45692. }
  45693. function setValueV3uiArray( gl, v ) {
  45694. gl.uniform3uiv( this.addr, v );
  45695. }
  45696. function setValueV4uiArray( gl, v ) {
  45697. gl.uniform4uiv( this.addr, v );
  45698. }
  45699. // Array of textures (2D / 3D / Cube / 2DArray)
  45700. function setValueT1Array( gl, v, textures ) {
  45701. const cache = this.cache;
  45702. const n = v.length;
  45703. const units = allocTexUnits( textures, n );
  45704. if ( ! arraysEqual( cache, units ) ) {
  45705. gl.uniform1iv( this.addr, units );
  45706. copyArray( cache, units );
  45707. }
  45708. for ( let i = 0; i !== n; ++ i ) {
  45709. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  45710. }
  45711. }
  45712. function setValueT3DArray( gl, v, textures ) {
  45713. const cache = this.cache;
  45714. const n = v.length;
  45715. const units = allocTexUnits( textures, n );
  45716. if ( ! arraysEqual( cache, units ) ) {
  45717. gl.uniform1iv( this.addr, units );
  45718. copyArray( cache, units );
  45719. }
  45720. for ( let i = 0; i !== n; ++ i ) {
  45721. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  45722. }
  45723. }
  45724. function setValueT6Array( gl, v, textures ) {
  45725. const cache = this.cache;
  45726. const n = v.length;
  45727. const units = allocTexUnits( textures, n );
  45728. if ( ! arraysEqual( cache, units ) ) {
  45729. gl.uniform1iv( this.addr, units );
  45730. copyArray( cache, units );
  45731. }
  45732. for ( let i = 0; i !== n; ++ i ) {
  45733. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  45734. }
  45735. }
  45736. function setValueT2DArrayArray( gl, v, textures ) {
  45737. const cache = this.cache;
  45738. const n = v.length;
  45739. const units = allocTexUnits( textures, n );
  45740. if ( ! arraysEqual( cache, units ) ) {
  45741. gl.uniform1iv( this.addr, units );
  45742. copyArray( cache, units );
  45743. }
  45744. for ( let i = 0; i !== n; ++ i ) {
  45745. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  45746. }
  45747. }
  45748. // Helper to pick the right setter for a pure (bottom-level) array
  45749. function getPureArraySetter( type ) {
  45750. switch ( type ) {
  45751. case 0x1406: return setValueV1fArray; // FLOAT
  45752. case 0x8b50: return setValueV2fArray; // _VEC2
  45753. case 0x8b51: return setValueV3fArray; // _VEC3
  45754. case 0x8b52: return setValueV4fArray; // _VEC4
  45755. case 0x8b5a: return setValueM2Array; // _MAT2
  45756. case 0x8b5b: return setValueM3Array; // _MAT3
  45757. case 0x8b5c: return setValueM4Array; // _MAT4
  45758. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  45759. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  45760. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  45761. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  45762. case 0x1405: return setValueV1uiArray; // UINT
  45763. case 0x8dc6: return setValueV2uiArray; // _VEC2
  45764. case 0x8dc7: return setValueV3uiArray; // _VEC3
  45765. case 0x8dc8: return setValueV4uiArray; // _VEC4
  45766. case 0x8b5e: // SAMPLER_2D
  45767. case 0x8d66: // SAMPLER_EXTERNAL_OES
  45768. case 0x8dca: // INT_SAMPLER_2D
  45769. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  45770. case 0x8b62: // SAMPLER_2D_SHADOW
  45771. return setValueT1Array;
  45772. case 0x8b5f: // SAMPLER_3D
  45773. case 0x8dcb: // INT_SAMPLER_3D
  45774. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  45775. return setValueT3DArray;
  45776. case 0x8b60: // SAMPLER_CUBE
  45777. case 0x8dcc: // INT_SAMPLER_CUBE
  45778. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  45779. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  45780. return setValueT6Array;
  45781. case 0x8dc1: // SAMPLER_2D_ARRAY
  45782. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  45783. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  45784. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  45785. return setValueT2DArrayArray;
  45786. }
  45787. }
  45788. // --- Uniform Classes ---
  45789. class SingleUniform {
  45790. constructor( id, activeInfo, addr ) {
  45791. this.id = id;
  45792. this.addr = addr;
  45793. this.cache = [];
  45794. this.type = activeInfo.type;
  45795. this.setValue = getSingularSetter( activeInfo.type );
  45796. // this.path = activeInfo.name; // DEBUG
  45797. }
  45798. }
  45799. class PureArrayUniform {
  45800. constructor( id, activeInfo, addr ) {
  45801. this.id = id;
  45802. this.addr = addr;
  45803. this.cache = [];
  45804. this.type = activeInfo.type;
  45805. this.size = activeInfo.size;
  45806. this.setValue = getPureArraySetter( activeInfo.type );
  45807. // this.path = activeInfo.name; // DEBUG
  45808. }
  45809. }
  45810. class StructuredUniform {
  45811. constructor( id ) {
  45812. this.id = id;
  45813. this.seq = [];
  45814. this.map = {};
  45815. }
  45816. setValue( gl, value, textures ) {
  45817. const seq = this.seq;
  45818. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  45819. const u = seq[ i ];
  45820. u.setValue( gl, value[ u.id ], textures );
  45821. }
  45822. }
  45823. }
  45824. // --- Top-level ---
  45825. // Parser - builds up the property tree from the path strings
  45826. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  45827. // extracts
  45828. // - the identifier (member name or array index)
  45829. // - followed by an optional right bracket (found when array index)
  45830. // - followed by an optional left bracket or dot (type of subscript)
  45831. //
  45832. // Note: These portions can be read in a non-overlapping fashion and
  45833. // allow straightforward parsing of the hierarchy that WebGL encodes
  45834. // in the uniform names.
  45835. function addUniform( container, uniformObject ) {
  45836. container.seq.push( uniformObject );
  45837. container.map[ uniformObject.id ] = uniformObject;
  45838. }
  45839. function parseUniform( activeInfo, addr, container ) {
  45840. const path = activeInfo.name,
  45841. pathLength = path.length;
  45842. // reset RegExp object, because of the early exit of a previous run
  45843. RePathPart.lastIndex = 0;
  45844. while ( true ) {
  45845. const match = RePathPart.exec( path ),
  45846. matchEnd = RePathPart.lastIndex;
  45847. let id = match[ 1 ];
  45848. const idIsIndex = match[ 2 ] === ']',
  45849. subscript = match[ 3 ];
  45850. if ( idIsIndex ) id = id | 0; // convert to integer
  45851. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  45852. // bare name or "pure" bottom-level array "[0]" suffix
  45853. addUniform( container, subscript === undefined ?
  45854. new SingleUniform( id, activeInfo, addr ) :
  45855. new PureArrayUniform( id, activeInfo, addr ) );
  45856. break;
  45857. } else {
  45858. // step into inner node / create it in case it doesn't exist
  45859. const map = container.map;
  45860. let next = map[ id ];
  45861. if ( next === undefined ) {
  45862. next = new StructuredUniform( id );
  45863. addUniform( container, next );
  45864. }
  45865. container = next;
  45866. }
  45867. }
  45868. }
  45869. // Root Container
  45870. class WebGLUniforms {
  45871. constructor( gl, program ) {
  45872. this.seq = [];
  45873. this.map = {};
  45874. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  45875. for ( let i = 0; i < n; ++ i ) {
  45876. const info = gl.getActiveUniform( program, i ),
  45877. addr = gl.getUniformLocation( program, info.name );
  45878. parseUniform( info, addr, this );
  45879. }
  45880. }
  45881. setValue( gl, name, value, textures ) {
  45882. const u = this.map[ name ];
  45883. if ( u !== undefined ) u.setValue( gl, value, textures );
  45884. }
  45885. setOptional( gl, object, name ) {
  45886. const v = object[ name ];
  45887. if ( v !== undefined ) this.setValue( gl, name, v );
  45888. }
  45889. static upload( gl, seq, values, textures ) {
  45890. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  45891. const u = seq[ i ],
  45892. v = values[ u.id ];
  45893. if ( v.needsUpdate !== false ) {
  45894. // note: always updating when .needsUpdate is undefined
  45895. u.setValue( gl, v.value, textures );
  45896. }
  45897. }
  45898. }
  45899. static seqWithValue( seq, values ) {
  45900. const r = [];
  45901. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  45902. const u = seq[ i ];
  45903. if ( u.id in values ) r.push( u );
  45904. }
  45905. return r;
  45906. }
  45907. }
  45908. function WebGLShader( gl, type, string ) {
  45909. const shader = gl.createShader( type );
  45910. gl.shaderSource( shader, string );
  45911. gl.compileShader( shader );
  45912. return shader;
  45913. }
  45914. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  45915. const COMPLETION_STATUS_KHR = 0x91B1;
  45916. let programIdCount = 0;
  45917. function handleSource( string, errorLine ) {
  45918. const lines = string.split( '\n' );
  45919. const lines2 = [];
  45920. const from = Math.max( errorLine - 6, 0 );
  45921. const to = Math.min( errorLine + 6, lines.length );
  45922. for ( let i = from; i < to; i ++ ) {
  45923. const line = i + 1;
  45924. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  45925. }
  45926. return lines2.join( '\n' );
  45927. }
  45928. const _m0 = /*@__PURE__*/ new Matrix3();
  45929. function getEncodingComponents( colorSpace ) {
  45930. ColorManagement._getMatrix( _m0, ColorManagement.workingColorSpace, colorSpace );
  45931. const encodingMatrix = `mat3( ${ _m0.elements.map( ( v ) => v.toFixed( 4 ) ) } )`;
  45932. switch ( ColorManagement.getTransfer( colorSpace ) ) {
  45933. case LinearTransfer:
  45934. return [ encodingMatrix, 'LinearTransferOETF' ];
  45935. case SRGBTransfer:
  45936. return [ encodingMatrix, 'sRGBTransferOETF' ];
  45937. default:
  45938. console.warn( 'THREE.WebGLProgram: Unsupported color space: ', colorSpace );
  45939. return [ encodingMatrix, 'LinearTransferOETF' ];
  45940. }
  45941. }
  45942. function getShaderErrors( gl, shader, type ) {
  45943. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  45944. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  45945. const errors = shaderInfoLog.trim();
  45946. if ( status && errors === '' ) return '';
  45947. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  45948. if ( errorMatches ) {
  45949. // --enable-privileged-webgl-extension
  45950. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  45951. const errorLine = parseInt( errorMatches[ 1 ] );
  45952. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  45953. } else {
  45954. return errors;
  45955. }
  45956. }
  45957. function getTexelEncodingFunction( functionName, colorSpace ) {
  45958. const components = getEncodingComponents( colorSpace );
  45959. return [
  45960. `vec4 ${functionName}( vec4 value ) {`,
  45961. ` return ${components[ 1 ]}( vec4( value.rgb * ${components[ 0 ]}, value.a ) );`,
  45962. '}',
  45963. ].join( '\n' );
  45964. }
  45965. function getToneMappingFunction( functionName, toneMapping ) {
  45966. let toneMappingName;
  45967. switch ( toneMapping ) {
  45968. case LinearToneMapping:
  45969. toneMappingName = 'Linear';
  45970. break;
  45971. case ReinhardToneMapping:
  45972. toneMappingName = 'Reinhard';
  45973. break;
  45974. case CineonToneMapping:
  45975. toneMappingName = 'Cineon';
  45976. break;
  45977. case ACESFilmicToneMapping:
  45978. toneMappingName = 'ACESFilmic';
  45979. break;
  45980. case AgXToneMapping:
  45981. toneMappingName = 'AgX';
  45982. break;
  45983. case NeutralToneMapping:
  45984. toneMappingName = 'Neutral';
  45985. break;
  45986. case CustomToneMapping:
  45987. toneMappingName = 'Custom';
  45988. break;
  45989. default:
  45990. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  45991. toneMappingName = 'Linear';
  45992. }
  45993. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  45994. }
  45995. const _v0 = /*@__PURE__*/ new Vector3();
  45996. function getLuminanceFunction() {
  45997. ColorManagement.getLuminanceCoefficients( _v0 );
  45998. const r = _v0.x.toFixed( 4 );
  45999. const g = _v0.y.toFixed( 4 );
  46000. const b = _v0.z.toFixed( 4 );
  46001. return [
  46002. 'float luminance( const in vec3 rgb ) {',
  46003. ` const vec3 weights = vec3( ${ r }, ${ g }, ${ b } );`,
  46004. ' return dot( weights, rgb );',
  46005. '}'
  46006. ].join( '\n' );
  46007. }
  46008. function generateVertexExtensions( parameters ) {
  46009. const chunks = [
  46010. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '',
  46011. parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '',
  46012. ];
  46013. return chunks.filter( filterEmptyLine ).join( '\n' );
  46014. }
  46015. function generateDefines( defines ) {
  46016. const chunks = [];
  46017. for ( const name in defines ) {
  46018. const value = defines[ name ];
  46019. if ( value === false ) continue;
  46020. chunks.push( '#define ' + name + ' ' + value );
  46021. }
  46022. return chunks.join( '\n' );
  46023. }
  46024. function fetchAttributeLocations( gl, program ) {
  46025. const attributes = {};
  46026. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  46027. for ( let i = 0; i < n; i ++ ) {
  46028. const info = gl.getActiveAttrib( program, i );
  46029. const name = info.name;
  46030. let locationSize = 1;
  46031. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  46032. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  46033. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  46034. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  46035. attributes[ name ] = {
  46036. type: info.type,
  46037. location: gl.getAttribLocation( program, name ),
  46038. locationSize: locationSize
  46039. };
  46040. }
  46041. return attributes;
  46042. }
  46043. function filterEmptyLine( string ) {
  46044. return string !== '';
  46045. }
  46046. function replaceLightNums( string, parameters ) {
  46047. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  46048. return string
  46049. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  46050. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  46051. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  46052. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  46053. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  46054. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  46055. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  46056. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  46057. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  46058. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  46059. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  46060. }
  46061. function replaceClippingPlaneNums( string, parameters ) {
  46062. return string
  46063. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  46064. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  46065. }
  46066. // Resolve Includes
  46067. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  46068. function resolveIncludes( string ) {
  46069. return string.replace( includePattern, includeReplacer );
  46070. }
  46071. const shaderChunkMap = new Map();
  46072. function includeReplacer( match, include ) {
  46073. let string = ShaderChunk[ include ];
  46074. if ( string === undefined ) {
  46075. const newInclude = shaderChunkMap.get( include );
  46076. if ( newInclude !== undefined ) {
  46077. string = ShaderChunk[ newInclude ];
  46078. console.warn( 'THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  46079. } else {
  46080. throw new Error( 'Can not resolve #include <' + include + '>' );
  46081. }
  46082. }
  46083. return resolveIncludes( string );
  46084. }
  46085. // Unroll Loops
  46086. 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;
  46087. function unrollLoops( string ) {
  46088. return string.replace( unrollLoopPattern, loopReplacer );
  46089. }
  46090. function loopReplacer( match, start, end, snippet ) {
  46091. let string = '';
  46092. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  46093. string += snippet
  46094. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  46095. .replace( /UNROLLED_LOOP_INDEX/g, i );
  46096. }
  46097. return string;
  46098. }
  46099. //
  46100. function generatePrecision( parameters ) {
  46101. let precisionstring = `precision ${parameters.precision} float;
  46102. precision ${parameters.precision} int;
  46103. precision ${parameters.precision} sampler2D;
  46104. precision ${parameters.precision} samplerCube;
  46105. precision ${parameters.precision} sampler3D;
  46106. precision ${parameters.precision} sampler2DArray;
  46107. precision ${parameters.precision} sampler2DShadow;
  46108. precision ${parameters.precision} samplerCubeShadow;
  46109. precision ${parameters.precision} sampler2DArrayShadow;
  46110. precision ${parameters.precision} isampler2D;
  46111. precision ${parameters.precision} isampler3D;
  46112. precision ${parameters.precision} isamplerCube;
  46113. precision ${parameters.precision} isampler2DArray;
  46114. precision ${parameters.precision} usampler2D;
  46115. precision ${parameters.precision} usampler3D;
  46116. precision ${parameters.precision} usamplerCube;
  46117. precision ${parameters.precision} usampler2DArray;
  46118. `;
  46119. if ( parameters.precision === 'highp' ) {
  46120. precisionstring += '\n#define HIGH_PRECISION';
  46121. } else if ( parameters.precision === 'mediump' ) {
  46122. precisionstring += '\n#define MEDIUM_PRECISION';
  46123. } else if ( parameters.precision === 'lowp' ) {
  46124. precisionstring += '\n#define LOW_PRECISION';
  46125. }
  46126. return precisionstring;
  46127. }
  46128. function generateShadowMapTypeDefine( parameters ) {
  46129. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  46130. if ( parameters.shadowMapType === PCFShadowMap ) {
  46131. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  46132. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  46133. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  46134. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  46135. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  46136. }
  46137. return shadowMapTypeDefine;
  46138. }
  46139. function generateEnvMapTypeDefine( parameters ) {
  46140. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  46141. if ( parameters.envMap ) {
  46142. switch ( parameters.envMapMode ) {
  46143. case CubeReflectionMapping:
  46144. case CubeRefractionMapping:
  46145. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  46146. break;
  46147. case CubeUVReflectionMapping:
  46148. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  46149. break;
  46150. }
  46151. }
  46152. return envMapTypeDefine;
  46153. }
  46154. function generateEnvMapModeDefine( parameters ) {
  46155. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  46156. if ( parameters.envMap ) {
  46157. switch ( parameters.envMapMode ) {
  46158. case CubeRefractionMapping:
  46159. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  46160. break;
  46161. }
  46162. }
  46163. return envMapModeDefine;
  46164. }
  46165. function generateEnvMapBlendingDefine( parameters ) {
  46166. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  46167. if ( parameters.envMap ) {
  46168. switch ( parameters.combine ) {
  46169. case MultiplyOperation:
  46170. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  46171. break;
  46172. case MixOperation:
  46173. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  46174. break;
  46175. case AddOperation:
  46176. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  46177. break;
  46178. }
  46179. }
  46180. return envMapBlendingDefine;
  46181. }
  46182. function generateCubeUVSize( parameters ) {
  46183. const imageHeight = parameters.envMapCubeUVHeight;
  46184. if ( imageHeight === null ) return null;
  46185. const maxMip = Math.log2( imageHeight ) - 2;
  46186. const texelHeight = 1.0 / imageHeight;
  46187. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  46188. return { texelWidth, texelHeight, maxMip };
  46189. }
  46190. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  46191. // TODO Send this event to Three.js DevTools
  46192. // console.log( 'WebGLProgram', cacheKey );
  46193. const gl = renderer.getContext();
  46194. const defines = parameters.defines;
  46195. let vertexShader = parameters.vertexShader;
  46196. let fragmentShader = parameters.fragmentShader;
  46197. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  46198. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  46199. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  46200. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  46201. const envMapCubeUVSize = generateCubeUVSize( parameters );
  46202. const customVertexExtensions = generateVertexExtensions( parameters );
  46203. const customDefines = generateDefines( defines );
  46204. const program = gl.createProgram();
  46205. let prefixVertex, prefixFragment;
  46206. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  46207. if ( parameters.isRawShaderMaterial ) {
  46208. prefixVertex = [
  46209. '#define SHADER_TYPE ' + parameters.shaderType,
  46210. '#define SHADER_NAME ' + parameters.shaderName,
  46211. customDefines
  46212. ].filter( filterEmptyLine ).join( '\n' );
  46213. if ( prefixVertex.length > 0 ) {
  46214. prefixVertex += '\n';
  46215. }
  46216. prefixFragment = [
  46217. '#define SHADER_TYPE ' + parameters.shaderType,
  46218. '#define SHADER_NAME ' + parameters.shaderName,
  46219. customDefines
  46220. ].filter( filterEmptyLine ).join( '\n' );
  46221. if ( prefixFragment.length > 0 ) {
  46222. prefixFragment += '\n';
  46223. }
  46224. } else {
  46225. prefixVertex = [
  46226. generatePrecision( parameters ),
  46227. '#define SHADER_TYPE ' + parameters.shaderType,
  46228. '#define SHADER_NAME ' + parameters.shaderName,
  46229. customDefines,
  46230. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  46231. parameters.batching ? '#define USE_BATCHING' : '',
  46232. parameters.batchingColor ? '#define USE_BATCHING_COLOR' : '',
  46233. parameters.instancing ? '#define USE_INSTANCING' : '',
  46234. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  46235. parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '',
  46236. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  46237. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  46238. parameters.map ? '#define USE_MAP' : '',
  46239. parameters.envMap ? '#define USE_ENVMAP' : '',
  46240. parameters.envMap ? '#define ' + envMapModeDefine : '',
  46241. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  46242. parameters.aoMap ? '#define USE_AOMAP' : '',
  46243. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  46244. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  46245. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  46246. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  46247. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  46248. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  46249. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  46250. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  46251. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  46252. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  46253. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  46254. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  46255. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  46256. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  46257. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  46258. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  46259. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  46260. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  46261. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  46262. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  46263. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  46264. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  46265. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  46266. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  46267. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  46268. //
  46269. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  46270. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  46271. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  46272. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  46273. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  46274. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  46275. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  46276. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  46277. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  46278. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  46279. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  46280. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  46281. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  46282. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  46283. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  46284. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  46285. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  46286. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  46287. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  46288. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  46289. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  46290. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  46291. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  46292. //
  46293. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  46294. parameters.vertexColors ? '#define USE_COLOR' : '',
  46295. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  46296. parameters.vertexUv1s ? '#define USE_UV1' : '',
  46297. parameters.vertexUv2s ? '#define USE_UV2' : '',
  46298. parameters.vertexUv3s ? '#define USE_UV3' : '',
  46299. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  46300. parameters.flatShading ? '#define FLAT_SHADED' : '',
  46301. parameters.skinning ? '#define USE_SKINNING' : '',
  46302. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  46303. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  46304. ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '',
  46305. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  46306. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  46307. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  46308. parameters.flipSided ? '#define FLIP_SIDED' : '',
  46309. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  46310. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  46311. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  46312. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  46313. parameters.logarithmicDepthBuffer ? '#define USE_LOGARITHMIC_DEPTH_BUFFER' : '',
  46314. parameters.reversedDepthBuffer ? '#define USE_REVERSED_DEPTH_BUFFER' : '',
  46315. 'uniform mat4 modelMatrix;',
  46316. 'uniform mat4 modelViewMatrix;',
  46317. 'uniform mat4 projectionMatrix;',
  46318. 'uniform mat4 viewMatrix;',
  46319. 'uniform mat3 normalMatrix;',
  46320. 'uniform vec3 cameraPosition;',
  46321. 'uniform bool isOrthographic;',
  46322. '#ifdef USE_INSTANCING',
  46323. ' attribute mat4 instanceMatrix;',
  46324. '#endif',
  46325. '#ifdef USE_INSTANCING_COLOR',
  46326. ' attribute vec3 instanceColor;',
  46327. '#endif',
  46328. '#ifdef USE_INSTANCING_MORPH',
  46329. ' uniform sampler2D morphTexture;',
  46330. '#endif',
  46331. 'attribute vec3 position;',
  46332. 'attribute vec3 normal;',
  46333. 'attribute vec2 uv;',
  46334. '#ifdef USE_UV1',
  46335. ' attribute vec2 uv1;',
  46336. '#endif',
  46337. '#ifdef USE_UV2',
  46338. ' attribute vec2 uv2;',
  46339. '#endif',
  46340. '#ifdef USE_UV3',
  46341. ' attribute vec2 uv3;',
  46342. '#endif',
  46343. '#ifdef USE_TANGENT',
  46344. ' attribute vec4 tangent;',
  46345. '#endif',
  46346. '#if defined( USE_COLOR_ALPHA )',
  46347. ' attribute vec4 color;',
  46348. '#elif defined( USE_COLOR )',
  46349. ' attribute vec3 color;',
  46350. '#endif',
  46351. '#ifdef USE_SKINNING',
  46352. ' attribute vec4 skinIndex;',
  46353. ' attribute vec4 skinWeight;',
  46354. '#endif',
  46355. '\n'
  46356. ].filter( filterEmptyLine ).join( '\n' );
  46357. prefixFragment = [
  46358. generatePrecision( parameters ),
  46359. '#define SHADER_TYPE ' + parameters.shaderType,
  46360. '#define SHADER_NAME ' + parameters.shaderName,
  46361. customDefines,
  46362. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  46363. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  46364. parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '',
  46365. parameters.map ? '#define USE_MAP' : '',
  46366. parameters.matcap ? '#define USE_MATCAP' : '',
  46367. parameters.envMap ? '#define USE_ENVMAP' : '',
  46368. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  46369. parameters.envMap ? '#define ' + envMapModeDefine : '',
  46370. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  46371. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  46372. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  46373. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  46374. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  46375. parameters.aoMap ? '#define USE_AOMAP' : '',
  46376. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  46377. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  46378. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  46379. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  46380. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  46381. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  46382. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  46383. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  46384. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  46385. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  46386. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  46387. parameters.dispersion ? '#define USE_DISPERSION' : '',
  46388. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  46389. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  46390. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  46391. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  46392. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  46393. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  46394. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  46395. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  46396. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  46397. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  46398. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  46399. parameters.sheen ? '#define USE_SHEEN' : '',
  46400. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  46401. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  46402. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  46403. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  46404. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  46405. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  46406. parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? '#define USE_COLOR' : '',
  46407. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  46408. parameters.vertexUv1s ? '#define USE_UV1' : '',
  46409. parameters.vertexUv2s ? '#define USE_UV2' : '',
  46410. parameters.vertexUv3s ? '#define USE_UV3' : '',
  46411. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  46412. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  46413. parameters.flatShading ? '#define FLAT_SHADED' : '',
  46414. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  46415. parameters.flipSided ? '#define FLIP_SIDED' : '',
  46416. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  46417. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  46418. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  46419. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  46420. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  46421. parameters.decodeVideoTextureEmissive ? '#define DECODE_VIDEO_TEXTURE_EMISSIVE' : '',
  46422. parameters.logarithmicDepthBuffer ? '#define USE_LOGARITHMIC_DEPTH_BUFFER' : '',
  46423. parameters.reversedDepthBuffer ? '#define USE_REVERSED_DEPTH_BUFFER' : '',
  46424. 'uniform mat4 viewMatrix;',
  46425. 'uniform vec3 cameraPosition;',
  46426. 'uniform bool isOrthographic;',
  46427. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  46428. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  46429. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  46430. parameters.dithering ? '#define DITHERING' : '',
  46431. parameters.opaque ? '#define OPAQUE' : '',
  46432. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  46433. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  46434. getLuminanceFunction(),
  46435. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  46436. '\n'
  46437. ].filter( filterEmptyLine ).join( '\n' );
  46438. }
  46439. vertexShader = resolveIncludes( vertexShader );
  46440. vertexShader = replaceLightNums( vertexShader, parameters );
  46441. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  46442. fragmentShader = resolveIncludes( fragmentShader );
  46443. fragmentShader = replaceLightNums( fragmentShader, parameters );
  46444. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  46445. vertexShader = unrollLoops( vertexShader );
  46446. fragmentShader = unrollLoops( fragmentShader );
  46447. if ( parameters.isRawShaderMaterial !== true ) {
  46448. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  46449. versionString = '#version 300 es\n';
  46450. prefixVertex = [
  46451. customVertexExtensions,
  46452. '#define attribute in',
  46453. '#define varying out',
  46454. '#define texture2D texture'
  46455. ].join( '\n' ) + '\n' + prefixVertex;
  46456. prefixFragment = [
  46457. '#define varying in',
  46458. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  46459. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  46460. '#define gl_FragDepthEXT gl_FragDepth',
  46461. '#define texture2D texture',
  46462. '#define textureCube texture',
  46463. '#define texture2DProj textureProj',
  46464. '#define texture2DLodEXT textureLod',
  46465. '#define texture2DProjLodEXT textureProjLod',
  46466. '#define textureCubeLodEXT textureLod',
  46467. '#define texture2DGradEXT textureGrad',
  46468. '#define texture2DProjGradEXT textureProjGrad',
  46469. '#define textureCubeGradEXT textureGrad'
  46470. ].join( '\n' ) + '\n' + prefixFragment;
  46471. }
  46472. const vertexGlsl = versionString + prefixVertex + vertexShader;
  46473. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  46474. // console.log( '*VERTEX*', vertexGlsl );
  46475. // console.log( '*FRAGMENT*', fragmentGlsl );
  46476. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  46477. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  46478. gl.attachShader( program, glVertexShader );
  46479. gl.attachShader( program, glFragmentShader );
  46480. // Force a particular attribute to index 0.
  46481. if ( parameters.index0AttributeName !== undefined ) {
  46482. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  46483. } else if ( parameters.morphTargets === true ) {
  46484. // programs with morphTargets displace position out of attribute 0
  46485. gl.bindAttribLocation( program, 0, 'position' );
  46486. }
  46487. gl.linkProgram( program );
  46488. function onFirstUse( self ) {
  46489. // check for link errors
  46490. if ( renderer.debug.checkShaderErrors ) {
  46491. const programInfoLog = gl.getProgramInfoLog( program ) || '';
  46492. const vertexShaderInfoLog = gl.getShaderInfoLog( glVertexShader ) || '';
  46493. const fragmentShaderInfoLog = gl.getShaderInfoLog( glFragmentShader ) || '';
  46494. const programLog = programInfoLog.trim();
  46495. const vertexLog = vertexShaderInfoLog.trim();
  46496. const fragmentLog = fragmentShaderInfoLog.trim();
  46497. let runnable = true;
  46498. let haveDiagnostics = true;
  46499. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  46500. runnable = false;
  46501. if ( typeof renderer.debug.onShaderError === 'function' ) {
  46502. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  46503. } else {
  46504. // default error reporting
  46505. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  46506. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  46507. console.error(
  46508. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  46509. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  46510. 'Material Name: ' + self.name + '\n' +
  46511. 'Material Type: ' + self.type + '\n\n' +
  46512. 'Program Info Log: ' + programLog + '\n' +
  46513. vertexErrors + '\n' +
  46514. fragmentErrors
  46515. );
  46516. }
  46517. } else if ( programLog !== '' ) {
  46518. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  46519. } else if ( vertexLog === '' || fragmentLog === '' ) {
  46520. haveDiagnostics = false;
  46521. }
  46522. if ( haveDiagnostics ) {
  46523. self.diagnostics = {
  46524. runnable: runnable,
  46525. programLog: programLog,
  46526. vertexShader: {
  46527. log: vertexLog,
  46528. prefix: prefixVertex
  46529. },
  46530. fragmentShader: {
  46531. log: fragmentLog,
  46532. prefix: prefixFragment
  46533. }
  46534. };
  46535. }
  46536. }
  46537. // Clean up
  46538. // Crashes in iOS9 and iOS10. #18402
  46539. // gl.detachShader( program, glVertexShader );
  46540. // gl.detachShader( program, glFragmentShader );
  46541. gl.deleteShader( glVertexShader );
  46542. gl.deleteShader( glFragmentShader );
  46543. cachedUniforms = new WebGLUniforms( gl, program );
  46544. cachedAttributes = fetchAttributeLocations( gl, program );
  46545. }
  46546. // set up caching for uniform locations
  46547. let cachedUniforms;
  46548. this.getUniforms = function () {
  46549. if ( cachedUniforms === undefined ) {
  46550. // Populates cachedUniforms and cachedAttributes
  46551. onFirstUse( this );
  46552. }
  46553. return cachedUniforms;
  46554. };
  46555. // set up caching for attribute locations
  46556. let cachedAttributes;
  46557. this.getAttributes = function () {
  46558. if ( cachedAttributes === undefined ) {
  46559. // Populates cachedAttributes and cachedUniforms
  46560. onFirstUse( this );
  46561. }
  46562. return cachedAttributes;
  46563. };
  46564. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  46565. // flag the program as ready immediately. It may cause a stall when it's first used.
  46566. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  46567. this.isReady = function () {
  46568. if ( programReady === false ) {
  46569. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  46570. }
  46571. return programReady;
  46572. };
  46573. // free resource
  46574. this.destroy = function () {
  46575. bindingStates.releaseStatesOfProgram( this );
  46576. gl.deleteProgram( program );
  46577. this.program = undefined;
  46578. };
  46579. //
  46580. this.type = parameters.shaderType;
  46581. this.name = parameters.shaderName;
  46582. this.id = programIdCount ++;
  46583. this.cacheKey = cacheKey;
  46584. this.usedTimes = 1;
  46585. this.program = program;
  46586. this.vertexShader = glVertexShader;
  46587. this.fragmentShader = glFragmentShader;
  46588. return this;
  46589. }
  46590. let _id = 0;
  46591. class WebGLShaderCache {
  46592. constructor() {
  46593. this.shaderCache = new Map();
  46594. this.materialCache = new Map();
  46595. }
  46596. update( material ) {
  46597. const vertexShader = material.vertexShader;
  46598. const fragmentShader = material.fragmentShader;
  46599. const vertexShaderStage = this._getShaderStage( vertexShader );
  46600. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  46601. const materialShaders = this._getShaderCacheForMaterial( material );
  46602. if ( materialShaders.has( vertexShaderStage ) === false ) {
  46603. materialShaders.add( vertexShaderStage );
  46604. vertexShaderStage.usedTimes ++;
  46605. }
  46606. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  46607. materialShaders.add( fragmentShaderStage );
  46608. fragmentShaderStage.usedTimes ++;
  46609. }
  46610. return this;
  46611. }
  46612. remove( material ) {
  46613. const materialShaders = this.materialCache.get( material );
  46614. for ( const shaderStage of materialShaders ) {
  46615. shaderStage.usedTimes --;
  46616. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  46617. }
  46618. this.materialCache.delete( material );
  46619. return this;
  46620. }
  46621. getVertexShaderID( material ) {
  46622. return this._getShaderStage( material.vertexShader ).id;
  46623. }
  46624. getFragmentShaderID( material ) {
  46625. return this._getShaderStage( material.fragmentShader ).id;
  46626. }
  46627. dispose() {
  46628. this.shaderCache.clear();
  46629. this.materialCache.clear();
  46630. }
  46631. _getShaderCacheForMaterial( material ) {
  46632. const cache = this.materialCache;
  46633. let set = cache.get( material );
  46634. if ( set === undefined ) {
  46635. set = new Set();
  46636. cache.set( material, set );
  46637. }
  46638. return set;
  46639. }
  46640. _getShaderStage( code ) {
  46641. const cache = this.shaderCache;
  46642. let stage = cache.get( code );
  46643. if ( stage === undefined ) {
  46644. stage = new WebGLShaderStage( code );
  46645. cache.set( code, stage );
  46646. }
  46647. return stage;
  46648. }
  46649. }
  46650. class WebGLShaderStage {
  46651. constructor( code ) {
  46652. this.id = _id ++;
  46653. this.code = code;
  46654. this.usedTimes = 0;
  46655. }
  46656. }
  46657. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  46658. const _programLayers = new Layers();
  46659. const _customShaders = new WebGLShaderCache();
  46660. const _activeChannels = new Set();
  46661. const programs = [];
  46662. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  46663. const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  46664. let precision = capabilities.precision;
  46665. const shaderIDs = {
  46666. MeshDepthMaterial: 'depth',
  46667. MeshDistanceMaterial: 'distanceRGBA',
  46668. MeshNormalMaterial: 'normal',
  46669. MeshBasicMaterial: 'basic',
  46670. MeshLambertMaterial: 'lambert',
  46671. MeshPhongMaterial: 'phong',
  46672. MeshToonMaterial: 'toon',
  46673. MeshStandardMaterial: 'physical',
  46674. MeshPhysicalMaterial: 'physical',
  46675. MeshMatcapMaterial: 'matcap',
  46676. LineBasicMaterial: 'basic',
  46677. LineDashedMaterial: 'dashed',
  46678. PointsMaterial: 'points',
  46679. ShadowMaterial: 'shadow',
  46680. SpriteMaterial: 'sprite'
  46681. };
  46682. function getChannel( value ) {
  46683. _activeChannels.add( value );
  46684. if ( value === 0 ) return 'uv';
  46685. return `uv${ value }`;
  46686. }
  46687. function getParameters( material, lights, shadows, scene, object ) {
  46688. const fog = scene.fog;
  46689. const geometry = object.geometry;
  46690. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  46691. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  46692. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  46693. const shaderID = shaderIDs[ material.type ];
  46694. // heuristics to create shader parameters according to lights in the scene
  46695. // (not to blow over maxLights budget)
  46696. if ( material.precision !== null ) {
  46697. precision = capabilities.getMaxPrecision( material.precision );
  46698. if ( precision !== material.precision ) {
  46699. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  46700. }
  46701. }
  46702. //
  46703. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  46704. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  46705. let morphTextureStride = 0;
  46706. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  46707. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  46708. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  46709. //
  46710. let vertexShader, fragmentShader;
  46711. let customVertexShaderID, customFragmentShaderID;
  46712. if ( shaderID ) {
  46713. const shader = ShaderLib[ shaderID ];
  46714. vertexShader = shader.vertexShader;
  46715. fragmentShader = shader.fragmentShader;
  46716. } else {
  46717. vertexShader = material.vertexShader;
  46718. fragmentShader = material.fragmentShader;
  46719. _customShaders.update( material );
  46720. customVertexShaderID = _customShaders.getVertexShaderID( material );
  46721. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  46722. }
  46723. const currentRenderTarget = renderer.getRenderTarget();
  46724. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  46725. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  46726. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  46727. const HAS_MAP = !! material.map;
  46728. const HAS_MATCAP = !! material.matcap;
  46729. const HAS_ENVMAP = !! envMap;
  46730. const HAS_AOMAP = !! material.aoMap;
  46731. const HAS_LIGHTMAP = !! material.lightMap;
  46732. const HAS_BUMPMAP = !! material.bumpMap;
  46733. const HAS_NORMALMAP = !! material.normalMap;
  46734. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  46735. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  46736. const HAS_METALNESSMAP = !! material.metalnessMap;
  46737. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  46738. const HAS_ANISOTROPY = material.anisotropy > 0;
  46739. const HAS_CLEARCOAT = material.clearcoat > 0;
  46740. const HAS_DISPERSION = material.dispersion > 0;
  46741. const HAS_IRIDESCENCE = material.iridescence > 0;
  46742. const HAS_SHEEN = material.sheen > 0;
  46743. const HAS_TRANSMISSION = material.transmission > 0;
  46744. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  46745. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  46746. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  46747. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  46748. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  46749. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  46750. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  46751. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  46752. const HAS_SPECULARMAP = !! material.specularMap;
  46753. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  46754. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  46755. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  46756. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  46757. const HAS_GRADIENTMAP = !! material.gradientMap;
  46758. const HAS_ALPHAMAP = !! material.alphaMap;
  46759. const HAS_ALPHATEST = material.alphaTest > 0;
  46760. const HAS_ALPHAHASH = !! material.alphaHash;
  46761. const HAS_EXTENSIONS = !! material.extensions;
  46762. let toneMapping = NoToneMapping;
  46763. if ( material.toneMapped ) {
  46764. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  46765. toneMapping = renderer.toneMapping;
  46766. }
  46767. }
  46768. const parameters = {
  46769. shaderID: shaderID,
  46770. shaderType: material.type,
  46771. shaderName: material.name,
  46772. vertexShader: vertexShader,
  46773. fragmentShader: fragmentShader,
  46774. defines: material.defines,
  46775. customVertexShaderID: customVertexShaderID,
  46776. customFragmentShaderID: customFragmentShaderID,
  46777. isRawShaderMaterial: material.isRawShaderMaterial === true,
  46778. glslVersion: material.glslVersion,
  46779. precision: precision,
  46780. batching: IS_BATCHEDMESH,
  46781. batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null,
  46782. instancing: IS_INSTANCEDMESH,
  46783. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  46784. instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
  46785. supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
  46786. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  46787. alphaToCoverage: !! material.alphaToCoverage,
  46788. map: HAS_MAP,
  46789. matcap: HAS_MATCAP,
  46790. envMap: HAS_ENVMAP,
  46791. envMapMode: HAS_ENVMAP && envMap.mapping,
  46792. envMapCubeUVHeight: envMapCubeUVHeight,
  46793. aoMap: HAS_AOMAP,
  46794. lightMap: HAS_LIGHTMAP,
  46795. bumpMap: HAS_BUMPMAP,
  46796. normalMap: HAS_NORMALMAP,
  46797. displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
  46798. emissiveMap: HAS_EMISSIVEMAP,
  46799. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  46800. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  46801. metalnessMap: HAS_METALNESSMAP,
  46802. roughnessMap: HAS_ROUGHNESSMAP,
  46803. anisotropy: HAS_ANISOTROPY,
  46804. anisotropyMap: HAS_ANISOTROPYMAP,
  46805. clearcoat: HAS_CLEARCOAT,
  46806. clearcoatMap: HAS_CLEARCOATMAP,
  46807. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  46808. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  46809. dispersion: HAS_DISPERSION,
  46810. iridescence: HAS_IRIDESCENCE,
  46811. iridescenceMap: HAS_IRIDESCENCEMAP,
  46812. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  46813. sheen: HAS_SHEEN,
  46814. sheenColorMap: HAS_SHEEN_COLORMAP,
  46815. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  46816. specularMap: HAS_SPECULARMAP,
  46817. specularColorMap: HAS_SPECULAR_COLORMAP,
  46818. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  46819. transmission: HAS_TRANSMISSION,
  46820. transmissionMap: HAS_TRANSMISSIONMAP,
  46821. thicknessMap: HAS_THICKNESSMAP,
  46822. gradientMap: HAS_GRADIENTMAP,
  46823. opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
  46824. alphaMap: HAS_ALPHAMAP,
  46825. alphaTest: HAS_ALPHATEST,
  46826. alphaHash: HAS_ALPHAHASH,
  46827. combine: material.combine,
  46828. //
  46829. mapUv: HAS_MAP && getChannel( material.map.channel ),
  46830. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  46831. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  46832. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  46833. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  46834. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  46835. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  46836. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  46837. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  46838. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  46839. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  46840. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  46841. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  46842. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  46843. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  46844. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  46845. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  46846. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  46847. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  46848. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  46849. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  46850. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  46851. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  46852. //
  46853. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  46854. vertexColors: material.vertexColors,
  46855. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  46856. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  46857. fog: !! fog,
  46858. useFog: material.fog === true,
  46859. fogExp2: ( !! fog && fog.isFogExp2 ),
  46860. flatShading: ( material.flatShading === true && material.wireframe === false ),
  46861. sizeAttenuation: material.sizeAttenuation === true,
  46862. logarithmicDepthBuffer: logarithmicDepthBuffer,
  46863. reversedDepthBuffer: reversedDepthBuffer,
  46864. skinning: object.isSkinnedMesh === true,
  46865. morphTargets: geometry.morphAttributes.position !== undefined,
  46866. morphNormals: geometry.morphAttributes.normal !== undefined,
  46867. morphColors: geometry.morphAttributes.color !== undefined,
  46868. morphTargetsCount: morphTargetsCount,
  46869. morphTextureStride: morphTextureStride,
  46870. numDirLights: lights.directional.length,
  46871. numPointLights: lights.point.length,
  46872. numSpotLights: lights.spot.length,
  46873. numSpotLightMaps: lights.spotLightMap.length,
  46874. numRectAreaLights: lights.rectArea.length,
  46875. numHemiLights: lights.hemi.length,
  46876. numDirLightShadows: lights.directionalShadowMap.length,
  46877. numPointLightShadows: lights.pointShadowMap.length,
  46878. numSpotLightShadows: lights.spotShadowMap.length,
  46879. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  46880. numLightProbes: lights.numLightProbes,
  46881. numClippingPlanes: clipping.numPlanes,
  46882. numClipIntersection: clipping.numIntersection,
  46883. dithering: material.dithering,
  46884. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  46885. shadowMapType: renderer.shadowMap.type,
  46886. toneMapping: toneMapping,
  46887. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  46888. decodeVideoTextureEmissive: HAS_EMISSIVEMAP && ( material.emissiveMap.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.emissiveMap.colorSpace ) === SRGBTransfer ),
  46889. premultipliedAlpha: material.premultipliedAlpha,
  46890. doubleSided: material.side === DoubleSide,
  46891. flipSided: material.side === BackSide,
  46892. useDepthPacking: material.depthPacking >= 0,
  46893. depthPacking: material.depthPacking || 0,
  46894. index0AttributeName: material.index0AttributeName,
  46895. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ),
  46896. extensionMultiDraw: ( HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH ) && extensions.has( 'WEBGL_multi_draw' ),
  46897. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  46898. customProgramCacheKey: material.customProgramCacheKey()
  46899. };
  46900. // the usage of getChannel() determines the active texture channels for this shader
  46901. parameters.vertexUv1s = _activeChannels.has( 1 );
  46902. parameters.vertexUv2s = _activeChannels.has( 2 );
  46903. parameters.vertexUv3s = _activeChannels.has( 3 );
  46904. _activeChannels.clear();
  46905. return parameters;
  46906. }
  46907. function getProgramCacheKey( parameters ) {
  46908. const array = [];
  46909. if ( parameters.shaderID ) {
  46910. array.push( parameters.shaderID );
  46911. } else {
  46912. array.push( parameters.customVertexShaderID );
  46913. array.push( parameters.customFragmentShaderID );
  46914. }
  46915. if ( parameters.defines !== undefined ) {
  46916. for ( const name in parameters.defines ) {
  46917. array.push( name );
  46918. array.push( parameters.defines[ name ] );
  46919. }
  46920. }
  46921. if ( parameters.isRawShaderMaterial === false ) {
  46922. getProgramCacheKeyParameters( array, parameters );
  46923. getProgramCacheKeyBooleans( array, parameters );
  46924. array.push( renderer.outputColorSpace );
  46925. }
  46926. array.push( parameters.customProgramCacheKey );
  46927. return array.join();
  46928. }
  46929. function getProgramCacheKeyParameters( array, parameters ) {
  46930. array.push( parameters.precision );
  46931. array.push( parameters.outputColorSpace );
  46932. array.push( parameters.envMapMode );
  46933. array.push( parameters.envMapCubeUVHeight );
  46934. array.push( parameters.mapUv );
  46935. array.push( parameters.alphaMapUv );
  46936. array.push( parameters.lightMapUv );
  46937. array.push( parameters.aoMapUv );
  46938. array.push( parameters.bumpMapUv );
  46939. array.push( parameters.normalMapUv );
  46940. array.push( parameters.displacementMapUv );
  46941. array.push( parameters.emissiveMapUv );
  46942. array.push( parameters.metalnessMapUv );
  46943. array.push( parameters.roughnessMapUv );
  46944. array.push( parameters.anisotropyMapUv );
  46945. array.push( parameters.clearcoatMapUv );
  46946. array.push( parameters.clearcoatNormalMapUv );
  46947. array.push( parameters.clearcoatRoughnessMapUv );
  46948. array.push( parameters.iridescenceMapUv );
  46949. array.push( parameters.iridescenceThicknessMapUv );
  46950. array.push( parameters.sheenColorMapUv );
  46951. array.push( parameters.sheenRoughnessMapUv );
  46952. array.push( parameters.specularMapUv );
  46953. array.push( parameters.specularColorMapUv );
  46954. array.push( parameters.specularIntensityMapUv );
  46955. array.push( parameters.transmissionMapUv );
  46956. array.push( parameters.thicknessMapUv );
  46957. array.push( parameters.combine );
  46958. array.push( parameters.fogExp2 );
  46959. array.push( parameters.sizeAttenuation );
  46960. array.push( parameters.morphTargetsCount );
  46961. array.push( parameters.morphAttributeCount );
  46962. array.push( parameters.numDirLights );
  46963. array.push( parameters.numPointLights );
  46964. array.push( parameters.numSpotLights );
  46965. array.push( parameters.numSpotLightMaps );
  46966. array.push( parameters.numHemiLights );
  46967. array.push( parameters.numRectAreaLights );
  46968. array.push( parameters.numDirLightShadows );
  46969. array.push( parameters.numPointLightShadows );
  46970. array.push( parameters.numSpotLightShadows );
  46971. array.push( parameters.numSpotLightShadowsWithMaps );
  46972. array.push( parameters.numLightProbes );
  46973. array.push( parameters.shadowMapType );
  46974. array.push( parameters.toneMapping );
  46975. array.push( parameters.numClippingPlanes );
  46976. array.push( parameters.numClipIntersection );
  46977. array.push( parameters.depthPacking );
  46978. }
  46979. function getProgramCacheKeyBooleans( array, parameters ) {
  46980. _programLayers.disableAll();
  46981. if ( parameters.supportsVertexTextures )
  46982. _programLayers.enable( 0 );
  46983. if ( parameters.instancing )
  46984. _programLayers.enable( 1 );
  46985. if ( parameters.instancingColor )
  46986. _programLayers.enable( 2 );
  46987. if ( parameters.instancingMorph )
  46988. _programLayers.enable( 3 );
  46989. if ( parameters.matcap )
  46990. _programLayers.enable( 4 );
  46991. if ( parameters.envMap )
  46992. _programLayers.enable( 5 );
  46993. if ( parameters.normalMapObjectSpace )
  46994. _programLayers.enable( 6 );
  46995. if ( parameters.normalMapTangentSpace )
  46996. _programLayers.enable( 7 );
  46997. if ( parameters.clearcoat )
  46998. _programLayers.enable( 8 );
  46999. if ( parameters.iridescence )
  47000. _programLayers.enable( 9 );
  47001. if ( parameters.alphaTest )
  47002. _programLayers.enable( 10 );
  47003. if ( parameters.vertexColors )
  47004. _programLayers.enable( 11 );
  47005. if ( parameters.vertexAlphas )
  47006. _programLayers.enable( 12 );
  47007. if ( parameters.vertexUv1s )
  47008. _programLayers.enable( 13 );
  47009. if ( parameters.vertexUv2s )
  47010. _programLayers.enable( 14 );
  47011. if ( parameters.vertexUv3s )
  47012. _programLayers.enable( 15 );
  47013. if ( parameters.vertexTangents )
  47014. _programLayers.enable( 16 );
  47015. if ( parameters.anisotropy )
  47016. _programLayers.enable( 17 );
  47017. if ( parameters.alphaHash )
  47018. _programLayers.enable( 18 );
  47019. if ( parameters.batching )
  47020. _programLayers.enable( 19 );
  47021. if ( parameters.dispersion )
  47022. _programLayers.enable( 20 );
  47023. if ( parameters.batchingColor )
  47024. _programLayers.enable( 21 );
  47025. if ( parameters.gradientMap )
  47026. _programLayers.enable( 22 );
  47027. array.push( _programLayers.mask );
  47028. _programLayers.disableAll();
  47029. if ( parameters.fog )
  47030. _programLayers.enable( 0 );
  47031. if ( parameters.useFog )
  47032. _programLayers.enable( 1 );
  47033. if ( parameters.flatShading )
  47034. _programLayers.enable( 2 );
  47035. if ( parameters.logarithmicDepthBuffer )
  47036. _programLayers.enable( 3 );
  47037. if ( parameters.reversedDepthBuffer )
  47038. _programLayers.enable( 4 );
  47039. if ( parameters.skinning )
  47040. _programLayers.enable( 5 );
  47041. if ( parameters.morphTargets )
  47042. _programLayers.enable( 6 );
  47043. if ( parameters.morphNormals )
  47044. _programLayers.enable( 7 );
  47045. if ( parameters.morphColors )
  47046. _programLayers.enable( 8 );
  47047. if ( parameters.premultipliedAlpha )
  47048. _programLayers.enable( 9 );
  47049. if ( parameters.shadowMapEnabled )
  47050. _programLayers.enable( 10 );
  47051. if ( parameters.doubleSided )
  47052. _programLayers.enable( 11 );
  47053. if ( parameters.flipSided )
  47054. _programLayers.enable( 12 );
  47055. if ( parameters.useDepthPacking )
  47056. _programLayers.enable( 13 );
  47057. if ( parameters.dithering )
  47058. _programLayers.enable( 14 );
  47059. if ( parameters.transmission )
  47060. _programLayers.enable( 15 );
  47061. if ( parameters.sheen )
  47062. _programLayers.enable( 16 );
  47063. if ( parameters.opaque )
  47064. _programLayers.enable( 17 );
  47065. if ( parameters.pointsUvs )
  47066. _programLayers.enable( 18 );
  47067. if ( parameters.decodeVideoTexture )
  47068. _programLayers.enable( 19 );
  47069. if ( parameters.decodeVideoTextureEmissive )
  47070. _programLayers.enable( 20 );
  47071. if ( parameters.alphaToCoverage )
  47072. _programLayers.enable( 21 );
  47073. array.push( _programLayers.mask );
  47074. }
  47075. function getUniforms( material ) {
  47076. const shaderID = shaderIDs[ material.type ];
  47077. let uniforms;
  47078. if ( shaderID ) {
  47079. const shader = ShaderLib[ shaderID ];
  47080. uniforms = UniformsUtils.clone( shader.uniforms );
  47081. } else {
  47082. uniforms = material.uniforms;
  47083. }
  47084. return uniforms;
  47085. }
  47086. function acquireProgram( parameters, cacheKey ) {
  47087. let program;
  47088. // Check if code has been already compiled
  47089. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  47090. const preexistingProgram = programs[ p ];
  47091. if ( preexistingProgram.cacheKey === cacheKey ) {
  47092. program = preexistingProgram;
  47093. ++ program.usedTimes;
  47094. break;
  47095. }
  47096. }
  47097. if ( program === undefined ) {
  47098. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  47099. programs.push( program );
  47100. }
  47101. return program;
  47102. }
  47103. function releaseProgram( program ) {
  47104. if ( -- program.usedTimes === 0 ) {
  47105. // Remove from unordered set
  47106. const i = programs.indexOf( program );
  47107. programs[ i ] = programs[ programs.length - 1 ];
  47108. programs.pop();
  47109. // Free WebGL resources
  47110. program.destroy();
  47111. }
  47112. }
  47113. function releaseShaderCache( material ) {
  47114. _customShaders.remove( material );
  47115. }
  47116. function dispose() {
  47117. _customShaders.dispose();
  47118. }
  47119. return {
  47120. getParameters: getParameters,
  47121. getProgramCacheKey: getProgramCacheKey,
  47122. getUniforms: getUniforms,
  47123. acquireProgram: acquireProgram,
  47124. releaseProgram: releaseProgram,
  47125. releaseShaderCache: releaseShaderCache,
  47126. // Exposed for resource monitoring & error feedback via renderer.info:
  47127. programs: programs,
  47128. dispose: dispose
  47129. };
  47130. }
  47131. function WebGLProperties() {
  47132. let properties = new WeakMap();
  47133. function has( object ) {
  47134. return properties.has( object );
  47135. }
  47136. function get( object ) {
  47137. let map = properties.get( object );
  47138. if ( map === undefined ) {
  47139. map = {};
  47140. properties.set( object, map );
  47141. }
  47142. return map;
  47143. }
  47144. function remove( object ) {
  47145. properties.delete( object );
  47146. }
  47147. function update( object, key, value ) {
  47148. properties.get( object )[ key ] = value;
  47149. }
  47150. function dispose() {
  47151. properties = new WeakMap();
  47152. }
  47153. return {
  47154. has: has,
  47155. get: get,
  47156. remove: remove,
  47157. update: update,
  47158. dispose: dispose
  47159. };
  47160. }
  47161. function painterSortStable( a, b ) {
  47162. if ( a.groupOrder !== b.groupOrder ) {
  47163. return a.groupOrder - b.groupOrder;
  47164. } else if ( a.renderOrder !== b.renderOrder ) {
  47165. return a.renderOrder - b.renderOrder;
  47166. } else if ( a.material.id !== b.material.id ) {
  47167. return a.material.id - b.material.id;
  47168. } else if ( a.z !== b.z ) {
  47169. return a.z - b.z;
  47170. } else {
  47171. return a.id - b.id;
  47172. }
  47173. }
  47174. function reversePainterSortStable( a, b ) {
  47175. if ( a.groupOrder !== b.groupOrder ) {
  47176. return a.groupOrder - b.groupOrder;
  47177. } else if ( a.renderOrder !== b.renderOrder ) {
  47178. return a.renderOrder - b.renderOrder;
  47179. } else if ( a.z !== b.z ) {
  47180. return b.z - a.z;
  47181. } else {
  47182. return a.id - b.id;
  47183. }
  47184. }
  47185. function WebGLRenderList() {
  47186. const renderItems = [];
  47187. let renderItemsIndex = 0;
  47188. const opaque = [];
  47189. const transmissive = [];
  47190. const transparent = [];
  47191. function init() {
  47192. renderItemsIndex = 0;
  47193. opaque.length = 0;
  47194. transmissive.length = 0;
  47195. transparent.length = 0;
  47196. }
  47197. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  47198. let renderItem = renderItems[ renderItemsIndex ];
  47199. if ( renderItem === undefined ) {
  47200. renderItem = {
  47201. id: object.id,
  47202. object: object,
  47203. geometry: geometry,
  47204. material: material,
  47205. groupOrder: groupOrder,
  47206. renderOrder: object.renderOrder,
  47207. z: z,
  47208. group: group
  47209. };
  47210. renderItems[ renderItemsIndex ] = renderItem;
  47211. } else {
  47212. renderItem.id = object.id;
  47213. renderItem.object = object;
  47214. renderItem.geometry = geometry;
  47215. renderItem.material = material;
  47216. renderItem.groupOrder = groupOrder;
  47217. renderItem.renderOrder = object.renderOrder;
  47218. renderItem.z = z;
  47219. renderItem.group = group;
  47220. }
  47221. renderItemsIndex ++;
  47222. return renderItem;
  47223. }
  47224. function push( object, geometry, material, groupOrder, z, group ) {
  47225. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  47226. if ( material.transmission > 0.0 ) {
  47227. transmissive.push( renderItem );
  47228. } else if ( material.transparent === true ) {
  47229. transparent.push( renderItem );
  47230. } else {
  47231. opaque.push( renderItem );
  47232. }
  47233. }
  47234. function unshift( object, geometry, material, groupOrder, z, group ) {
  47235. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  47236. if ( material.transmission > 0.0 ) {
  47237. transmissive.unshift( renderItem );
  47238. } else if ( material.transparent === true ) {
  47239. transparent.unshift( renderItem );
  47240. } else {
  47241. opaque.unshift( renderItem );
  47242. }
  47243. }
  47244. function sort( customOpaqueSort, customTransparentSort ) {
  47245. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  47246. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  47247. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  47248. }
  47249. function finish() {
  47250. // Clear references from inactive renderItems in the list
  47251. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  47252. const renderItem = renderItems[ i ];
  47253. if ( renderItem.id === null ) break;
  47254. renderItem.id = null;
  47255. renderItem.object = null;
  47256. renderItem.geometry = null;
  47257. renderItem.material = null;
  47258. renderItem.group = null;
  47259. }
  47260. }
  47261. return {
  47262. opaque: opaque,
  47263. transmissive: transmissive,
  47264. transparent: transparent,
  47265. init: init,
  47266. push: push,
  47267. unshift: unshift,
  47268. finish: finish,
  47269. sort: sort
  47270. };
  47271. }
  47272. function WebGLRenderLists() {
  47273. let lists = new WeakMap();
  47274. function get( scene, renderCallDepth ) {
  47275. const listArray = lists.get( scene );
  47276. let list;
  47277. if ( listArray === undefined ) {
  47278. list = new WebGLRenderList();
  47279. lists.set( scene, [ list ] );
  47280. } else {
  47281. if ( renderCallDepth >= listArray.length ) {
  47282. list = new WebGLRenderList();
  47283. listArray.push( list );
  47284. } else {
  47285. list = listArray[ renderCallDepth ];
  47286. }
  47287. }
  47288. return list;
  47289. }
  47290. function dispose() {
  47291. lists = new WeakMap();
  47292. }
  47293. return {
  47294. get: get,
  47295. dispose: dispose
  47296. };
  47297. }
  47298. function UniformsCache() {
  47299. const lights = {};
  47300. return {
  47301. get: function ( light ) {
  47302. if ( lights[ light.id ] !== undefined ) {
  47303. return lights[ light.id ];
  47304. }
  47305. let uniforms;
  47306. switch ( light.type ) {
  47307. case 'DirectionalLight':
  47308. uniforms = {
  47309. direction: new Vector3(),
  47310. color: new Color()
  47311. };
  47312. break;
  47313. case 'SpotLight':
  47314. uniforms = {
  47315. position: new Vector3(),
  47316. direction: new Vector3(),
  47317. color: new Color(),
  47318. distance: 0,
  47319. coneCos: 0,
  47320. penumbraCos: 0,
  47321. decay: 0
  47322. };
  47323. break;
  47324. case 'PointLight':
  47325. uniforms = {
  47326. position: new Vector3(),
  47327. color: new Color(),
  47328. distance: 0,
  47329. decay: 0
  47330. };
  47331. break;
  47332. case 'HemisphereLight':
  47333. uniforms = {
  47334. direction: new Vector3(),
  47335. skyColor: new Color(),
  47336. groundColor: new Color()
  47337. };
  47338. break;
  47339. case 'RectAreaLight':
  47340. uniforms = {
  47341. color: new Color(),
  47342. position: new Vector3(),
  47343. halfWidth: new Vector3(),
  47344. halfHeight: new Vector3()
  47345. };
  47346. break;
  47347. }
  47348. lights[ light.id ] = uniforms;
  47349. return uniforms;
  47350. }
  47351. };
  47352. }
  47353. function ShadowUniformsCache() {
  47354. const lights = {};
  47355. return {
  47356. get: function ( light ) {
  47357. if ( lights[ light.id ] !== undefined ) {
  47358. return lights[ light.id ];
  47359. }
  47360. let uniforms;
  47361. switch ( light.type ) {
  47362. case 'DirectionalLight':
  47363. uniforms = {
  47364. shadowIntensity: 1,
  47365. shadowBias: 0,
  47366. shadowNormalBias: 0,
  47367. shadowRadius: 1,
  47368. shadowMapSize: new Vector2()
  47369. };
  47370. break;
  47371. case 'SpotLight':
  47372. uniforms = {
  47373. shadowIntensity: 1,
  47374. shadowBias: 0,
  47375. shadowNormalBias: 0,
  47376. shadowRadius: 1,
  47377. shadowMapSize: new Vector2()
  47378. };
  47379. break;
  47380. case 'PointLight':
  47381. uniforms = {
  47382. shadowIntensity: 1,
  47383. shadowBias: 0,
  47384. shadowNormalBias: 0,
  47385. shadowRadius: 1,
  47386. shadowMapSize: new Vector2(),
  47387. shadowCameraNear: 1,
  47388. shadowCameraFar: 1000
  47389. };
  47390. break;
  47391. // TODO (abelnation): set RectAreaLight shadow uniforms
  47392. }
  47393. lights[ light.id ] = uniforms;
  47394. return uniforms;
  47395. }
  47396. };
  47397. }
  47398. let nextVersion = 0;
  47399. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  47400. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  47401. }
  47402. function WebGLLights( extensions ) {
  47403. const cache = new UniformsCache();
  47404. const shadowCache = ShadowUniformsCache();
  47405. const state = {
  47406. version: 0,
  47407. hash: {
  47408. directionalLength: -1,
  47409. pointLength: -1,
  47410. spotLength: -1,
  47411. rectAreaLength: -1,
  47412. hemiLength: -1,
  47413. numDirectionalShadows: -1,
  47414. numPointShadows: -1,
  47415. numSpotShadows: -1,
  47416. numSpotMaps: -1,
  47417. numLightProbes: -1
  47418. },
  47419. ambient: [ 0, 0, 0 ],
  47420. probe: [],
  47421. directional: [],
  47422. directionalShadow: [],
  47423. directionalShadowMap: [],
  47424. directionalShadowMatrix: [],
  47425. spot: [],
  47426. spotLightMap: [],
  47427. spotShadow: [],
  47428. spotShadowMap: [],
  47429. spotLightMatrix: [],
  47430. rectArea: [],
  47431. rectAreaLTC1: null,
  47432. rectAreaLTC2: null,
  47433. point: [],
  47434. pointShadow: [],
  47435. pointShadowMap: [],
  47436. pointShadowMatrix: [],
  47437. hemi: [],
  47438. numSpotLightShadowsWithMaps: 0,
  47439. numLightProbes: 0
  47440. };
  47441. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  47442. const vector3 = new Vector3();
  47443. const matrix4 = new Matrix4();
  47444. const matrix42 = new Matrix4();
  47445. function setup( lights ) {
  47446. let r = 0, g = 0, b = 0;
  47447. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  47448. let directionalLength = 0;
  47449. let pointLength = 0;
  47450. let spotLength = 0;
  47451. let rectAreaLength = 0;
  47452. let hemiLength = 0;
  47453. let numDirectionalShadows = 0;
  47454. let numPointShadows = 0;
  47455. let numSpotShadows = 0;
  47456. let numSpotMaps = 0;
  47457. let numSpotShadowsWithMaps = 0;
  47458. let numLightProbes = 0;
  47459. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  47460. lights.sort( shadowCastingAndTexturingLightsFirst );
  47461. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  47462. const light = lights[ i ];
  47463. const color = light.color;
  47464. const intensity = light.intensity;
  47465. const distance = light.distance;
  47466. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  47467. if ( light.isAmbientLight ) {
  47468. r += color.r * intensity;
  47469. g += color.g * intensity;
  47470. b += color.b * intensity;
  47471. } else if ( light.isLightProbe ) {
  47472. for ( let j = 0; j < 9; j ++ ) {
  47473. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  47474. }
  47475. numLightProbes ++;
  47476. } else if ( light.isDirectionalLight ) {
  47477. const uniforms = cache.get( light );
  47478. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  47479. if ( light.castShadow ) {
  47480. const shadow = light.shadow;
  47481. const shadowUniforms = shadowCache.get( light );
  47482. shadowUniforms.shadowIntensity = shadow.intensity;
  47483. shadowUniforms.shadowBias = shadow.bias;
  47484. shadowUniforms.shadowNormalBias = shadow.normalBias;
  47485. shadowUniforms.shadowRadius = shadow.radius;
  47486. shadowUniforms.shadowMapSize = shadow.mapSize;
  47487. state.directionalShadow[ directionalLength ] = shadowUniforms;
  47488. state.directionalShadowMap[ directionalLength ] = shadowMap;
  47489. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  47490. numDirectionalShadows ++;
  47491. }
  47492. state.directional[ directionalLength ] = uniforms;
  47493. directionalLength ++;
  47494. } else if ( light.isSpotLight ) {
  47495. const uniforms = cache.get( light );
  47496. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  47497. uniforms.color.copy( color ).multiplyScalar( intensity );
  47498. uniforms.distance = distance;
  47499. uniforms.coneCos = Math.cos( light.angle );
  47500. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  47501. uniforms.decay = light.decay;
  47502. state.spot[ spotLength ] = uniforms;
  47503. const shadow = light.shadow;
  47504. if ( light.map ) {
  47505. state.spotLightMap[ numSpotMaps ] = light.map;
  47506. numSpotMaps ++;
  47507. // make sure the lightMatrix is up to date
  47508. // TODO : do it if required only
  47509. shadow.updateMatrices( light );
  47510. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  47511. }
  47512. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  47513. if ( light.castShadow ) {
  47514. const shadowUniforms = shadowCache.get( light );
  47515. shadowUniforms.shadowIntensity = shadow.intensity;
  47516. shadowUniforms.shadowBias = shadow.bias;
  47517. shadowUniforms.shadowNormalBias = shadow.normalBias;
  47518. shadowUniforms.shadowRadius = shadow.radius;
  47519. shadowUniforms.shadowMapSize = shadow.mapSize;
  47520. state.spotShadow[ spotLength ] = shadowUniforms;
  47521. state.spotShadowMap[ spotLength ] = shadowMap;
  47522. numSpotShadows ++;
  47523. }
  47524. spotLength ++;
  47525. } else if ( light.isRectAreaLight ) {
  47526. const uniforms = cache.get( light );
  47527. uniforms.color.copy( color ).multiplyScalar( intensity );
  47528. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  47529. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  47530. state.rectArea[ rectAreaLength ] = uniforms;
  47531. rectAreaLength ++;
  47532. } else if ( light.isPointLight ) {
  47533. const uniforms = cache.get( light );
  47534. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  47535. uniforms.distance = light.distance;
  47536. uniforms.decay = light.decay;
  47537. if ( light.castShadow ) {
  47538. const shadow = light.shadow;
  47539. const shadowUniforms = shadowCache.get( light );
  47540. shadowUniforms.shadowIntensity = shadow.intensity;
  47541. shadowUniforms.shadowBias = shadow.bias;
  47542. shadowUniforms.shadowNormalBias = shadow.normalBias;
  47543. shadowUniforms.shadowRadius = shadow.radius;
  47544. shadowUniforms.shadowMapSize = shadow.mapSize;
  47545. shadowUniforms.shadowCameraNear = shadow.camera.near;
  47546. shadowUniforms.shadowCameraFar = shadow.camera.far;
  47547. state.pointShadow[ pointLength ] = shadowUniforms;
  47548. state.pointShadowMap[ pointLength ] = shadowMap;
  47549. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  47550. numPointShadows ++;
  47551. }
  47552. state.point[ pointLength ] = uniforms;
  47553. pointLength ++;
  47554. } else if ( light.isHemisphereLight ) {
  47555. const uniforms = cache.get( light );
  47556. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  47557. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  47558. state.hemi[ hemiLength ] = uniforms;
  47559. hemiLength ++;
  47560. }
  47561. }
  47562. if ( rectAreaLength > 0 ) {
  47563. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  47564. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  47565. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  47566. } else {
  47567. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  47568. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  47569. }
  47570. }
  47571. state.ambient[ 0 ] = r;
  47572. state.ambient[ 1 ] = g;
  47573. state.ambient[ 2 ] = b;
  47574. const hash = state.hash;
  47575. if ( hash.directionalLength !== directionalLength ||
  47576. hash.pointLength !== pointLength ||
  47577. hash.spotLength !== spotLength ||
  47578. hash.rectAreaLength !== rectAreaLength ||
  47579. hash.hemiLength !== hemiLength ||
  47580. hash.numDirectionalShadows !== numDirectionalShadows ||
  47581. hash.numPointShadows !== numPointShadows ||
  47582. hash.numSpotShadows !== numSpotShadows ||
  47583. hash.numSpotMaps !== numSpotMaps ||
  47584. hash.numLightProbes !== numLightProbes ) {
  47585. state.directional.length = directionalLength;
  47586. state.spot.length = spotLength;
  47587. state.rectArea.length = rectAreaLength;
  47588. state.point.length = pointLength;
  47589. state.hemi.length = hemiLength;
  47590. state.directionalShadow.length = numDirectionalShadows;
  47591. state.directionalShadowMap.length = numDirectionalShadows;
  47592. state.pointShadow.length = numPointShadows;
  47593. state.pointShadowMap.length = numPointShadows;
  47594. state.spotShadow.length = numSpotShadows;
  47595. state.spotShadowMap.length = numSpotShadows;
  47596. state.directionalShadowMatrix.length = numDirectionalShadows;
  47597. state.pointShadowMatrix.length = numPointShadows;
  47598. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  47599. state.spotLightMap.length = numSpotMaps;
  47600. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  47601. state.numLightProbes = numLightProbes;
  47602. hash.directionalLength = directionalLength;
  47603. hash.pointLength = pointLength;
  47604. hash.spotLength = spotLength;
  47605. hash.rectAreaLength = rectAreaLength;
  47606. hash.hemiLength = hemiLength;
  47607. hash.numDirectionalShadows = numDirectionalShadows;
  47608. hash.numPointShadows = numPointShadows;
  47609. hash.numSpotShadows = numSpotShadows;
  47610. hash.numSpotMaps = numSpotMaps;
  47611. hash.numLightProbes = numLightProbes;
  47612. state.version = nextVersion ++;
  47613. }
  47614. }
  47615. function setupView( lights, camera ) {
  47616. let directionalLength = 0;
  47617. let pointLength = 0;
  47618. let spotLength = 0;
  47619. let rectAreaLength = 0;
  47620. let hemiLength = 0;
  47621. const viewMatrix = camera.matrixWorldInverse;
  47622. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  47623. const light = lights[ i ];
  47624. if ( light.isDirectionalLight ) {
  47625. const uniforms = state.directional[ directionalLength ];
  47626. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  47627. vector3.setFromMatrixPosition( light.target.matrixWorld );
  47628. uniforms.direction.sub( vector3 );
  47629. uniforms.direction.transformDirection( viewMatrix );
  47630. directionalLength ++;
  47631. } else if ( light.isSpotLight ) {
  47632. const uniforms = state.spot[ spotLength ];
  47633. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  47634. uniforms.position.applyMatrix4( viewMatrix );
  47635. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  47636. vector3.setFromMatrixPosition( light.target.matrixWorld );
  47637. uniforms.direction.sub( vector3 );
  47638. uniforms.direction.transformDirection( viewMatrix );
  47639. spotLength ++;
  47640. } else if ( light.isRectAreaLight ) {
  47641. const uniforms = state.rectArea[ rectAreaLength ];
  47642. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  47643. uniforms.position.applyMatrix4( viewMatrix );
  47644. // extract local rotation of light to derive width/height half vectors
  47645. matrix42.identity();
  47646. matrix4.copy( light.matrixWorld );
  47647. matrix4.premultiply( viewMatrix );
  47648. matrix42.extractRotation( matrix4 );
  47649. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  47650. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  47651. uniforms.halfWidth.applyMatrix4( matrix42 );
  47652. uniforms.halfHeight.applyMatrix4( matrix42 );
  47653. rectAreaLength ++;
  47654. } else if ( light.isPointLight ) {
  47655. const uniforms = state.point[ pointLength ];
  47656. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  47657. uniforms.position.applyMatrix4( viewMatrix );
  47658. pointLength ++;
  47659. } else if ( light.isHemisphereLight ) {
  47660. const uniforms = state.hemi[ hemiLength ];
  47661. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  47662. uniforms.direction.transformDirection( viewMatrix );
  47663. hemiLength ++;
  47664. }
  47665. }
  47666. }
  47667. return {
  47668. setup: setup,
  47669. setupView: setupView,
  47670. state: state
  47671. };
  47672. }
  47673. function WebGLRenderState( extensions ) {
  47674. const lights = new WebGLLights( extensions );
  47675. const lightsArray = [];
  47676. const shadowsArray = [];
  47677. function init( camera ) {
  47678. state.camera = camera;
  47679. lightsArray.length = 0;
  47680. shadowsArray.length = 0;
  47681. }
  47682. function pushLight( light ) {
  47683. lightsArray.push( light );
  47684. }
  47685. function pushShadow( shadowLight ) {
  47686. shadowsArray.push( shadowLight );
  47687. }
  47688. function setupLights() {
  47689. lights.setup( lightsArray );
  47690. }
  47691. function setupLightsView( camera ) {
  47692. lights.setupView( lightsArray, camera );
  47693. }
  47694. const state = {
  47695. lightsArray: lightsArray,
  47696. shadowsArray: shadowsArray,
  47697. camera: null,
  47698. lights: lights,
  47699. transmissionRenderTarget: {}
  47700. };
  47701. return {
  47702. init: init,
  47703. state: state,
  47704. setupLights: setupLights,
  47705. setupLightsView: setupLightsView,
  47706. pushLight: pushLight,
  47707. pushShadow: pushShadow
  47708. };
  47709. }
  47710. function WebGLRenderStates( extensions ) {
  47711. let renderStates = new WeakMap();
  47712. function get( scene, renderCallDepth = 0 ) {
  47713. const renderStateArray = renderStates.get( scene );
  47714. let renderState;
  47715. if ( renderStateArray === undefined ) {
  47716. renderState = new WebGLRenderState( extensions );
  47717. renderStates.set( scene, [ renderState ] );
  47718. } else {
  47719. if ( renderCallDepth >= renderStateArray.length ) {
  47720. renderState = new WebGLRenderState( extensions );
  47721. renderStateArray.push( renderState );
  47722. } else {
  47723. renderState = renderStateArray[ renderCallDepth ];
  47724. }
  47725. }
  47726. return renderState;
  47727. }
  47728. function dispose() {
  47729. renderStates = new WeakMap();
  47730. }
  47731. return {
  47732. get: get,
  47733. dispose: dispose
  47734. };
  47735. }
  47736. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  47737. 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}";
  47738. function WebGLShadowMap( renderer, objects, capabilities ) {
  47739. let _frustum = new Frustum();
  47740. const _shadowMapSize = new Vector2(),
  47741. _viewportSize = new Vector2(),
  47742. _viewport = new Vector4(),
  47743. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  47744. _distanceMaterial = new MeshDistanceMaterial(),
  47745. _materialCache = {},
  47746. _maxTextureSize = capabilities.maxTextureSize;
  47747. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  47748. const shadowMaterialVertical = new ShaderMaterial( {
  47749. defines: {
  47750. VSM_SAMPLES: 8
  47751. },
  47752. uniforms: {
  47753. shadow_pass: { value: null },
  47754. resolution: { value: new Vector2() },
  47755. radius: { value: 4.0 }
  47756. },
  47757. vertexShader: vertex,
  47758. fragmentShader: fragment
  47759. } );
  47760. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  47761. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  47762. const fullScreenTri = new BufferGeometry();
  47763. fullScreenTri.setAttribute(
  47764. 'position',
  47765. new BufferAttribute(
  47766. new Float32Array( [ -1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5 ] ),
  47767. 3
  47768. )
  47769. );
  47770. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  47771. const scope = this;
  47772. this.enabled = false;
  47773. this.autoUpdate = true;
  47774. this.needsUpdate = false;
  47775. this.type = PCFShadowMap;
  47776. let _previousType = this.type;
  47777. this.render = function ( lights, scene, camera ) {
  47778. if ( scope.enabled === false ) return;
  47779. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  47780. if ( lights.length === 0 ) return;
  47781. const currentRenderTarget = renderer.getRenderTarget();
  47782. const activeCubeFace = renderer.getActiveCubeFace();
  47783. const activeMipmapLevel = renderer.getActiveMipmapLevel();
  47784. const _state = renderer.state;
  47785. // Set GL state for depth map.
  47786. _state.setBlending( NoBlending );
  47787. if ( _state.buffers.depth.getReversed() === true ) {
  47788. _state.buffers.color.setClear( 0, 0, 0, 0 );
  47789. } else {
  47790. _state.buffers.color.setClear( 1, 1, 1, 1 );
  47791. }
  47792. _state.buffers.depth.setTest( true );
  47793. _state.setScissorTest( false );
  47794. // check for shadow map type changes
  47795. const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap );
  47796. const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap );
  47797. // render depth map
  47798. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  47799. const light = lights[ i ];
  47800. const shadow = light.shadow;
  47801. if ( shadow === undefined ) {
  47802. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  47803. continue;
  47804. }
  47805. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  47806. _shadowMapSize.copy( shadow.mapSize );
  47807. const shadowFrameExtents = shadow.getFrameExtents();
  47808. _shadowMapSize.multiply( shadowFrameExtents );
  47809. _viewportSize.copy( shadow.mapSize );
  47810. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  47811. if ( _shadowMapSize.x > _maxTextureSize ) {
  47812. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  47813. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  47814. shadow.mapSize.x = _viewportSize.x;
  47815. }
  47816. if ( _shadowMapSize.y > _maxTextureSize ) {
  47817. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  47818. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  47819. shadow.mapSize.y = _viewportSize.y;
  47820. }
  47821. }
  47822. if ( shadow.map === null || toVSM === true || fromVSM === true ) {
  47823. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  47824. if ( shadow.map !== null ) {
  47825. shadow.map.dispose();
  47826. }
  47827. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  47828. shadow.map.texture.name = light.name + '.shadowMap';
  47829. shadow.camera.updateProjectionMatrix();
  47830. }
  47831. renderer.setRenderTarget( shadow.map );
  47832. renderer.clear();
  47833. const viewportCount = shadow.getViewportCount();
  47834. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  47835. const viewport = shadow.getViewport( vp );
  47836. _viewport.set(
  47837. _viewportSize.x * viewport.x,
  47838. _viewportSize.y * viewport.y,
  47839. _viewportSize.x * viewport.z,
  47840. _viewportSize.y * viewport.w
  47841. );
  47842. _state.viewport( _viewport );
  47843. shadow.updateMatrices( light, vp );
  47844. _frustum = shadow.getFrustum();
  47845. renderObject( scene, camera, shadow.camera, light, this.type );
  47846. }
  47847. // do blur pass for VSM
  47848. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  47849. VSMPass( shadow, camera );
  47850. }
  47851. shadow.needsUpdate = false;
  47852. }
  47853. _previousType = this.type;
  47854. scope.needsUpdate = false;
  47855. renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  47856. };
  47857. function VSMPass( shadow, camera ) {
  47858. const geometry = objects.update( fullScreenMesh );
  47859. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  47860. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  47861. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  47862. shadowMaterialVertical.needsUpdate = true;
  47863. shadowMaterialHorizontal.needsUpdate = true;
  47864. }
  47865. if ( shadow.mapPass === null ) {
  47866. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  47867. }
  47868. // vertical pass
  47869. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  47870. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  47871. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  47872. renderer.setRenderTarget( shadow.mapPass );
  47873. renderer.clear();
  47874. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  47875. // horizontal pass
  47876. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  47877. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  47878. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  47879. renderer.setRenderTarget( shadow.map );
  47880. renderer.clear();
  47881. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  47882. }
  47883. function getDepthMaterial( object, material, light, type ) {
  47884. let result = null;
  47885. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  47886. if ( customMaterial !== undefined ) {
  47887. result = customMaterial;
  47888. } else {
  47889. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  47890. if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  47891. ( material.displacementMap && material.displacementScale !== 0 ) ||
  47892. ( material.alphaMap && material.alphaTest > 0 ) ||
  47893. ( material.map && material.alphaTest > 0 ) ||
  47894. ( material.alphaToCoverage === true ) ) {
  47895. // in this case we need a unique material instance reflecting the
  47896. // appropriate state
  47897. const keyA = result.uuid, keyB = material.uuid;
  47898. let materialsForVariant = _materialCache[ keyA ];
  47899. if ( materialsForVariant === undefined ) {
  47900. materialsForVariant = {};
  47901. _materialCache[ keyA ] = materialsForVariant;
  47902. }
  47903. let cachedMaterial = materialsForVariant[ keyB ];
  47904. if ( cachedMaterial === undefined ) {
  47905. cachedMaterial = result.clone();
  47906. materialsForVariant[ keyB ] = cachedMaterial;
  47907. material.addEventListener( 'dispose', onMaterialDispose );
  47908. }
  47909. result = cachedMaterial;
  47910. }
  47911. }
  47912. result.visible = material.visible;
  47913. result.wireframe = material.wireframe;
  47914. if ( type === VSMShadowMap ) {
  47915. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  47916. } else {
  47917. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  47918. }
  47919. result.alphaMap = material.alphaMap;
  47920. result.alphaTest = ( material.alphaToCoverage === true ) ? 0.5 : material.alphaTest; // approximate alphaToCoverage by using a fixed alphaTest value
  47921. result.map = material.map;
  47922. result.clipShadows = material.clipShadows;
  47923. result.clippingPlanes = material.clippingPlanes;
  47924. result.clipIntersection = material.clipIntersection;
  47925. result.displacementMap = material.displacementMap;
  47926. result.displacementScale = material.displacementScale;
  47927. result.displacementBias = material.displacementBias;
  47928. result.wireframeLinewidth = material.wireframeLinewidth;
  47929. result.linewidth = material.linewidth;
  47930. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  47931. const materialProperties = renderer.properties.get( result );
  47932. materialProperties.light = light;
  47933. }
  47934. return result;
  47935. }
  47936. function renderObject( object, camera, shadowCamera, light, type ) {
  47937. if ( object.visible === false ) return;
  47938. const visible = object.layers.test( camera.layers );
  47939. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  47940. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  47941. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  47942. const geometry = objects.update( object );
  47943. const material = object.material;
  47944. if ( Array.isArray( material ) ) {
  47945. const groups = geometry.groups;
  47946. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  47947. const group = groups[ k ];
  47948. const groupMaterial = material[ group.materialIndex ];
  47949. if ( groupMaterial && groupMaterial.visible ) {
  47950. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  47951. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  47952. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  47953. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  47954. }
  47955. }
  47956. } else if ( material.visible ) {
  47957. const depthMaterial = getDepthMaterial( object, material, light, type );
  47958. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  47959. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  47960. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  47961. }
  47962. }
  47963. }
  47964. const children = object.children;
  47965. for ( let i = 0, l = children.length; i < l; i ++ ) {
  47966. renderObject( children[ i ], camera, shadowCamera, light, type );
  47967. }
  47968. }
  47969. function onMaterialDispose( event ) {
  47970. const material = event.target;
  47971. material.removeEventListener( 'dispose', onMaterialDispose );
  47972. // make sure to remove the unique distance/depth materials used for shadow map rendering
  47973. for ( const id in _materialCache ) {
  47974. const cache = _materialCache[ id ];
  47975. const uuid = event.target.uuid;
  47976. if ( uuid in cache ) {
  47977. const shadowMaterial = cache[ uuid ];
  47978. shadowMaterial.dispose();
  47979. delete cache[ uuid ];
  47980. }
  47981. }
  47982. }
  47983. }
  47984. const reversedFuncs = {
  47985. [ NeverDepth ]: AlwaysDepth,
  47986. [ LessDepth ]: GreaterDepth,
  47987. [ EqualDepth ]: NotEqualDepth,
  47988. [ LessEqualDepth ]: GreaterEqualDepth,
  47989. [ AlwaysDepth ]: NeverDepth,
  47990. [ GreaterDepth ]: LessDepth,
  47991. [ NotEqualDepth ]: EqualDepth,
  47992. [ GreaterEqualDepth ]: LessEqualDepth,
  47993. };
  47994. function WebGLState( gl, extensions ) {
  47995. function ColorBuffer() {
  47996. let locked = false;
  47997. const color = new Vector4();
  47998. let currentColorMask = null;
  47999. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  48000. return {
  48001. setMask: function ( colorMask ) {
  48002. if ( currentColorMask !== colorMask && ! locked ) {
  48003. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  48004. currentColorMask = colorMask;
  48005. }
  48006. },
  48007. setLocked: function ( lock ) {
  48008. locked = lock;
  48009. },
  48010. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  48011. if ( premultipliedAlpha === true ) {
  48012. r *= a; g *= a; b *= a;
  48013. }
  48014. color.set( r, g, b, a );
  48015. if ( currentColorClear.equals( color ) === false ) {
  48016. gl.clearColor( r, g, b, a );
  48017. currentColorClear.copy( color );
  48018. }
  48019. },
  48020. reset: function () {
  48021. locked = false;
  48022. currentColorMask = null;
  48023. currentColorClear.set( -1, 0, 0, 0 ); // set to invalid state
  48024. }
  48025. };
  48026. }
  48027. function DepthBuffer() {
  48028. let locked = false;
  48029. let currentReversed = false;
  48030. let currentDepthMask = null;
  48031. let currentDepthFunc = null;
  48032. let currentDepthClear = null;
  48033. return {
  48034. setReversed: function ( reversed ) {
  48035. if ( currentReversed !== reversed ) {
  48036. const ext = extensions.get( 'EXT_clip_control' );
  48037. if ( reversed ) {
  48038. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT );
  48039. } else {
  48040. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT );
  48041. }
  48042. currentReversed = reversed;
  48043. const oldDepth = currentDepthClear;
  48044. currentDepthClear = null;
  48045. this.setClear( oldDepth );
  48046. }
  48047. },
  48048. getReversed: function () {
  48049. return currentReversed;
  48050. },
  48051. setTest: function ( depthTest ) {
  48052. if ( depthTest ) {
  48053. enable( gl.DEPTH_TEST );
  48054. } else {
  48055. disable( gl.DEPTH_TEST );
  48056. }
  48057. },
  48058. setMask: function ( depthMask ) {
  48059. if ( currentDepthMask !== depthMask && ! locked ) {
  48060. gl.depthMask( depthMask );
  48061. currentDepthMask = depthMask;
  48062. }
  48063. },
  48064. setFunc: function ( depthFunc ) {
  48065. if ( currentReversed ) depthFunc = reversedFuncs[ depthFunc ];
  48066. if ( currentDepthFunc !== depthFunc ) {
  48067. switch ( depthFunc ) {
  48068. case NeverDepth:
  48069. gl.depthFunc( gl.NEVER );
  48070. break;
  48071. case AlwaysDepth:
  48072. gl.depthFunc( gl.ALWAYS );
  48073. break;
  48074. case LessDepth:
  48075. gl.depthFunc( gl.LESS );
  48076. break;
  48077. case LessEqualDepth:
  48078. gl.depthFunc( gl.LEQUAL );
  48079. break;
  48080. case EqualDepth:
  48081. gl.depthFunc( gl.EQUAL );
  48082. break;
  48083. case GreaterEqualDepth:
  48084. gl.depthFunc( gl.GEQUAL );
  48085. break;
  48086. case GreaterDepth:
  48087. gl.depthFunc( gl.GREATER );
  48088. break;
  48089. case NotEqualDepth:
  48090. gl.depthFunc( gl.NOTEQUAL );
  48091. break;
  48092. default:
  48093. gl.depthFunc( gl.LEQUAL );
  48094. }
  48095. currentDepthFunc = depthFunc;
  48096. }
  48097. },
  48098. setLocked: function ( lock ) {
  48099. locked = lock;
  48100. },
  48101. setClear: function ( depth ) {
  48102. if ( currentDepthClear !== depth ) {
  48103. if ( currentReversed ) {
  48104. depth = 1 - depth;
  48105. }
  48106. gl.clearDepth( depth );
  48107. currentDepthClear = depth;
  48108. }
  48109. },
  48110. reset: function () {
  48111. locked = false;
  48112. currentDepthMask = null;
  48113. currentDepthFunc = null;
  48114. currentDepthClear = null;
  48115. currentReversed = false;
  48116. }
  48117. };
  48118. }
  48119. function StencilBuffer() {
  48120. let locked = false;
  48121. let currentStencilMask = null;
  48122. let currentStencilFunc = null;
  48123. let currentStencilRef = null;
  48124. let currentStencilFuncMask = null;
  48125. let currentStencilFail = null;
  48126. let currentStencilZFail = null;
  48127. let currentStencilZPass = null;
  48128. let currentStencilClear = null;
  48129. return {
  48130. setTest: function ( stencilTest ) {
  48131. if ( ! locked ) {
  48132. if ( stencilTest ) {
  48133. enable( gl.STENCIL_TEST );
  48134. } else {
  48135. disable( gl.STENCIL_TEST );
  48136. }
  48137. }
  48138. },
  48139. setMask: function ( stencilMask ) {
  48140. if ( currentStencilMask !== stencilMask && ! locked ) {
  48141. gl.stencilMask( stencilMask );
  48142. currentStencilMask = stencilMask;
  48143. }
  48144. },
  48145. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  48146. if ( currentStencilFunc !== stencilFunc ||
  48147. currentStencilRef !== stencilRef ||
  48148. currentStencilFuncMask !== stencilMask ) {
  48149. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  48150. currentStencilFunc = stencilFunc;
  48151. currentStencilRef = stencilRef;
  48152. currentStencilFuncMask = stencilMask;
  48153. }
  48154. },
  48155. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  48156. if ( currentStencilFail !== stencilFail ||
  48157. currentStencilZFail !== stencilZFail ||
  48158. currentStencilZPass !== stencilZPass ) {
  48159. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  48160. currentStencilFail = stencilFail;
  48161. currentStencilZFail = stencilZFail;
  48162. currentStencilZPass = stencilZPass;
  48163. }
  48164. },
  48165. setLocked: function ( lock ) {
  48166. locked = lock;
  48167. },
  48168. setClear: function ( stencil ) {
  48169. if ( currentStencilClear !== stencil ) {
  48170. gl.clearStencil( stencil );
  48171. currentStencilClear = stencil;
  48172. }
  48173. },
  48174. reset: function () {
  48175. locked = false;
  48176. currentStencilMask = null;
  48177. currentStencilFunc = null;
  48178. currentStencilRef = null;
  48179. currentStencilFuncMask = null;
  48180. currentStencilFail = null;
  48181. currentStencilZFail = null;
  48182. currentStencilZPass = null;
  48183. currentStencilClear = null;
  48184. }
  48185. };
  48186. }
  48187. //
  48188. const colorBuffer = new ColorBuffer();
  48189. const depthBuffer = new DepthBuffer();
  48190. const stencilBuffer = new StencilBuffer();
  48191. const uboBindings = new WeakMap();
  48192. const uboProgramMap = new WeakMap();
  48193. let enabledCapabilities = {};
  48194. let currentBoundFramebuffers = {};
  48195. let currentDrawbuffers = new WeakMap();
  48196. let defaultDrawbuffers = [];
  48197. let currentProgram = null;
  48198. let currentBlendingEnabled = false;
  48199. let currentBlending = null;
  48200. let currentBlendEquation = null;
  48201. let currentBlendSrc = null;
  48202. let currentBlendDst = null;
  48203. let currentBlendEquationAlpha = null;
  48204. let currentBlendSrcAlpha = null;
  48205. let currentBlendDstAlpha = null;
  48206. let currentBlendColor = new Color( 0, 0, 0 );
  48207. let currentBlendAlpha = 0;
  48208. let currentPremultipledAlpha = false;
  48209. let currentFlipSided = null;
  48210. let currentCullFace = null;
  48211. let currentLineWidth = null;
  48212. let currentPolygonOffsetFactor = null;
  48213. let currentPolygonOffsetUnits = null;
  48214. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  48215. let lineWidthAvailable = false;
  48216. let version = 0;
  48217. const glVersion = gl.getParameter( gl.VERSION );
  48218. if ( glVersion.indexOf( 'WebGL' ) !== -1 ) {
  48219. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  48220. lineWidthAvailable = ( version >= 1.0 );
  48221. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== -1 ) {
  48222. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  48223. lineWidthAvailable = ( version >= 2.0 );
  48224. }
  48225. let currentTextureSlot = null;
  48226. let currentBoundTextures = {};
  48227. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  48228. const viewportParam = gl.getParameter( gl.VIEWPORT );
  48229. const currentScissor = new Vector4().fromArray( scissorParam );
  48230. const currentViewport = new Vector4().fromArray( viewportParam );
  48231. function createTexture( type, target, count, dimensions ) {
  48232. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  48233. const texture = gl.createTexture();
  48234. gl.bindTexture( type, texture );
  48235. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  48236. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  48237. for ( let i = 0; i < count; i ++ ) {
  48238. if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) {
  48239. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  48240. } else {
  48241. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  48242. }
  48243. }
  48244. return texture;
  48245. }
  48246. const emptyTextures = {};
  48247. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  48248. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  48249. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  48250. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  48251. // init
  48252. colorBuffer.setClear( 0, 0, 0, 1 );
  48253. depthBuffer.setClear( 1 );
  48254. stencilBuffer.setClear( 0 );
  48255. enable( gl.DEPTH_TEST );
  48256. depthBuffer.setFunc( LessEqualDepth );
  48257. setFlipSided( false );
  48258. setCullFace( CullFaceBack );
  48259. enable( gl.CULL_FACE );
  48260. setBlending( NoBlending );
  48261. //
  48262. function enable( id ) {
  48263. if ( enabledCapabilities[ id ] !== true ) {
  48264. gl.enable( id );
  48265. enabledCapabilities[ id ] = true;
  48266. }
  48267. }
  48268. function disable( id ) {
  48269. if ( enabledCapabilities[ id ] !== false ) {
  48270. gl.disable( id );
  48271. enabledCapabilities[ id ] = false;
  48272. }
  48273. }
  48274. function bindFramebuffer( target, framebuffer ) {
  48275. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  48276. gl.bindFramebuffer( target, framebuffer );
  48277. currentBoundFramebuffers[ target ] = framebuffer;
  48278. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  48279. if ( target === gl.DRAW_FRAMEBUFFER ) {
  48280. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  48281. }
  48282. if ( target === gl.FRAMEBUFFER ) {
  48283. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  48284. }
  48285. return true;
  48286. }
  48287. return false;
  48288. }
  48289. function drawBuffers( renderTarget, framebuffer ) {
  48290. let drawBuffers = defaultDrawbuffers;
  48291. let needsUpdate = false;
  48292. if ( renderTarget ) {
  48293. drawBuffers = currentDrawbuffers.get( framebuffer );
  48294. if ( drawBuffers === undefined ) {
  48295. drawBuffers = [];
  48296. currentDrawbuffers.set( framebuffer, drawBuffers );
  48297. }
  48298. const textures = renderTarget.textures;
  48299. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  48300. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  48301. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  48302. }
  48303. drawBuffers.length = textures.length;
  48304. needsUpdate = true;
  48305. }
  48306. } else {
  48307. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  48308. drawBuffers[ 0 ] = gl.BACK;
  48309. needsUpdate = true;
  48310. }
  48311. }
  48312. if ( needsUpdate ) {
  48313. gl.drawBuffers( drawBuffers );
  48314. }
  48315. }
  48316. function useProgram( program ) {
  48317. if ( currentProgram !== program ) {
  48318. gl.useProgram( program );
  48319. currentProgram = program;
  48320. return true;
  48321. }
  48322. return false;
  48323. }
  48324. const equationToGL = {
  48325. [ AddEquation ]: gl.FUNC_ADD,
  48326. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  48327. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  48328. };
  48329. equationToGL[ MinEquation ] = gl.MIN;
  48330. equationToGL[ MaxEquation ] = gl.MAX;
  48331. const factorToGL = {
  48332. [ ZeroFactor ]: gl.ZERO,
  48333. [ OneFactor ]: gl.ONE,
  48334. [ SrcColorFactor ]: gl.SRC_COLOR,
  48335. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  48336. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  48337. [ DstColorFactor ]: gl.DST_COLOR,
  48338. [ DstAlphaFactor ]: gl.DST_ALPHA,
  48339. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  48340. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  48341. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  48342. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  48343. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  48344. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  48345. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  48346. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  48347. };
  48348. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  48349. if ( blending === NoBlending ) {
  48350. if ( currentBlendingEnabled === true ) {
  48351. disable( gl.BLEND );
  48352. currentBlendingEnabled = false;
  48353. }
  48354. return;
  48355. }
  48356. if ( currentBlendingEnabled === false ) {
  48357. enable( gl.BLEND );
  48358. currentBlendingEnabled = true;
  48359. }
  48360. if ( blending !== CustomBlending ) {
  48361. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  48362. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  48363. gl.blendEquation( gl.FUNC_ADD );
  48364. currentBlendEquation = AddEquation;
  48365. currentBlendEquationAlpha = AddEquation;
  48366. }
  48367. if ( premultipliedAlpha ) {
  48368. switch ( blending ) {
  48369. case NormalBlending:
  48370. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  48371. break;
  48372. case AdditiveBlending:
  48373. gl.blendFunc( gl.ONE, gl.ONE );
  48374. break;
  48375. case SubtractiveBlending:
  48376. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  48377. break;
  48378. case MultiplyBlending:
  48379. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  48380. break;
  48381. default:
  48382. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  48383. break;
  48384. }
  48385. } else {
  48386. switch ( blending ) {
  48387. case NormalBlending:
  48388. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  48389. break;
  48390. case AdditiveBlending:
  48391. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  48392. break;
  48393. case SubtractiveBlending:
  48394. console.error( 'THREE.WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  48395. break;
  48396. case MultiplyBlending:
  48397. console.error( 'THREE.WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  48398. break;
  48399. default:
  48400. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  48401. break;
  48402. }
  48403. }
  48404. currentBlendSrc = null;
  48405. currentBlendDst = null;
  48406. currentBlendSrcAlpha = null;
  48407. currentBlendDstAlpha = null;
  48408. currentBlendColor.set( 0, 0, 0 );
  48409. currentBlendAlpha = 0;
  48410. currentBlending = blending;
  48411. currentPremultipledAlpha = premultipliedAlpha;
  48412. }
  48413. return;
  48414. }
  48415. // custom blending
  48416. blendEquationAlpha = blendEquationAlpha || blendEquation;
  48417. blendSrcAlpha = blendSrcAlpha || blendSrc;
  48418. blendDstAlpha = blendDstAlpha || blendDst;
  48419. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  48420. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  48421. currentBlendEquation = blendEquation;
  48422. currentBlendEquationAlpha = blendEquationAlpha;
  48423. }
  48424. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  48425. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  48426. currentBlendSrc = blendSrc;
  48427. currentBlendDst = blendDst;
  48428. currentBlendSrcAlpha = blendSrcAlpha;
  48429. currentBlendDstAlpha = blendDstAlpha;
  48430. }
  48431. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  48432. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  48433. currentBlendColor.copy( blendColor );
  48434. currentBlendAlpha = blendAlpha;
  48435. }
  48436. currentBlending = blending;
  48437. currentPremultipledAlpha = false;
  48438. }
  48439. function setMaterial( material, frontFaceCW ) {
  48440. material.side === DoubleSide
  48441. ? disable( gl.CULL_FACE )
  48442. : enable( gl.CULL_FACE );
  48443. let flipSided = ( material.side === BackSide );
  48444. if ( frontFaceCW ) flipSided = ! flipSided;
  48445. setFlipSided( flipSided );
  48446. ( material.blending === NormalBlending && material.transparent === false )
  48447. ? setBlending( NoBlending )
  48448. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  48449. depthBuffer.setFunc( material.depthFunc );
  48450. depthBuffer.setTest( material.depthTest );
  48451. depthBuffer.setMask( material.depthWrite );
  48452. colorBuffer.setMask( material.colorWrite );
  48453. const stencilWrite = material.stencilWrite;
  48454. stencilBuffer.setTest( stencilWrite );
  48455. if ( stencilWrite ) {
  48456. stencilBuffer.setMask( material.stencilWriteMask );
  48457. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  48458. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  48459. }
  48460. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  48461. material.alphaToCoverage === true
  48462. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  48463. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  48464. }
  48465. //
  48466. function setFlipSided( flipSided ) {
  48467. if ( currentFlipSided !== flipSided ) {
  48468. if ( flipSided ) {
  48469. gl.frontFace( gl.CW );
  48470. } else {
  48471. gl.frontFace( gl.CCW );
  48472. }
  48473. currentFlipSided = flipSided;
  48474. }
  48475. }
  48476. function setCullFace( cullFace ) {
  48477. if ( cullFace !== CullFaceNone ) {
  48478. enable( gl.CULL_FACE );
  48479. if ( cullFace !== currentCullFace ) {
  48480. if ( cullFace === CullFaceBack ) {
  48481. gl.cullFace( gl.BACK );
  48482. } else if ( cullFace === CullFaceFront ) {
  48483. gl.cullFace( gl.FRONT );
  48484. } else {
  48485. gl.cullFace( gl.FRONT_AND_BACK );
  48486. }
  48487. }
  48488. } else {
  48489. disable( gl.CULL_FACE );
  48490. }
  48491. currentCullFace = cullFace;
  48492. }
  48493. function setLineWidth( width ) {
  48494. if ( width !== currentLineWidth ) {
  48495. if ( lineWidthAvailable ) gl.lineWidth( width );
  48496. currentLineWidth = width;
  48497. }
  48498. }
  48499. function setPolygonOffset( polygonOffset, factor, units ) {
  48500. if ( polygonOffset ) {
  48501. enable( gl.POLYGON_OFFSET_FILL );
  48502. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  48503. gl.polygonOffset( factor, units );
  48504. currentPolygonOffsetFactor = factor;
  48505. currentPolygonOffsetUnits = units;
  48506. }
  48507. } else {
  48508. disable( gl.POLYGON_OFFSET_FILL );
  48509. }
  48510. }
  48511. function setScissorTest( scissorTest ) {
  48512. if ( scissorTest ) {
  48513. enable( gl.SCISSOR_TEST );
  48514. } else {
  48515. disable( gl.SCISSOR_TEST );
  48516. }
  48517. }
  48518. // texture
  48519. function activeTexture( webglSlot ) {
  48520. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  48521. if ( currentTextureSlot !== webglSlot ) {
  48522. gl.activeTexture( webglSlot );
  48523. currentTextureSlot = webglSlot;
  48524. }
  48525. }
  48526. function bindTexture( webglType, webglTexture, webglSlot ) {
  48527. if ( webglSlot === undefined ) {
  48528. if ( currentTextureSlot === null ) {
  48529. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  48530. } else {
  48531. webglSlot = currentTextureSlot;
  48532. }
  48533. }
  48534. let boundTexture = currentBoundTextures[ webglSlot ];
  48535. if ( boundTexture === undefined ) {
  48536. boundTexture = { type: undefined, texture: undefined };
  48537. currentBoundTextures[ webglSlot ] = boundTexture;
  48538. }
  48539. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  48540. if ( currentTextureSlot !== webglSlot ) {
  48541. gl.activeTexture( webglSlot );
  48542. currentTextureSlot = webglSlot;
  48543. }
  48544. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  48545. boundTexture.type = webglType;
  48546. boundTexture.texture = webglTexture;
  48547. }
  48548. }
  48549. function unbindTexture() {
  48550. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  48551. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  48552. gl.bindTexture( boundTexture.type, null );
  48553. boundTexture.type = undefined;
  48554. boundTexture.texture = undefined;
  48555. }
  48556. }
  48557. function compressedTexImage2D() {
  48558. try {
  48559. gl.compressedTexImage2D( ...arguments );
  48560. } catch ( error ) {
  48561. console.error( 'THREE.WebGLState:', error );
  48562. }
  48563. }
  48564. function compressedTexImage3D() {
  48565. try {
  48566. gl.compressedTexImage3D( ...arguments );
  48567. } catch ( error ) {
  48568. console.error( 'THREE.WebGLState:', error );
  48569. }
  48570. }
  48571. function texSubImage2D() {
  48572. try {
  48573. gl.texSubImage2D( ...arguments );
  48574. } catch ( error ) {
  48575. console.error( 'THREE.WebGLState:', error );
  48576. }
  48577. }
  48578. function texSubImage3D() {
  48579. try {
  48580. gl.texSubImage3D( ...arguments );
  48581. } catch ( error ) {
  48582. console.error( 'THREE.WebGLState:', error );
  48583. }
  48584. }
  48585. function compressedTexSubImage2D() {
  48586. try {
  48587. gl.compressedTexSubImage2D( ...arguments );
  48588. } catch ( error ) {
  48589. console.error( 'THREE.WebGLState:', error );
  48590. }
  48591. }
  48592. function compressedTexSubImage3D() {
  48593. try {
  48594. gl.compressedTexSubImage3D( ...arguments );
  48595. } catch ( error ) {
  48596. console.error( 'THREE.WebGLState:', error );
  48597. }
  48598. }
  48599. function texStorage2D() {
  48600. try {
  48601. gl.texStorage2D( ...arguments );
  48602. } catch ( error ) {
  48603. console.error( 'THREE.WebGLState:', error );
  48604. }
  48605. }
  48606. function texStorage3D() {
  48607. try {
  48608. gl.texStorage3D( ...arguments );
  48609. } catch ( error ) {
  48610. console.error( 'THREE.WebGLState:', error );
  48611. }
  48612. }
  48613. function texImage2D() {
  48614. try {
  48615. gl.texImage2D( ...arguments );
  48616. } catch ( error ) {
  48617. console.error( 'THREE.WebGLState:', error );
  48618. }
  48619. }
  48620. function texImage3D() {
  48621. try {
  48622. gl.texImage3D( ...arguments );
  48623. } catch ( error ) {
  48624. console.error( 'THREE.WebGLState:', error );
  48625. }
  48626. }
  48627. //
  48628. function scissor( scissor ) {
  48629. if ( currentScissor.equals( scissor ) === false ) {
  48630. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  48631. currentScissor.copy( scissor );
  48632. }
  48633. }
  48634. function viewport( viewport ) {
  48635. if ( currentViewport.equals( viewport ) === false ) {
  48636. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  48637. currentViewport.copy( viewport );
  48638. }
  48639. }
  48640. function updateUBOMapping( uniformsGroup, program ) {
  48641. let mapping = uboProgramMap.get( program );
  48642. if ( mapping === undefined ) {
  48643. mapping = new WeakMap();
  48644. uboProgramMap.set( program, mapping );
  48645. }
  48646. let blockIndex = mapping.get( uniformsGroup );
  48647. if ( blockIndex === undefined ) {
  48648. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  48649. mapping.set( uniformsGroup, blockIndex );
  48650. }
  48651. }
  48652. function uniformBlockBinding( uniformsGroup, program ) {
  48653. const mapping = uboProgramMap.get( program );
  48654. const blockIndex = mapping.get( uniformsGroup );
  48655. if ( uboBindings.get( program ) !== blockIndex ) {
  48656. // bind shader specific block index to global block point
  48657. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  48658. uboBindings.set( program, blockIndex );
  48659. }
  48660. }
  48661. //
  48662. function reset() {
  48663. // reset state
  48664. gl.disable( gl.BLEND );
  48665. gl.disable( gl.CULL_FACE );
  48666. gl.disable( gl.DEPTH_TEST );
  48667. gl.disable( gl.POLYGON_OFFSET_FILL );
  48668. gl.disable( gl.SCISSOR_TEST );
  48669. gl.disable( gl.STENCIL_TEST );
  48670. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  48671. gl.blendEquation( gl.FUNC_ADD );
  48672. gl.blendFunc( gl.ONE, gl.ZERO );
  48673. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  48674. gl.blendColor( 0, 0, 0, 0 );
  48675. gl.colorMask( true, true, true, true );
  48676. gl.clearColor( 0, 0, 0, 0 );
  48677. gl.depthMask( true );
  48678. gl.depthFunc( gl.LESS );
  48679. depthBuffer.setReversed( false );
  48680. gl.clearDepth( 1 );
  48681. gl.stencilMask( 0xffffffff );
  48682. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  48683. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  48684. gl.clearStencil( 0 );
  48685. gl.cullFace( gl.BACK );
  48686. gl.frontFace( gl.CCW );
  48687. gl.polygonOffset( 0, 0 );
  48688. gl.activeTexture( gl.TEXTURE0 );
  48689. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  48690. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  48691. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  48692. gl.useProgram( null );
  48693. gl.lineWidth( 1 );
  48694. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  48695. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  48696. // reset internals
  48697. enabledCapabilities = {};
  48698. currentTextureSlot = null;
  48699. currentBoundTextures = {};
  48700. currentBoundFramebuffers = {};
  48701. currentDrawbuffers = new WeakMap();
  48702. defaultDrawbuffers = [];
  48703. currentProgram = null;
  48704. currentBlendingEnabled = false;
  48705. currentBlending = null;
  48706. currentBlendEquation = null;
  48707. currentBlendSrc = null;
  48708. currentBlendDst = null;
  48709. currentBlendEquationAlpha = null;
  48710. currentBlendSrcAlpha = null;
  48711. currentBlendDstAlpha = null;
  48712. currentBlendColor = new Color( 0, 0, 0 );
  48713. currentBlendAlpha = 0;
  48714. currentPremultipledAlpha = false;
  48715. currentFlipSided = null;
  48716. currentCullFace = null;
  48717. currentLineWidth = null;
  48718. currentPolygonOffsetFactor = null;
  48719. currentPolygonOffsetUnits = null;
  48720. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  48721. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  48722. colorBuffer.reset();
  48723. depthBuffer.reset();
  48724. stencilBuffer.reset();
  48725. }
  48726. return {
  48727. buffers: {
  48728. color: colorBuffer,
  48729. depth: depthBuffer,
  48730. stencil: stencilBuffer
  48731. },
  48732. enable: enable,
  48733. disable: disable,
  48734. bindFramebuffer: bindFramebuffer,
  48735. drawBuffers: drawBuffers,
  48736. useProgram: useProgram,
  48737. setBlending: setBlending,
  48738. setMaterial: setMaterial,
  48739. setFlipSided: setFlipSided,
  48740. setCullFace: setCullFace,
  48741. setLineWidth: setLineWidth,
  48742. setPolygonOffset: setPolygonOffset,
  48743. setScissorTest: setScissorTest,
  48744. activeTexture: activeTexture,
  48745. bindTexture: bindTexture,
  48746. unbindTexture: unbindTexture,
  48747. compressedTexImage2D: compressedTexImage2D,
  48748. compressedTexImage3D: compressedTexImage3D,
  48749. texImage2D: texImage2D,
  48750. texImage3D: texImage3D,
  48751. updateUBOMapping: updateUBOMapping,
  48752. uniformBlockBinding: uniformBlockBinding,
  48753. texStorage2D: texStorage2D,
  48754. texStorage3D: texStorage3D,
  48755. texSubImage2D: texSubImage2D,
  48756. texSubImage3D: texSubImage3D,
  48757. compressedTexSubImage2D: compressedTexSubImage2D,
  48758. compressedTexSubImage3D: compressedTexSubImage3D,
  48759. scissor: scissor,
  48760. viewport: viewport,
  48761. reset: reset
  48762. };
  48763. }
  48764. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  48765. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  48766. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  48767. const _imageDimensions = new Vector2();
  48768. const _videoTextures = new WeakMap();
  48769. let _canvas;
  48770. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  48771. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  48772. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  48773. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  48774. let useOffscreenCanvas = false;
  48775. try {
  48776. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  48777. // eslint-disable-next-line compat/compat
  48778. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  48779. } catch ( err ) {
  48780. // Ignore any errors
  48781. }
  48782. function createCanvas( width, height ) {
  48783. // Use OffscreenCanvas when available. Specially needed in web workers
  48784. return useOffscreenCanvas ?
  48785. // eslint-disable-next-line compat/compat
  48786. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  48787. }
  48788. function resizeImage( image, needsNewCanvas, maxSize ) {
  48789. let scale = 1;
  48790. const dimensions = getDimensions( image );
  48791. // handle case if texture exceeds max size
  48792. if ( dimensions.width > maxSize || dimensions.height > maxSize ) {
  48793. scale = maxSize / Math.max( dimensions.width, dimensions.height );
  48794. }
  48795. // only perform resize if necessary
  48796. if ( scale < 1 ) {
  48797. // only perform resize for certain image types
  48798. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  48799. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  48800. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  48801. ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) {
  48802. const width = Math.floor( scale * dimensions.width );
  48803. const height = Math.floor( scale * dimensions.height );
  48804. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  48805. // cube textures can't reuse the same canvas
  48806. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  48807. canvas.width = width;
  48808. canvas.height = height;
  48809. const context = canvas.getContext( '2d' );
  48810. context.drawImage( image, 0, 0, width, height );
  48811. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' );
  48812. return canvas;
  48813. } else {
  48814. if ( 'data' in image ) {
  48815. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' );
  48816. }
  48817. return image;
  48818. }
  48819. }
  48820. return image;
  48821. }
  48822. function textureNeedsGenerateMipmaps( texture ) {
  48823. return texture.generateMipmaps;
  48824. }
  48825. function generateMipmap( target ) {
  48826. _gl.generateMipmap( target );
  48827. }
  48828. function getTargetType( texture ) {
  48829. if ( texture.isWebGLCubeRenderTarget ) return _gl.TEXTURE_CUBE_MAP;
  48830. if ( texture.isWebGL3DRenderTarget ) return _gl.TEXTURE_3D;
  48831. if ( texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture ) return _gl.TEXTURE_2D_ARRAY;
  48832. return _gl.TEXTURE_2D;
  48833. }
  48834. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  48835. if ( internalFormatName !== null ) {
  48836. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  48837. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  48838. }
  48839. let internalFormat = glFormat;
  48840. if ( glFormat === _gl.RED ) {
  48841. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  48842. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  48843. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  48844. }
  48845. if ( glFormat === _gl.RED_INTEGER ) {
  48846. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  48847. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  48848. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  48849. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  48850. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  48851. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  48852. }
  48853. if ( glFormat === _gl.RG ) {
  48854. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  48855. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  48856. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  48857. }
  48858. if ( glFormat === _gl.RG_INTEGER ) {
  48859. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI;
  48860. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI;
  48861. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI;
  48862. if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I;
  48863. if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I;
  48864. if ( glType === _gl.INT ) internalFormat = _gl.RG32I;
  48865. }
  48866. if ( glFormat === _gl.RGB_INTEGER ) {
  48867. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGB8UI;
  48868. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGB16UI;
  48869. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGB32UI;
  48870. if ( glType === _gl.BYTE ) internalFormat = _gl.RGB8I;
  48871. if ( glType === _gl.SHORT ) internalFormat = _gl.RGB16I;
  48872. if ( glType === _gl.INT ) internalFormat = _gl.RGB32I;
  48873. }
  48874. if ( glFormat === _gl.RGBA_INTEGER ) {
  48875. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGBA8UI;
  48876. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGBA16UI;
  48877. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGBA32UI;
  48878. if ( glType === _gl.BYTE ) internalFormat = _gl.RGBA8I;
  48879. if ( glType === _gl.SHORT ) internalFormat = _gl.RGBA16I;
  48880. if ( glType === _gl.INT ) internalFormat = _gl.RGBA32I;
  48881. }
  48882. if ( glFormat === _gl.RGB ) {
  48883. if ( glType === _gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = _gl.RGB9_E5;
  48884. }
  48885. if ( glFormat === _gl.RGBA ) {
  48886. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  48887. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  48888. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  48889. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  48890. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  48891. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  48892. }
  48893. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  48894. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  48895. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  48896. extensions.get( 'EXT_color_buffer_float' );
  48897. }
  48898. return internalFormat;
  48899. }
  48900. function getInternalDepthFormat( useStencil, depthType ) {
  48901. let glInternalFormat;
  48902. if ( useStencil ) {
  48903. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  48904. glInternalFormat = _gl.DEPTH24_STENCIL8;
  48905. } else if ( depthType === FloatType ) {
  48906. glInternalFormat = _gl.DEPTH32F_STENCIL8;
  48907. } else if ( depthType === UnsignedShortType ) {
  48908. glInternalFormat = _gl.DEPTH24_STENCIL8;
  48909. console.warn( 'DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.' );
  48910. }
  48911. } else {
  48912. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  48913. glInternalFormat = _gl.DEPTH_COMPONENT24;
  48914. } else if ( depthType === FloatType ) {
  48915. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  48916. } else if ( depthType === UnsignedShortType ) {
  48917. glInternalFormat = _gl.DEPTH_COMPONENT16;
  48918. }
  48919. }
  48920. return glInternalFormat;
  48921. }
  48922. function getMipLevels( texture, image ) {
  48923. if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  48924. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  48925. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  48926. // user-defined mipmaps
  48927. return texture.mipmaps.length;
  48928. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  48929. return image.mipmaps.length;
  48930. } else {
  48931. // texture without mipmaps (only base level)
  48932. return 1;
  48933. }
  48934. }
  48935. //
  48936. function onTextureDispose( event ) {
  48937. const texture = event.target;
  48938. texture.removeEventListener( 'dispose', onTextureDispose );
  48939. deallocateTexture( texture );
  48940. if ( texture.isVideoTexture ) {
  48941. _videoTextures.delete( texture );
  48942. }
  48943. }
  48944. function onRenderTargetDispose( event ) {
  48945. const renderTarget = event.target;
  48946. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  48947. deallocateRenderTarget( renderTarget );
  48948. }
  48949. //
  48950. function deallocateTexture( texture ) {
  48951. const textureProperties = properties.get( texture );
  48952. if ( textureProperties.__webglInit === undefined ) return;
  48953. // check if it's necessary to remove the WebGLTexture object
  48954. const source = texture.source;
  48955. const webglTextures = _sources.get( source );
  48956. if ( webglTextures ) {
  48957. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  48958. webglTexture.usedTimes --;
  48959. // the WebGLTexture object is not used anymore, remove it
  48960. if ( webglTexture.usedTimes === 0 ) {
  48961. deleteTexture( texture );
  48962. }
  48963. // remove the weak map entry if no WebGLTexture uses the source anymore
  48964. if ( Object.keys( webglTextures ).length === 0 ) {
  48965. _sources.delete( source );
  48966. }
  48967. }
  48968. properties.remove( texture );
  48969. }
  48970. function deleteTexture( texture ) {
  48971. const textureProperties = properties.get( texture );
  48972. _gl.deleteTexture( textureProperties.__webglTexture );
  48973. const source = texture.source;
  48974. const webglTextures = _sources.get( source );
  48975. delete webglTextures[ textureProperties.__cacheKey ];
  48976. info.memory.textures --;
  48977. }
  48978. function deallocateRenderTarget( renderTarget ) {
  48979. const renderTargetProperties = properties.get( renderTarget );
  48980. if ( renderTarget.depthTexture ) {
  48981. renderTarget.depthTexture.dispose();
  48982. properties.remove( renderTarget.depthTexture );
  48983. }
  48984. if ( renderTarget.isWebGLCubeRenderTarget ) {
  48985. for ( let i = 0; i < 6; i ++ ) {
  48986. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  48987. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  48988. } else {
  48989. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  48990. }
  48991. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  48992. }
  48993. } else {
  48994. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  48995. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  48996. } else {
  48997. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  48998. }
  48999. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  49000. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  49001. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  49002. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  49003. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  49004. }
  49005. }
  49006. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  49007. }
  49008. const textures = renderTarget.textures;
  49009. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49010. const attachmentProperties = properties.get( textures[ i ] );
  49011. if ( attachmentProperties.__webglTexture ) {
  49012. _gl.deleteTexture( attachmentProperties.__webglTexture );
  49013. info.memory.textures --;
  49014. }
  49015. properties.remove( textures[ i ] );
  49016. }
  49017. properties.remove( renderTarget );
  49018. }
  49019. //
  49020. let textureUnits = 0;
  49021. function resetTextureUnits() {
  49022. textureUnits = 0;
  49023. }
  49024. function allocateTextureUnit() {
  49025. const textureUnit = textureUnits;
  49026. if ( textureUnit >= capabilities.maxTextures ) {
  49027. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  49028. }
  49029. textureUnits += 1;
  49030. return textureUnit;
  49031. }
  49032. function getTextureCacheKey( texture ) {
  49033. const array = [];
  49034. array.push( texture.wrapS );
  49035. array.push( texture.wrapT );
  49036. array.push( texture.wrapR || 0 );
  49037. array.push( texture.magFilter );
  49038. array.push( texture.minFilter );
  49039. array.push( texture.anisotropy );
  49040. array.push( texture.internalFormat );
  49041. array.push( texture.format );
  49042. array.push( texture.type );
  49043. array.push( texture.generateMipmaps );
  49044. array.push( texture.premultiplyAlpha );
  49045. array.push( texture.flipY );
  49046. array.push( texture.unpackAlignment );
  49047. array.push( texture.colorSpace );
  49048. return array.join();
  49049. }
  49050. //
  49051. function setTexture2D( texture, slot ) {
  49052. const textureProperties = properties.get( texture );
  49053. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  49054. if ( texture.isRenderTargetTexture === false && texture.isExternalTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49055. const image = texture.image;
  49056. if ( image === null ) {
  49057. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  49058. } else if ( image.complete === false ) {
  49059. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  49060. } else {
  49061. uploadTexture( textureProperties, texture, slot );
  49062. return;
  49063. }
  49064. } else if ( texture.isExternalTexture ) {
  49065. textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null;
  49066. }
  49067. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49068. }
  49069. function setTexture2DArray( texture, slot ) {
  49070. const textureProperties = properties.get( texture );
  49071. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49072. uploadTexture( textureProperties, texture, slot );
  49073. return;
  49074. }
  49075. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49076. }
  49077. function setTexture3D( texture, slot ) {
  49078. const textureProperties = properties.get( texture );
  49079. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49080. uploadTexture( textureProperties, texture, slot );
  49081. return;
  49082. }
  49083. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49084. }
  49085. function setTextureCube( texture, slot ) {
  49086. const textureProperties = properties.get( texture );
  49087. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  49088. uploadCubeTexture( textureProperties, texture, slot );
  49089. return;
  49090. }
  49091. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49092. }
  49093. const wrappingToGL = {
  49094. [ RepeatWrapping ]: _gl.REPEAT,
  49095. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  49096. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  49097. };
  49098. const filterToGL = {
  49099. [ NearestFilter ]: _gl.NEAREST,
  49100. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  49101. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  49102. [ LinearFilter ]: _gl.LINEAR,
  49103. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  49104. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  49105. };
  49106. const compareToGL = {
  49107. [ NeverCompare ]: _gl.NEVER,
  49108. [ AlwaysCompare ]: _gl.ALWAYS,
  49109. [ LessCompare ]: _gl.LESS,
  49110. [ LessEqualCompare ]: _gl.LEQUAL,
  49111. [ EqualCompare ]: _gl.EQUAL,
  49112. [ GreaterEqualCompare ]: _gl.GEQUAL,
  49113. [ GreaterCompare ]: _gl.GREATER,
  49114. [ NotEqualCompare ]: _gl.NOTEQUAL
  49115. };
  49116. function setTextureParameters( textureType, texture ) {
  49117. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false &&
  49118. ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  49119. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) {
  49120. console.warn( 'THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' );
  49121. }
  49122. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  49123. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  49124. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  49125. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  49126. }
  49127. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  49128. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  49129. if ( texture.compareFunction ) {
  49130. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  49131. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  49132. }
  49133. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  49134. if ( texture.magFilter === NearestFilter ) return;
  49135. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  49136. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension
  49137. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  49138. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  49139. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  49140. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  49141. }
  49142. }
  49143. }
  49144. function initTexture( textureProperties, texture ) {
  49145. let forceUpload = false;
  49146. if ( textureProperties.__webglInit === undefined ) {
  49147. textureProperties.__webglInit = true;
  49148. texture.addEventListener( 'dispose', onTextureDispose );
  49149. }
  49150. // create Source <-> WebGLTextures mapping if necessary
  49151. const source = texture.source;
  49152. let webglTextures = _sources.get( source );
  49153. if ( webglTextures === undefined ) {
  49154. webglTextures = {};
  49155. _sources.set( source, webglTextures );
  49156. }
  49157. // check if there is already a WebGLTexture object for the given texture parameters
  49158. const textureCacheKey = getTextureCacheKey( texture );
  49159. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  49160. // if not, create a new instance of WebGLTexture
  49161. if ( webglTextures[ textureCacheKey ] === undefined ) {
  49162. // create new entry
  49163. webglTextures[ textureCacheKey ] = {
  49164. texture: _gl.createTexture(),
  49165. usedTimes: 0
  49166. };
  49167. info.memory.textures ++;
  49168. // when a new instance of WebGLTexture was created, a texture upload is required
  49169. // even if the image contents are identical
  49170. forceUpload = true;
  49171. }
  49172. webglTextures[ textureCacheKey ].usedTimes ++;
  49173. // every time the texture cache key changes, it's necessary to check if an instance of
  49174. // WebGLTexture can be deleted in order to avoid a memory leak.
  49175. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  49176. if ( webglTexture !== undefined ) {
  49177. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  49178. if ( webglTexture.usedTimes === 0 ) {
  49179. deleteTexture( texture );
  49180. }
  49181. }
  49182. // store references to cache key and WebGLTexture object
  49183. textureProperties.__cacheKey = textureCacheKey;
  49184. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  49185. }
  49186. return forceUpload;
  49187. }
  49188. function getRow( index, rowLength, componentStride ) {
  49189. return Math.floor( Math.floor( index / componentStride ) / rowLength );
  49190. }
  49191. function updateTexture( texture, image, glFormat, glType ) {
  49192. const componentStride = 4; // only RGBA supported
  49193. const updateRanges = texture.updateRanges;
  49194. if ( updateRanges.length === 0 ) {
  49195. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  49196. } else {
  49197. // Before applying update ranges, we merge any adjacent / overlapping
  49198. // ranges to reduce load on `gl.texSubImage2D`. Empirically, this has led
  49199. // to performance improvements for applications which make heavy use of
  49200. // update ranges. Likely due to GPU command overhead.
  49201. //
  49202. // Note that to reduce garbage collection between frames, we merge the
  49203. // update ranges in-place. This is safe because this method will clear the
  49204. // update ranges once updated.
  49205. updateRanges.sort( ( a, b ) => a.start - b.start );
  49206. // To merge the update ranges in-place, we work from left to right in the
  49207. // existing updateRanges array, merging ranges. This may result in a final
  49208. // array which is smaller than the original. This index tracks the last
  49209. // index representing a merged range, any data after this index can be
  49210. // trimmed once the merge algorithm is completed.
  49211. let mergeIndex = 0;
  49212. for ( let i = 1; i < updateRanges.length; i ++ ) {
  49213. const previousRange = updateRanges[ mergeIndex ];
  49214. const range = updateRanges[ i ];
  49215. // Only merge if in the same row and overlapping/adjacent
  49216. const previousEnd = previousRange.start + previousRange.count;
  49217. const currentRow = getRow( range.start, image.width, componentStride );
  49218. const previousRow = getRow( previousRange.start, image.width, componentStride );
  49219. // We add one here to merge adjacent ranges. This is safe because ranges
  49220. // operate over positive integers.
  49221. if (
  49222. range.start <= previousEnd + 1 &&
  49223. currentRow === previousRow &&
  49224. getRow( range.start + range.count - 1, image.width, componentStride ) === currentRow // ensure range doesn't spill
  49225. ) {
  49226. previousRange.count = Math.max(
  49227. previousRange.count,
  49228. range.start + range.count - previousRange.start
  49229. );
  49230. } else {
  49231. ++ mergeIndex;
  49232. updateRanges[ mergeIndex ] = range;
  49233. }
  49234. }
  49235. // Trim the array to only contain the merged ranges.
  49236. updateRanges.length = mergeIndex + 1;
  49237. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  49238. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  49239. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  49240. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  49241. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  49242. const range = updateRanges[ i ];
  49243. const pixelStart = Math.floor( range.start / componentStride );
  49244. const pixelCount = Math.ceil( range.count / componentStride );
  49245. const x = pixelStart % image.width;
  49246. const y = Math.floor( pixelStart / image.width );
  49247. // Assumes update ranges refer to contiguous memory
  49248. const width = pixelCount;
  49249. const height = 1;
  49250. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, x );
  49251. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, y );
  49252. state.texSubImage2D( _gl.TEXTURE_2D, 0, x, y, width, height, glFormat, glType, image.data );
  49253. }
  49254. texture.clearUpdateRanges();
  49255. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  49256. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  49257. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  49258. }
  49259. }
  49260. function uploadTexture( textureProperties, texture, slot ) {
  49261. let textureType = _gl.TEXTURE_2D;
  49262. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  49263. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  49264. const forceUpload = initTexture( textureProperties, texture );
  49265. const source = texture.source;
  49266. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49267. const sourceProperties = properties.get( source );
  49268. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  49269. state.activeTexture( _gl.TEXTURE0 + slot );
  49270. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  49271. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  49272. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  49273. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  49274. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  49275. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  49276. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  49277. let image = resizeImage( texture.image, false, capabilities.maxTextureSize );
  49278. image = verifyColorSpace( texture, image );
  49279. const glFormat = utils.convert( texture.format, texture.colorSpace );
  49280. const glType = utils.convert( texture.type );
  49281. let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  49282. setTextureParameters( textureType, texture );
  49283. let mipmap;
  49284. const mipmaps = texture.mipmaps;
  49285. const useTexStorage = ( texture.isVideoTexture !== true );
  49286. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  49287. const dataReady = source.dataReady;
  49288. const levels = getMipLevels( texture, image );
  49289. if ( texture.isDepthTexture ) {
  49290. glInternalFormat = getInternalDepthFormat( texture.format === DepthStencilFormat, texture.type );
  49291. //
  49292. if ( allocateMemory ) {
  49293. if ( useTexStorage ) {
  49294. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  49295. } else {
  49296. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  49297. }
  49298. }
  49299. } else if ( texture.isDataTexture ) {
  49300. // use manually created mipmaps if available
  49301. // if there are no manual mipmaps
  49302. // set 0 level mipmap and then use GL to generate other mipmap levels
  49303. if ( mipmaps.length > 0 ) {
  49304. if ( useTexStorage && allocateMemory ) {
  49305. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  49306. }
  49307. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49308. mipmap = mipmaps[ i ];
  49309. if ( useTexStorage ) {
  49310. if ( dataReady ) {
  49311. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  49312. }
  49313. } else {
  49314. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  49315. }
  49316. }
  49317. texture.generateMipmaps = false;
  49318. } else {
  49319. if ( useTexStorage ) {
  49320. if ( allocateMemory ) {
  49321. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  49322. }
  49323. if ( dataReady ) {
  49324. updateTexture( texture, image, glFormat, glType );
  49325. }
  49326. } else {
  49327. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  49328. }
  49329. }
  49330. } else if ( texture.isCompressedTexture ) {
  49331. if ( texture.isCompressedArrayTexture ) {
  49332. if ( useTexStorage && allocateMemory ) {
  49333. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  49334. }
  49335. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49336. mipmap = mipmaps[ i ];
  49337. if ( texture.format !== RGBAFormat ) {
  49338. if ( glFormat !== null ) {
  49339. if ( useTexStorage ) {
  49340. if ( dataReady ) {
  49341. if ( texture.layerUpdates.size > 0 ) {
  49342. const layerByteLength = getByteLength( mipmap.width, mipmap.height, texture.format, texture.type );
  49343. for ( const layerIndex of texture.layerUpdates ) {
  49344. const layerData = mipmap.data.subarray(
  49345. layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT,
  49346. ( layerIndex + 1 ) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT
  49347. );
  49348. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData );
  49349. }
  49350. texture.clearLayerUpdates();
  49351. } else {
  49352. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  49353. }
  49354. }
  49355. } else {
  49356. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  49357. }
  49358. } else {
  49359. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  49360. }
  49361. } else {
  49362. if ( useTexStorage ) {
  49363. if ( dataReady ) {
  49364. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  49365. }
  49366. } else {
  49367. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  49368. }
  49369. }
  49370. }
  49371. } else {
  49372. if ( useTexStorage && allocateMemory ) {
  49373. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  49374. }
  49375. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49376. mipmap = mipmaps[ i ];
  49377. if ( texture.format !== RGBAFormat ) {
  49378. if ( glFormat !== null ) {
  49379. if ( useTexStorage ) {
  49380. if ( dataReady ) {
  49381. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  49382. }
  49383. } else {
  49384. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  49385. }
  49386. } else {
  49387. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  49388. }
  49389. } else {
  49390. if ( useTexStorage ) {
  49391. if ( dataReady ) {
  49392. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  49393. }
  49394. } else {
  49395. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  49396. }
  49397. }
  49398. }
  49399. }
  49400. } else if ( texture.isDataArrayTexture ) {
  49401. if ( useTexStorage ) {
  49402. if ( allocateMemory ) {
  49403. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  49404. }
  49405. if ( dataReady ) {
  49406. if ( texture.layerUpdates.size > 0 ) {
  49407. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  49408. for ( const layerIndex of texture.layerUpdates ) {
  49409. const layerData = image.data.subarray(
  49410. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  49411. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  49412. );
  49413. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  49414. }
  49415. texture.clearLayerUpdates();
  49416. } else {
  49417. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  49418. }
  49419. }
  49420. } else {
  49421. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  49422. }
  49423. } else if ( texture.isData3DTexture ) {
  49424. if ( useTexStorage ) {
  49425. if ( allocateMemory ) {
  49426. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  49427. }
  49428. if ( dataReady ) {
  49429. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  49430. }
  49431. } else {
  49432. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  49433. }
  49434. } else if ( texture.isFramebufferTexture ) {
  49435. if ( allocateMemory ) {
  49436. if ( useTexStorage ) {
  49437. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  49438. } else {
  49439. let width = image.width, height = image.height;
  49440. for ( let i = 0; i < levels; i ++ ) {
  49441. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  49442. width >>= 1;
  49443. height >>= 1;
  49444. }
  49445. }
  49446. }
  49447. } else {
  49448. // regular Texture (image, video, canvas)
  49449. // use manually created mipmaps if available
  49450. // if there are no manual mipmaps
  49451. // set 0 level mipmap and then use GL to generate other mipmap levels
  49452. if ( mipmaps.length > 0 ) {
  49453. if ( useTexStorage && allocateMemory ) {
  49454. const dimensions = getDimensions( mipmaps[ 0 ] );
  49455. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  49456. }
  49457. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49458. mipmap = mipmaps[ i ];
  49459. if ( useTexStorage ) {
  49460. if ( dataReady ) {
  49461. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  49462. }
  49463. } else {
  49464. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  49465. }
  49466. }
  49467. texture.generateMipmaps = false;
  49468. } else {
  49469. if ( useTexStorage ) {
  49470. if ( allocateMemory ) {
  49471. const dimensions = getDimensions( image );
  49472. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  49473. }
  49474. if ( dataReady ) {
  49475. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  49476. }
  49477. } else {
  49478. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  49479. }
  49480. }
  49481. }
  49482. if ( textureNeedsGenerateMipmaps( texture ) ) {
  49483. generateMipmap( textureType );
  49484. }
  49485. sourceProperties.__version = source.version;
  49486. if ( texture.onUpdate ) texture.onUpdate( texture );
  49487. }
  49488. textureProperties.__version = texture.version;
  49489. }
  49490. function uploadCubeTexture( textureProperties, texture, slot ) {
  49491. if ( texture.image.length !== 6 ) return;
  49492. const forceUpload = initTexture( textureProperties, texture );
  49493. const source = texture.source;
  49494. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49495. const sourceProperties = properties.get( source );
  49496. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  49497. state.activeTexture( _gl.TEXTURE0 + slot );
  49498. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  49499. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  49500. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  49501. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  49502. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  49503. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  49504. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  49505. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  49506. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  49507. const cubeImage = [];
  49508. for ( let i = 0; i < 6; i ++ ) {
  49509. if ( ! isCompressed && ! isDataTexture ) {
  49510. cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize );
  49511. } else {
  49512. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  49513. }
  49514. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  49515. }
  49516. const image = cubeImage[ 0 ],
  49517. glFormat = utils.convert( texture.format, texture.colorSpace ),
  49518. glType = utils.convert( texture.type ),
  49519. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  49520. const useTexStorage = ( texture.isVideoTexture !== true );
  49521. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  49522. const dataReady = source.dataReady;
  49523. let levels = getMipLevels( texture, image );
  49524. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  49525. let mipmaps;
  49526. if ( isCompressed ) {
  49527. if ( useTexStorage && allocateMemory ) {
  49528. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  49529. }
  49530. for ( let i = 0; i < 6; i ++ ) {
  49531. mipmaps = cubeImage[ i ].mipmaps;
  49532. for ( let j = 0; j < mipmaps.length; j ++ ) {
  49533. const mipmap = mipmaps[ j ];
  49534. if ( texture.format !== RGBAFormat ) {
  49535. if ( glFormat !== null ) {
  49536. if ( useTexStorage ) {
  49537. if ( dataReady ) {
  49538. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  49539. }
  49540. } else {
  49541. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  49542. }
  49543. } else {
  49544. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  49545. }
  49546. } else {
  49547. if ( useTexStorage ) {
  49548. if ( dataReady ) {
  49549. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  49550. }
  49551. } else {
  49552. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  49553. }
  49554. }
  49555. }
  49556. }
  49557. } else {
  49558. mipmaps = texture.mipmaps;
  49559. if ( useTexStorage && allocateMemory ) {
  49560. // TODO: Uniformly handle mipmap definitions
  49561. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  49562. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  49563. if ( mipmaps.length > 0 ) levels ++;
  49564. const dimensions = getDimensions( cubeImage[ 0 ] );
  49565. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height );
  49566. }
  49567. for ( let i = 0; i < 6; i ++ ) {
  49568. if ( isDataTexture ) {
  49569. if ( useTexStorage ) {
  49570. if ( dataReady ) {
  49571. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  49572. }
  49573. } else {
  49574. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  49575. }
  49576. for ( let j = 0; j < mipmaps.length; j ++ ) {
  49577. const mipmap = mipmaps[ j ];
  49578. const mipmapImage = mipmap.image[ i ].image;
  49579. if ( useTexStorage ) {
  49580. if ( dataReady ) {
  49581. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  49582. }
  49583. } else {
  49584. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  49585. }
  49586. }
  49587. } else {
  49588. if ( useTexStorage ) {
  49589. if ( dataReady ) {
  49590. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  49591. }
  49592. } else {
  49593. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  49594. }
  49595. for ( let j = 0; j < mipmaps.length; j ++ ) {
  49596. const mipmap = mipmaps[ j ];
  49597. if ( useTexStorage ) {
  49598. if ( dataReady ) {
  49599. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  49600. }
  49601. } else {
  49602. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  49603. }
  49604. }
  49605. }
  49606. }
  49607. }
  49608. if ( textureNeedsGenerateMipmaps( texture ) ) {
  49609. // We assume images for cube map have the same size.
  49610. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  49611. }
  49612. sourceProperties.__version = source.version;
  49613. if ( texture.onUpdate ) texture.onUpdate( texture );
  49614. }
  49615. textureProperties.__version = texture.version;
  49616. }
  49617. // Render targets
  49618. // Setup storage for target texture and bind it to correct framebuffer
  49619. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  49620. const glFormat = utils.convert( texture.format, texture.colorSpace );
  49621. const glType = utils.convert( texture.type );
  49622. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  49623. const renderTargetProperties = properties.get( renderTarget );
  49624. const textureProperties = properties.get( texture );
  49625. textureProperties.__renderTarget = renderTarget;
  49626. if ( ! renderTargetProperties.__hasExternalTextures ) {
  49627. const width = Math.max( 1, renderTarget.width >> level );
  49628. const height = Math.max( 1, renderTarget.height >> level );
  49629. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  49630. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  49631. } else {
  49632. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  49633. }
  49634. }
  49635. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  49636. if ( useMultisampledRTT( renderTarget ) ) {
  49637. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  49638. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  49639. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level );
  49640. }
  49641. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  49642. }
  49643. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  49644. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  49645. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  49646. if ( renderTarget.depthBuffer ) {
  49647. // retrieve the depth attachment types
  49648. const depthTexture = renderTarget.depthTexture;
  49649. const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null;
  49650. const glInternalFormat = getInternalDepthFormat( renderTarget.stencilBuffer, depthType );
  49651. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  49652. // set up the attachment
  49653. const samples = getRenderTargetSamples( renderTarget );
  49654. const isUseMultisampledRTT = useMultisampledRTT( renderTarget );
  49655. if ( isUseMultisampledRTT ) {
  49656. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49657. } else if ( isMultisample ) {
  49658. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49659. } else {
  49660. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  49661. }
  49662. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  49663. } else {
  49664. const textures = renderTarget.textures;
  49665. for ( let i = 0; i < textures.length; i ++ ) {
  49666. const texture = textures[ i ];
  49667. const glFormat = utils.convert( texture.format, texture.colorSpace );
  49668. const glType = utils.convert( texture.type );
  49669. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  49670. const samples = getRenderTargetSamples( renderTarget );
  49671. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  49672. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49673. } else if ( useMultisampledRTT( renderTarget ) ) {
  49674. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49675. } else {
  49676. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  49677. }
  49678. }
  49679. }
  49680. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  49681. }
  49682. // Setup resources for a Depth Texture for a FBO (needs an extension)
  49683. function setupDepthTexture( framebuffer, renderTarget ) {
  49684. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  49685. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  49686. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  49687. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  49688. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  49689. }
  49690. const textureProperties = properties.get( renderTarget.depthTexture );
  49691. textureProperties.__renderTarget = renderTarget;
  49692. // upload an empty depth texture with framebuffer size
  49693. if ( ! textureProperties.__webglTexture ||
  49694. renderTarget.depthTexture.image.width !== renderTarget.width ||
  49695. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  49696. renderTarget.depthTexture.image.width = renderTarget.width;
  49697. renderTarget.depthTexture.image.height = renderTarget.height;
  49698. renderTarget.depthTexture.needsUpdate = true;
  49699. }
  49700. setTexture2D( renderTarget.depthTexture, 0 );
  49701. const webglDepthTexture = textureProperties.__webglTexture;
  49702. const samples = getRenderTargetSamples( renderTarget );
  49703. if ( renderTarget.depthTexture.format === DepthFormat ) {
  49704. if ( useMultisampledRTT( renderTarget ) ) {
  49705. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  49706. } else {
  49707. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  49708. }
  49709. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  49710. if ( useMultisampledRTT( renderTarget ) ) {
  49711. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  49712. } else {
  49713. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  49714. }
  49715. } else {
  49716. throw new Error( 'Unknown depthTexture format' );
  49717. }
  49718. }
  49719. // Setup GL resources for a non-texture depth buffer
  49720. function setupDepthRenderbuffer( renderTarget ) {
  49721. const renderTargetProperties = properties.get( renderTarget );
  49722. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  49723. // if the bound depth texture has changed
  49724. if ( renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture ) {
  49725. // fire the dispose event to get rid of stored state associated with the previously bound depth buffer
  49726. const depthTexture = renderTarget.depthTexture;
  49727. if ( renderTargetProperties.__depthDisposeCallback ) {
  49728. renderTargetProperties.__depthDisposeCallback();
  49729. }
  49730. // set up dispose listeners to track when the currently attached buffer is implicitly unbound
  49731. if ( depthTexture ) {
  49732. const disposeEvent = () => {
  49733. delete renderTargetProperties.__boundDepthTexture;
  49734. delete renderTargetProperties.__depthDisposeCallback;
  49735. depthTexture.removeEventListener( 'dispose', disposeEvent );
  49736. };
  49737. depthTexture.addEventListener( 'dispose', disposeEvent );
  49738. renderTargetProperties.__depthDisposeCallback = disposeEvent;
  49739. }
  49740. renderTargetProperties.__boundDepthTexture = depthTexture;
  49741. }
  49742. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  49743. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  49744. const mipmaps = renderTarget.texture.mipmaps;
  49745. if ( mipmaps && mipmaps.length > 0 ) {
  49746. setupDepthTexture( renderTargetProperties.__webglFramebuffer[ 0 ], renderTarget );
  49747. } else {
  49748. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  49749. }
  49750. } else {
  49751. if ( isCube ) {
  49752. renderTargetProperties.__webglDepthbuffer = [];
  49753. for ( let i = 0; i < 6; i ++ ) {
  49754. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  49755. if ( renderTargetProperties.__webglDepthbuffer[ i ] === undefined ) {
  49756. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  49757. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  49758. } else {
  49759. // attach buffer if it's been created already
  49760. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  49761. const renderbuffer = renderTargetProperties.__webglDepthbuffer[ i ];
  49762. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  49763. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  49764. }
  49765. }
  49766. } else {
  49767. const mipmaps = renderTarget.texture.mipmaps;
  49768. if ( mipmaps && mipmaps.length > 0 ) {
  49769. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  49770. } else {
  49771. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  49772. }
  49773. if ( renderTargetProperties.__webglDepthbuffer === undefined ) {
  49774. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  49775. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  49776. } else {
  49777. // attach buffer if it's been created already
  49778. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  49779. const renderbuffer = renderTargetProperties.__webglDepthbuffer;
  49780. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  49781. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  49782. }
  49783. }
  49784. }
  49785. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  49786. }
  49787. // rebind framebuffer with external textures
  49788. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  49789. const renderTargetProperties = properties.get( renderTarget );
  49790. if ( colorTexture !== undefined ) {
  49791. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  49792. }
  49793. if ( depthTexture !== undefined ) {
  49794. setupDepthRenderbuffer( renderTarget );
  49795. }
  49796. }
  49797. // Set up GL resources for the render target
  49798. function setupRenderTarget( renderTarget ) {
  49799. const texture = renderTarget.texture;
  49800. const renderTargetProperties = properties.get( renderTarget );
  49801. const textureProperties = properties.get( texture );
  49802. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  49803. const textures = renderTarget.textures;
  49804. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  49805. const isMultipleRenderTargets = ( textures.length > 1 );
  49806. if ( ! isMultipleRenderTargets ) {
  49807. if ( textureProperties.__webglTexture === undefined ) {
  49808. textureProperties.__webglTexture = _gl.createTexture();
  49809. }
  49810. textureProperties.__version = texture.version;
  49811. info.memory.textures ++;
  49812. }
  49813. // Setup framebuffer
  49814. if ( isCube ) {
  49815. renderTargetProperties.__webglFramebuffer = [];
  49816. for ( let i = 0; i < 6; i ++ ) {
  49817. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  49818. renderTargetProperties.__webglFramebuffer[ i ] = [];
  49819. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  49820. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  49821. }
  49822. } else {
  49823. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  49824. }
  49825. }
  49826. } else {
  49827. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  49828. renderTargetProperties.__webglFramebuffer = [];
  49829. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  49830. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  49831. }
  49832. } else {
  49833. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  49834. }
  49835. if ( isMultipleRenderTargets ) {
  49836. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49837. const attachmentProperties = properties.get( textures[ i ] );
  49838. if ( attachmentProperties.__webglTexture === undefined ) {
  49839. attachmentProperties.__webglTexture = _gl.createTexture();
  49840. info.memory.textures ++;
  49841. }
  49842. }
  49843. }
  49844. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  49845. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  49846. renderTargetProperties.__webglColorRenderbuffer = [];
  49847. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  49848. for ( let i = 0; i < textures.length; i ++ ) {
  49849. const texture = textures[ i ];
  49850. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  49851. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  49852. const glFormat = utils.convert( texture.format, texture.colorSpace );
  49853. const glType = utils.convert( texture.type );
  49854. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  49855. const samples = getRenderTargetSamples( renderTarget );
  49856. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49857. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  49858. }
  49859. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  49860. if ( renderTarget.depthBuffer ) {
  49861. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  49862. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  49863. }
  49864. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  49865. }
  49866. }
  49867. // Setup color buffer
  49868. if ( isCube ) {
  49869. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  49870. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  49871. for ( let i = 0; i < 6; i ++ ) {
  49872. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  49873. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  49874. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  49875. }
  49876. } else {
  49877. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  49878. }
  49879. }
  49880. if ( textureNeedsGenerateMipmaps( texture ) ) {
  49881. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  49882. }
  49883. state.unbindTexture();
  49884. } else if ( isMultipleRenderTargets ) {
  49885. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49886. const attachment = textures[ i ];
  49887. const attachmentProperties = properties.get( attachment );
  49888. let glTextureType = _gl.TEXTURE_2D;
  49889. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  49890. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  49891. }
  49892. state.bindTexture( glTextureType, attachmentProperties.__webglTexture );
  49893. setTextureParameters( glTextureType, attachment );
  49894. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, glTextureType, 0 );
  49895. if ( textureNeedsGenerateMipmaps( attachment ) ) {
  49896. generateMipmap( glTextureType );
  49897. }
  49898. }
  49899. state.unbindTexture();
  49900. } else {
  49901. let glTextureType = _gl.TEXTURE_2D;
  49902. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  49903. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  49904. }
  49905. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  49906. setTextureParameters( glTextureType, texture );
  49907. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  49908. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  49909. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  49910. }
  49911. } else {
  49912. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  49913. }
  49914. if ( textureNeedsGenerateMipmaps( texture ) ) {
  49915. generateMipmap( glTextureType );
  49916. }
  49917. state.unbindTexture();
  49918. }
  49919. // Setup depth and stencil buffers
  49920. if ( renderTarget.depthBuffer ) {
  49921. setupDepthRenderbuffer( renderTarget );
  49922. }
  49923. }
  49924. function updateRenderTargetMipmap( renderTarget ) {
  49925. const textures = renderTarget.textures;
  49926. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49927. const texture = textures[ i ];
  49928. if ( textureNeedsGenerateMipmaps( texture ) ) {
  49929. const targetType = getTargetType( renderTarget );
  49930. const webglTexture = properties.get( texture ).__webglTexture;
  49931. state.bindTexture( targetType, webglTexture );
  49932. generateMipmap( targetType );
  49933. state.unbindTexture();
  49934. }
  49935. }
  49936. }
  49937. const invalidationArrayRead = [];
  49938. const invalidationArrayDraw = [];
  49939. function updateMultisampleRenderTarget( renderTarget ) {
  49940. if ( renderTarget.samples > 0 ) {
  49941. if ( useMultisampledRTT( renderTarget ) === false ) {
  49942. const textures = renderTarget.textures;
  49943. const width = renderTarget.width;
  49944. const height = renderTarget.height;
  49945. let mask = _gl.COLOR_BUFFER_BIT;
  49946. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  49947. const renderTargetProperties = properties.get( renderTarget );
  49948. const isMultipleRenderTargets = ( textures.length > 1 );
  49949. // If MRT we need to remove FBO attachments
  49950. if ( isMultipleRenderTargets ) {
  49951. for ( let i = 0; i < textures.length; i ++ ) {
  49952. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  49953. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  49954. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  49955. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  49956. }
  49957. }
  49958. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  49959. const mipmaps = renderTarget.texture.mipmaps;
  49960. if ( mipmaps && mipmaps.length > 0 ) {
  49961. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  49962. } else {
  49963. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  49964. }
  49965. for ( let i = 0; i < textures.length; i ++ ) {
  49966. if ( renderTarget.resolveDepthBuffer ) {
  49967. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  49968. // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799)
  49969. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  49970. }
  49971. if ( isMultipleRenderTargets ) {
  49972. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  49973. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  49974. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  49975. }
  49976. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  49977. if ( supportsInvalidateFramebuffer === true ) {
  49978. invalidationArrayRead.length = 0;
  49979. invalidationArrayDraw.length = 0;
  49980. invalidationArrayRead.push( _gl.COLOR_ATTACHMENT0 + i );
  49981. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false ) {
  49982. invalidationArrayRead.push( depthStyle );
  49983. invalidationArrayDraw.push( depthStyle );
  49984. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, invalidationArrayDraw );
  49985. }
  49986. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArrayRead );
  49987. }
  49988. }
  49989. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  49990. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  49991. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  49992. if ( isMultipleRenderTargets ) {
  49993. for ( let i = 0; i < textures.length; i ++ ) {
  49994. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  49995. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  49996. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  49997. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  49998. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  49999. }
  50000. }
  50001. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50002. } else {
  50003. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer ) {
  50004. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50005. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  50006. }
  50007. }
  50008. }
  50009. }
  50010. function getRenderTargetSamples( renderTarget ) {
  50011. return Math.min( capabilities.maxSamples, renderTarget.samples );
  50012. }
  50013. function useMultisampledRTT( renderTarget ) {
  50014. const renderTargetProperties = properties.get( renderTarget );
  50015. return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  50016. }
  50017. function updateVideoTexture( texture ) {
  50018. const frame = info.render.frame;
  50019. // Check the last frame we updated the VideoTexture
  50020. if ( _videoTextures.get( texture ) !== frame ) {
  50021. _videoTextures.set( texture, frame );
  50022. texture.update();
  50023. }
  50024. }
  50025. function verifyColorSpace( texture, image ) {
  50026. const colorSpace = texture.colorSpace;
  50027. const format = texture.format;
  50028. const type = texture.type;
  50029. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image;
  50030. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  50031. // sRGB
  50032. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  50033. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  50034. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  50035. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  50036. }
  50037. } else {
  50038. console.error( 'THREE.WebGLTextures: Unsupported texture color space:', colorSpace );
  50039. }
  50040. }
  50041. return image;
  50042. }
  50043. function getDimensions( image ) {
  50044. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) {
  50045. // if intrinsic data are not available, fallback to width/height
  50046. _imageDimensions.width = image.naturalWidth || image.width;
  50047. _imageDimensions.height = image.naturalHeight || image.height;
  50048. } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) {
  50049. _imageDimensions.width = image.displayWidth;
  50050. _imageDimensions.height = image.displayHeight;
  50051. } else {
  50052. _imageDimensions.width = image.width;
  50053. _imageDimensions.height = image.height;
  50054. }
  50055. return _imageDimensions;
  50056. }
  50057. //
  50058. this.allocateTextureUnit = allocateTextureUnit;
  50059. this.resetTextureUnits = resetTextureUnits;
  50060. this.setTexture2D = setTexture2D;
  50061. this.setTexture2DArray = setTexture2DArray;
  50062. this.setTexture3D = setTexture3D;
  50063. this.setTextureCube = setTextureCube;
  50064. this.rebindTextures = rebindTextures;
  50065. this.setupRenderTarget = setupRenderTarget;
  50066. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  50067. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  50068. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  50069. this.setupFrameBufferTexture = setupFrameBufferTexture;
  50070. this.useMultisampledRTT = useMultisampledRTT;
  50071. }
  50072. function WebGLUtils( gl, extensions ) {
  50073. function convert( p, colorSpace = NoColorSpace ) {
  50074. let extension;
  50075. const transfer = ColorManagement.getTransfer( colorSpace );
  50076. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  50077. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  50078. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  50079. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  50080. if ( p === ByteType ) return gl.BYTE;
  50081. if ( p === ShortType ) return gl.SHORT;
  50082. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  50083. if ( p === IntType ) return gl.INT;
  50084. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  50085. if ( p === FloatType ) return gl.FLOAT;
  50086. if ( p === HalfFloatType ) return gl.HALF_FLOAT;
  50087. if ( p === AlphaFormat ) return gl.ALPHA;
  50088. if ( p === RGBFormat ) return gl.RGB;
  50089. if ( p === RGBAFormat ) return gl.RGBA;
  50090. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  50091. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  50092. // WebGL2 formats.
  50093. if ( p === RedFormat ) return gl.RED;
  50094. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  50095. if ( p === RGFormat ) return gl.RG;
  50096. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  50097. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  50098. // S3TC
  50099. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  50100. if ( transfer === SRGBTransfer ) {
  50101. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  50102. if ( extension !== null ) {
  50103. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  50104. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  50105. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  50106. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  50107. } else {
  50108. return null;
  50109. }
  50110. } else {
  50111. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  50112. if ( extension !== null ) {
  50113. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  50114. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  50115. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  50116. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  50117. } else {
  50118. return null;
  50119. }
  50120. }
  50121. }
  50122. // PVRTC
  50123. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  50124. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  50125. if ( extension !== null ) {
  50126. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  50127. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  50128. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  50129. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  50130. } else {
  50131. return null;
  50132. }
  50133. }
  50134. // ETC
  50135. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  50136. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  50137. if ( extension !== null ) {
  50138. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  50139. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  50140. } else {
  50141. return null;
  50142. }
  50143. }
  50144. // ASTC
  50145. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  50146. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  50147. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  50148. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  50149. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  50150. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  50151. if ( extension !== null ) {
  50152. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  50153. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  50154. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  50155. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  50156. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  50157. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  50158. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  50159. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  50160. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  50161. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  50162. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  50163. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  50164. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  50165. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  50166. } else {
  50167. return null;
  50168. }
  50169. }
  50170. // BPTC
  50171. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  50172. extension = extensions.get( 'EXT_texture_compression_bptc' );
  50173. if ( extension !== null ) {
  50174. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  50175. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  50176. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  50177. } else {
  50178. return null;
  50179. }
  50180. }
  50181. // RGTC
  50182. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  50183. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  50184. if ( extension !== null ) {
  50185. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  50186. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  50187. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  50188. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  50189. } else {
  50190. return null;
  50191. }
  50192. }
  50193. //
  50194. if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8;
  50195. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  50196. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  50197. }
  50198. return { convert: convert };
  50199. }
  50200. /**
  50201. * Represents a texture created externally from the renderer context.
  50202. *
  50203. * This may be a texture from a protected media stream, device camera feed,
  50204. * or other data feeds like a depth sensor.
  50205. *
  50206. * Note that this class is only supported in {@link WebGLRenderer} right now.
  50207. *
  50208. * @augments Texture
  50209. */
  50210. class ExternalTexture extends Texture {
  50211. /**
  50212. * Creates a new raw texture.
  50213. *
  50214. * @param {?WebGLTexture} [sourceTexture=null] - The external texture.
  50215. */
  50216. constructor( sourceTexture = null ) {
  50217. super();
  50218. /**
  50219. * The external source texture.
  50220. *
  50221. * @type {?WebGLTexture}
  50222. * @default null
  50223. */
  50224. this.sourceTexture = sourceTexture;
  50225. /**
  50226. * This flag can be used for type testing.
  50227. *
  50228. * @type {boolean}
  50229. * @readonly
  50230. * @default true
  50231. */
  50232. this.isExternalTexture = true;
  50233. }
  50234. }
  50235. const _occlusion_vertex = `
  50236. void main() {
  50237. gl_Position = vec4( position, 1.0 );
  50238. }`;
  50239. const _occlusion_fragment = `
  50240. uniform sampler2DArray depthColor;
  50241. uniform float depthWidth;
  50242. uniform float depthHeight;
  50243. void main() {
  50244. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  50245. if ( coord.x >= 1.0 ) {
  50246. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  50247. } else {
  50248. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  50249. }
  50250. }`;
  50251. /**
  50252. * A XR module that manages the access to the Depth Sensing API.
  50253. */
  50254. class WebXRDepthSensing {
  50255. /**
  50256. * Constructs a new depth sensing module.
  50257. */
  50258. constructor() {
  50259. /**
  50260. * An opaque texture representing the depth of the user's environment.
  50261. *
  50262. * @type {?ExternalTexture}
  50263. */
  50264. this.texture = null;
  50265. /**
  50266. * A plane mesh for visualizing the depth texture.
  50267. *
  50268. * @type {?Mesh}
  50269. */
  50270. this.mesh = null;
  50271. /**
  50272. * The depth near value.
  50273. *
  50274. * @type {number}
  50275. */
  50276. this.depthNear = 0;
  50277. /**
  50278. * The depth near far.
  50279. *
  50280. * @type {number}
  50281. */
  50282. this.depthFar = 0;
  50283. }
  50284. /**
  50285. * Inits the depth sensing module
  50286. *
  50287. * @param {XRWebGLDepthInformation} depthData - The XR depth data.
  50288. * @param {XRRenderState} renderState - The XR render state.
  50289. */
  50290. init( depthData, renderState ) {
  50291. if ( this.texture === null ) {
  50292. const texture = new ExternalTexture( depthData.texture );
  50293. if ( ( depthData.depthNear !== renderState.depthNear ) || ( depthData.depthFar !== renderState.depthFar ) ) {
  50294. this.depthNear = depthData.depthNear;
  50295. this.depthFar = depthData.depthFar;
  50296. }
  50297. this.texture = texture;
  50298. }
  50299. }
  50300. /**
  50301. * Returns a plane mesh that visualizes the depth texture.
  50302. *
  50303. * @param {ArrayCamera} cameraXR - The XR camera.
  50304. * @return {?Mesh} The plane mesh.
  50305. */
  50306. getMesh( cameraXR ) {
  50307. if ( this.texture !== null ) {
  50308. if ( this.mesh === null ) {
  50309. const viewport = cameraXR.cameras[ 0 ].viewport;
  50310. const material = new ShaderMaterial( {
  50311. vertexShader: _occlusion_vertex,
  50312. fragmentShader: _occlusion_fragment,
  50313. uniforms: {
  50314. depthColor: { value: this.texture },
  50315. depthWidth: { value: viewport.z },
  50316. depthHeight: { value: viewport.w }
  50317. }
  50318. } );
  50319. this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material );
  50320. }
  50321. }
  50322. return this.mesh;
  50323. }
  50324. /**
  50325. * Resets the module
  50326. */
  50327. reset() {
  50328. this.texture = null;
  50329. this.mesh = null;
  50330. }
  50331. /**
  50332. * Returns a texture representing the depth of the user's environment.
  50333. *
  50334. * @return {?ExternalTexture} The depth texture.
  50335. */
  50336. getDepthTexture() {
  50337. return this.texture;
  50338. }
  50339. }
  50340. /**
  50341. * This class represents an abstraction of the WebXR Device API and is
  50342. * internally used by {@link WebGLRenderer}. `WebXRManager` also provides a public
  50343. * interface that allows users to enable/disable XR and perform XR related
  50344. * tasks like for instance retrieving controllers.
  50345. *
  50346. * @augments EventDispatcher
  50347. * @hideconstructor
  50348. */
  50349. class WebXRManager extends EventDispatcher {
  50350. /**
  50351. * Constructs a new WebGL renderer.
  50352. *
  50353. * @param {WebGLRenderer} renderer - The renderer.
  50354. * @param {WebGL2RenderingContext} gl - The rendering context.
  50355. */
  50356. constructor( renderer, gl ) {
  50357. super();
  50358. const scope = this;
  50359. let session = null;
  50360. let framebufferScaleFactor = 1.0;
  50361. let referenceSpace = null;
  50362. let referenceSpaceType = 'local-floor';
  50363. // Set default foveation to maximum.
  50364. let foveation = 1.0;
  50365. let customReferenceSpace = null;
  50366. let pose = null;
  50367. let glBinding = null;
  50368. let glProjLayer = null;
  50369. let glBaseLayer = null;
  50370. let xrFrame = null;
  50371. const depthSensing = new WebXRDepthSensing();
  50372. const cameraAccessTextures = {};
  50373. const attributes = gl.getContextAttributes();
  50374. let initialRenderTarget = null;
  50375. let newRenderTarget = null;
  50376. const controllers = [];
  50377. const controllerInputSources = [];
  50378. const currentSize = new Vector2();
  50379. let currentPixelRatio = null;
  50380. //
  50381. const cameraL = new PerspectiveCamera();
  50382. cameraL.viewport = new Vector4();
  50383. const cameraR = new PerspectiveCamera();
  50384. cameraR.viewport = new Vector4();
  50385. const cameras = [ cameraL, cameraR ];
  50386. const cameraXR = new ArrayCamera();
  50387. let _currentDepthNear = null;
  50388. let _currentDepthFar = null;
  50389. //
  50390. /**
  50391. * Whether the manager's XR camera should be automatically updated or not.
  50392. *
  50393. * @type {boolean}
  50394. * @default true
  50395. */
  50396. this.cameraAutoUpdate = true;
  50397. /**
  50398. * This flag notifies the renderer to be ready for XR rendering. Set it to `true`
  50399. * if you are going to use XR in your app.
  50400. *
  50401. * @type {boolean}
  50402. * @default false
  50403. */
  50404. this.enabled = false;
  50405. /**
  50406. * Whether XR presentation is active or not.
  50407. *
  50408. * @type {boolean}
  50409. * @readonly
  50410. * @default false
  50411. */
  50412. this.isPresenting = false;
  50413. /**
  50414. * Returns a group representing the `target ray` space of the XR controller.
  50415. * Use this space for visualizing 3D objects that support the user in pointing
  50416. * tasks like UI interaction.
  50417. *
  50418. * @param {number} index - The index of the controller.
  50419. * @return {Group} A group representing the `target ray` space.
  50420. */
  50421. this.getController = function ( index ) {
  50422. let controller = controllers[ index ];
  50423. if ( controller === undefined ) {
  50424. controller = new WebXRController();
  50425. controllers[ index ] = controller;
  50426. }
  50427. return controller.getTargetRaySpace();
  50428. };
  50429. /**
  50430. * Returns a group representing the `grip` space of the XR controller.
  50431. * Use this space for visualizing 3D objects that support the user in pointing
  50432. * tasks like UI interaction.
  50433. *
  50434. * Note: If you want to show something in the user's hand AND offer a
  50435. * pointing ray at the same time, you'll want to attached the handheld object
  50436. * to the group returned by `getControllerGrip()` and the ray to the
  50437. * group returned by `getController()`. The idea is to have two
  50438. * different groups in two different coordinate spaces for the same WebXR
  50439. * controller.
  50440. *
  50441. * @param {number} index - The index of the controller.
  50442. * @return {Group} A group representing the `grip` space.
  50443. */
  50444. this.getControllerGrip = function ( index ) {
  50445. let controller = controllers[ index ];
  50446. if ( controller === undefined ) {
  50447. controller = new WebXRController();
  50448. controllers[ index ] = controller;
  50449. }
  50450. return controller.getGripSpace();
  50451. };
  50452. /**
  50453. * Returns a group representing the `hand` space of the XR controller.
  50454. * Use this space for visualizing 3D objects that support the user in pointing
  50455. * tasks like UI interaction.
  50456. *
  50457. * @param {number} index - The index of the controller.
  50458. * @return {Group} A group representing the `hand` space.
  50459. */
  50460. this.getHand = function ( index ) {
  50461. let controller = controllers[ index ];
  50462. if ( controller === undefined ) {
  50463. controller = new WebXRController();
  50464. controllers[ index ] = controller;
  50465. }
  50466. return controller.getHandSpace();
  50467. };
  50468. //
  50469. function onSessionEvent( event ) {
  50470. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  50471. if ( controllerIndex === -1 ) {
  50472. return;
  50473. }
  50474. const controller = controllers[ controllerIndex ];
  50475. if ( controller !== undefined ) {
  50476. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  50477. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  50478. }
  50479. }
  50480. function onSessionEnd() {
  50481. session.removeEventListener( 'select', onSessionEvent );
  50482. session.removeEventListener( 'selectstart', onSessionEvent );
  50483. session.removeEventListener( 'selectend', onSessionEvent );
  50484. session.removeEventListener( 'squeeze', onSessionEvent );
  50485. session.removeEventListener( 'squeezestart', onSessionEvent );
  50486. session.removeEventListener( 'squeezeend', onSessionEvent );
  50487. session.removeEventListener( 'end', onSessionEnd );
  50488. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  50489. for ( let i = 0; i < controllers.length; i ++ ) {
  50490. const inputSource = controllerInputSources[ i ];
  50491. if ( inputSource === null ) continue;
  50492. controllerInputSources[ i ] = null;
  50493. controllers[ i ].disconnect( inputSource );
  50494. }
  50495. _currentDepthNear = null;
  50496. _currentDepthFar = null;
  50497. depthSensing.reset();
  50498. for ( const key in cameraAccessTextures ) {
  50499. delete cameraAccessTextures[ key ];
  50500. }
  50501. // restore framebuffer/rendering state
  50502. renderer.setRenderTarget( initialRenderTarget );
  50503. glBaseLayer = null;
  50504. glProjLayer = null;
  50505. glBinding = null;
  50506. session = null;
  50507. newRenderTarget = null;
  50508. //
  50509. animation.stop();
  50510. scope.isPresenting = false;
  50511. renderer.setPixelRatio( currentPixelRatio );
  50512. renderer.setSize( currentSize.width, currentSize.height, false );
  50513. scope.dispatchEvent( { type: 'sessionend' } );
  50514. }
  50515. /**
  50516. * Sets the framebuffer scale factor.
  50517. *
  50518. * This method can not be used during a XR session.
  50519. *
  50520. * @param {number} value - The framebuffer scale factor.
  50521. */
  50522. this.setFramebufferScaleFactor = function ( value ) {
  50523. framebufferScaleFactor = value;
  50524. if ( scope.isPresenting === true ) {
  50525. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  50526. }
  50527. };
  50528. /**
  50529. * Sets the reference space type. Can be used to configure a spatial relationship with the user's physical
  50530. * environment. Depending on how the user moves in 3D space, setting an appropriate reference space can
  50531. * improve tracking. Default is `local-floor`. Valid values can be found here
  50532. * https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpace#reference_space_types.
  50533. *
  50534. * This method can not be used during a XR session.
  50535. *
  50536. * @param {string} value - The reference space type.
  50537. */
  50538. this.setReferenceSpaceType = function ( value ) {
  50539. referenceSpaceType = value;
  50540. if ( scope.isPresenting === true ) {
  50541. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  50542. }
  50543. };
  50544. /**
  50545. * Returns the XR reference space.
  50546. *
  50547. * @return {XRReferenceSpace} The XR reference space.
  50548. */
  50549. this.getReferenceSpace = function () {
  50550. return customReferenceSpace || referenceSpace;
  50551. };
  50552. /**
  50553. * Sets a custom XR reference space.
  50554. *
  50555. * @param {XRReferenceSpace} space - The XR reference space.
  50556. */
  50557. this.setReferenceSpace = function ( space ) {
  50558. customReferenceSpace = space;
  50559. };
  50560. /**
  50561. * Returns the current base layer.
  50562. *
  50563. * @return {?(XRWebGLLayer|XRProjectionLayer)} The XR base layer.
  50564. */
  50565. this.getBaseLayer = function () {
  50566. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  50567. };
  50568. /**
  50569. * Returns the current XR binding.
  50570. *
  50571. * @return {?XRWebGLBinding} The XR binding.
  50572. */
  50573. this.getBinding = function () {
  50574. return glBinding;
  50575. };
  50576. /**
  50577. * Returns the current XR frame.
  50578. *
  50579. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  50580. */
  50581. this.getFrame = function () {
  50582. return xrFrame;
  50583. };
  50584. /**
  50585. * Returns the current XR session.
  50586. *
  50587. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  50588. */
  50589. this.getSession = function () {
  50590. return session;
  50591. };
  50592. /**
  50593. * After a XR session has been requested usually with one of the `*Button` modules, it
  50594. * is injected into the renderer with this method. This method triggers the start of
  50595. * the actual XR rendering.
  50596. *
  50597. * @async
  50598. * @param {XRSession} value - The XR session to set.
  50599. * @return {Promise} A Promise that resolves when the session has been set.
  50600. */
  50601. this.setSession = async function ( value ) {
  50602. session = value;
  50603. if ( session !== null ) {
  50604. initialRenderTarget = renderer.getRenderTarget();
  50605. session.addEventListener( 'select', onSessionEvent );
  50606. session.addEventListener( 'selectstart', onSessionEvent );
  50607. session.addEventListener( 'selectend', onSessionEvent );
  50608. session.addEventListener( 'squeeze', onSessionEvent );
  50609. session.addEventListener( 'squeezestart', onSessionEvent );
  50610. session.addEventListener( 'squeezeend', onSessionEvent );
  50611. session.addEventListener( 'end', onSessionEnd );
  50612. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  50613. if ( attributes.xrCompatible !== true ) {
  50614. await gl.makeXRCompatible();
  50615. }
  50616. currentPixelRatio = renderer.getPixelRatio();
  50617. renderer.getSize( currentSize );
  50618. if ( typeof XRWebGLBinding !== 'undefined' ) {
  50619. glBinding = new XRWebGLBinding( session, gl );
  50620. }
  50621. // Check that the browser implements the necessary APIs to use an
  50622. // XRProjectionLayer rather than an XRWebGLLayer
  50623. const useLayers = glBinding !== null && 'createProjectionLayer' in XRWebGLBinding.prototype;
  50624. if ( ! useLayers ) {
  50625. const layerInit = {
  50626. antialias: attributes.antialias,
  50627. alpha: true,
  50628. depth: attributes.depth,
  50629. stencil: attributes.stencil,
  50630. framebufferScaleFactor: framebufferScaleFactor
  50631. };
  50632. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  50633. session.updateRenderState( { baseLayer: glBaseLayer } );
  50634. renderer.setPixelRatio( 1 );
  50635. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  50636. newRenderTarget = new WebGLRenderTarget(
  50637. glBaseLayer.framebufferWidth,
  50638. glBaseLayer.framebufferHeight,
  50639. {
  50640. format: RGBAFormat,
  50641. type: UnsignedByteType,
  50642. colorSpace: renderer.outputColorSpace,
  50643. stencilBuffer: attributes.stencil,
  50644. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  50645. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false )
  50646. }
  50647. );
  50648. } else {
  50649. let depthFormat = null;
  50650. let depthType = null;
  50651. let glDepthFormat = null;
  50652. if ( attributes.depth ) {
  50653. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  50654. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  50655. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  50656. }
  50657. const projectionlayerInit = {
  50658. colorFormat: gl.RGBA8,
  50659. depthFormat: glDepthFormat,
  50660. scaleFactor: framebufferScaleFactor
  50661. };
  50662. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  50663. session.updateRenderState( { layers: [ glProjLayer ] } );
  50664. renderer.setPixelRatio( 1 );
  50665. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  50666. newRenderTarget = new WebGLRenderTarget(
  50667. glProjLayer.textureWidth,
  50668. glProjLayer.textureHeight,
  50669. {
  50670. format: RGBAFormat,
  50671. type: UnsignedByteType,
  50672. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  50673. stencilBuffer: attributes.stencil,
  50674. colorSpace: renderer.outputColorSpace,
  50675. samples: attributes.antialias ? 4 : 0,
  50676. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  50677. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false )
  50678. } );
  50679. }
  50680. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  50681. this.setFoveation( foveation );
  50682. customReferenceSpace = null;
  50683. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  50684. animation.setContext( session );
  50685. animation.start();
  50686. scope.isPresenting = true;
  50687. scope.dispatchEvent( { type: 'sessionstart' } );
  50688. }
  50689. };
  50690. /**
  50691. * Returns the environment blend mode from the current XR session.
  50692. *
  50693. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  50694. */
  50695. this.getEnvironmentBlendMode = function () {
  50696. if ( session !== null ) {
  50697. return session.environmentBlendMode;
  50698. }
  50699. };
  50700. /**
  50701. * Returns the current depth texture computed via depth sensing.
  50702. *
  50703. * @return {?Texture} The depth texture.
  50704. */
  50705. this.getDepthTexture = function () {
  50706. return depthSensing.getDepthTexture();
  50707. };
  50708. function onInputSourcesChange( event ) {
  50709. // Notify disconnected
  50710. for ( let i = 0; i < event.removed.length; i ++ ) {
  50711. const inputSource = event.removed[ i ];
  50712. const index = controllerInputSources.indexOf( inputSource );
  50713. if ( index >= 0 ) {
  50714. controllerInputSources[ index ] = null;
  50715. controllers[ index ].disconnect( inputSource );
  50716. }
  50717. }
  50718. // Notify connected
  50719. for ( let i = 0; i < event.added.length; i ++ ) {
  50720. const inputSource = event.added[ i ];
  50721. let controllerIndex = controllerInputSources.indexOf( inputSource );
  50722. if ( controllerIndex === -1 ) {
  50723. // Assign input source a controller that currently has no input source
  50724. for ( let i = 0; i < controllers.length; i ++ ) {
  50725. if ( i >= controllerInputSources.length ) {
  50726. controllerInputSources.push( inputSource );
  50727. controllerIndex = i;
  50728. break;
  50729. } else if ( controllerInputSources[ i ] === null ) {
  50730. controllerInputSources[ i ] = inputSource;
  50731. controllerIndex = i;
  50732. break;
  50733. }
  50734. }
  50735. // If all controllers do currently receive input we ignore new ones
  50736. if ( controllerIndex === -1 ) break;
  50737. }
  50738. const controller = controllers[ controllerIndex ];
  50739. if ( controller ) {
  50740. controller.connect( inputSource );
  50741. }
  50742. }
  50743. }
  50744. //
  50745. const cameraLPos = new Vector3();
  50746. const cameraRPos = new Vector3();
  50747. /**
  50748. * Assumes 2 cameras that are parallel and share an X-axis, and that
  50749. * the cameras' projection and world matrices have already been set.
  50750. * And that near and far planes are identical for both cameras.
  50751. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  50752. *
  50753. * @param {ArrayCamera} camera - The camera to update.
  50754. * @param {PerspectiveCamera} cameraL - The left camera.
  50755. * @param {PerspectiveCamera} cameraR - The right camera.
  50756. */
  50757. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  50758. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  50759. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  50760. const ipd = cameraLPos.distanceTo( cameraRPos );
  50761. const projL = cameraL.projectionMatrix.elements;
  50762. const projR = cameraR.projectionMatrix.elements;
  50763. // VR systems will have identical far and near planes, and
  50764. // most likely identical top and bottom frustum extents.
  50765. // Use the left camera for these values.
  50766. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  50767. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  50768. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  50769. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  50770. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  50771. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  50772. const left = near * leftFov;
  50773. const right = near * rightFov;
  50774. // Calculate the new camera's position offset from the
  50775. // left camera. xOffset should be roughly half `ipd`.
  50776. const zOffset = ipd / ( - leftFov + rightFov );
  50777. const xOffset = zOffset * - leftFov;
  50778. // TODO: Better way to apply this offset?
  50779. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  50780. camera.translateX( xOffset );
  50781. camera.translateZ( zOffset );
  50782. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  50783. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  50784. // Check if the projection uses an infinite far plane.
  50785. if ( projL[ 10 ] === -1 ) {
  50786. // Use the projection matrix from the left eye.
  50787. // The camera offset is sufficient to include the view volumes
  50788. // of both eyes (assuming symmetric projections).
  50789. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  50790. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  50791. } else {
  50792. // Find the union of the frustum values of the cameras and scale
  50793. // the values so that the near plane's position does not change in world space,
  50794. // although must now be relative to the new union camera.
  50795. const near2 = near + zOffset;
  50796. const far2 = far + zOffset;
  50797. const left2 = left - xOffset;
  50798. const right2 = right + ( ipd - xOffset );
  50799. const top2 = topFov * far / far2 * near2;
  50800. const bottom2 = bottomFov * far / far2 * near2;
  50801. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  50802. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  50803. }
  50804. }
  50805. function updateCamera( camera, parent ) {
  50806. if ( parent === null ) {
  50807. camera.matrixWorld.copy( camera.matrix );
  50808. } else {
  50809. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  50810. }
  50811. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  50812. }
  50813. /**
  50814. * Updates the state of the XR camera. Use this method on app level if you
  50815. * set cameraAutoUpdate` to `false`. The method requires the non-XR
  50816. * camera of the scene as a parameter. The passed in camera's transformation
  50817. * is automatically adjusted to the position of the XR camera when calling
  50818. * this method.
  50819. *
  50820. * @param {Camera} camera - The camera.
  50821. */
  50822. this.updateCamera = function ( camera ) {
  50823. if ( session === null ) return;
  50824. let depthNear = camera.near;
  50825. let depthFar = camera.far;
  50826. if ( depthSensing.texture !== null ) {
  50827. if ( depthSensing.depthNear > 0 ) depthNear = depthSensing.depthNear;
  50828. if ( depthSensing.depthFar > 0 ) depthFar = depthSensing.depthFar;
  50829. }
  50830. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  50831. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  50832. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  50833. // Note that the new renderState won't apply until the next frame. See #18320
  50834. session.updateRenderState( {
  50835. depthNear: cameraXR.near,
  50836. depthFar: cameraXR.far
  50837. } );
  50838. _currentDepthNear = cameraXR.near;
  50839. _currentDepthFar = cameraXR.far;
  50840. }
  50841. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  50842. cameraXR.layers.mask = camera.layers.mask | 0b110;
  50843. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  50844. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  50845. const parent = camera.parent;
  50846. const cameras = cameraXR.cameras;
  50847. updateCamera( cameraXR, parent );
  50848. for ( let i = 0; i < cameras.length; i ++ ) {
  50849. updateCamera( cameras[ i ], parent );
  50850. }
  50851. // update projection matrix for proper view frustum culling
  50852. if ( cameras.length === 2 ) {
  50853. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  50854. } else {
  50855. // assume single camera setup (AR)
  50856. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  50857. }
  50858. // update user camera and its children
  50859. updateUserCamera( camera, cameraXR, parent );
  50860. };
  50861. function updateUserCamera( camera, cameraXR, parent ) {
  50862. if ( parent === null ) {
  50863. camera.matrix.copy( cameraXR.matrixWorld );
  50864. } else {
  50865. camera.matrix.copy( parent.matrixWorld );
  50866. camera.matrix.invert();
  50867. camera.matrix.multiply( cameraXR.matrixWorld );
  50868. }
  50869. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  50870. camera.updateMatrixWorld( true );
  50871. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  50872. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  50873. if ( camera.isPerspectiveCamera ) {
  50874. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  50875. camera.zoom = 1;
  50876. }
  50877. }
  50878. /**
  50879. * Returns an instance of {@link ArrayCamera} which represents the XR camera
  50880. * of the active XR session. For each view it holds a separate camera object.
  50881. *
  50882. * The camera's `fov` is currently not used and does not reflect the fov of
  50883. * the XR camera. If you need the fov on app level, you have to compute in
  50884. * manually from the XR camera's projection matrices.
  50885. *
  50886. * @return {ArrayCamera} The XR camera.
  50887. */
  50888. this.getCamera = function () {
  50889. return cameraXR;
  50890. };
  50891. /**
  50892. * Returns the amount of foveation used by the XR compositor for the projection layer.
  50893. *
  50894. * @return {number|undefined} The amount of foveation.
  50895. */
  50896. this.getFoveation = function () {
  50897. if ( glProjLayer === null && glBaseLayer === null ) {
  50898. return undefined;
  50899. }
  50900. return foveation;
  50901. };
  50902. /**
  50903. * Sets the foveation value.
  50904. *
  50905. * @param {number} value - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  50906. * and `1` means maximum foveation (the edges render at lower resolution).
  50907. */
  50908. this.setFoveation = function ( value ) {
  50909. // 0 = no foveation = full resolution
  50910. // 1 = maximum foveation = the edges render at lower resolution
  50911. foveation = value;
  50912. if ( glProjLayer !== null ) {
  50913. glProjLayer.fixedFoveation = value;
  50914. }
  50915. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  50916. glBaseLayer.fixedFoveation = value;
  50917. }
  50918. };
  50919. /**
  50920. * Returns `true` if depth sensing is supported.
  50921. *
  50922. * @return {boolean} Whether depth sensing is supported or not.
  50923. */
  50924. this.hasDepthSensing = function () {
  50925. return depthSensing.texture !== null;
  50926. };
  50927. /**
  50928. * Returns the depth sensing mesh.
  50929. *
  50930. * @return {Mesh} The depth sensing mesh.
  50931. */
  50932. this.getDepthSensingMesh = function () {
  50933. return depthSensing.getMesh( cameraXR );
  50934. };
  50935. /**
  50936. * Retrieves an opaque texture from the view-aligned {@link XRCamera}.
  50937. * Only available during the current animation loop.
  50938. *
  50939. * @param {XRCamera} xrCamera - The camera to query.
  50940. * @return {?Texture} An opaque texture representing the current raw camera frame.
  50941. */
  50942. this.getCameraTexture = function ( xrCamera ) {
  50943. return cameraAccessTextures[ xrCamera ];
  50944. };
  50945. // Animation Loop
  50946. let onAnimationFrameCallback = null;
  50947. function onAnimationFrame( time, frame ) {
  50948. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  50949. xrFrame = frame;
  50950. if ( pose !== null ) {
  50951. const views = pose.views;
  50952. if ( glBaseLayer !== null ) {
  50953. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  50954. renderer.setRenderTarget( newRenderTarget );
  50955. }
  50956. let cameraXRNeedsUpdate = false;
  50957. // check if it's necessary to rebuild cameraXR's camera list
  50958. if ( views.length !== cameraXR.cameras.length ) {
  50959. cameraXR.cameras.length = 0;
  50960. cameraXRNeedsUpdate = true;
  50961. }
  50962. for ( let i = 0; i < views.length; i ++ ) {
  50963. const view = views[ i ];
  50964. let viewport = null;
  50965. if ( glBaseLayer !== null ) {
  50966. viewport = glBaseLayer.getViewport( view );
  50967. } else {
  50968. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  50969. viewport = glSubImage.viewport;
  50970. // For side-by-side projection, we only produce a single texture for both eyes.
  50971. if ( i === 0 ) {
  50972. renderer.setRenderTargetTextures(
  50973. newRenderTarget,
  50974. glSubImage.colorTexture,
  50975. glSubImage.depthStencilTexture );
  50976. renderer.setRenderTarget( newRenderTarget );
  50977. }
  50978. }
  50979. let camera = cameras[ i ];
  50980. if ( camera === undefined ) {
  50981. camera = new PerspectiveCamera();
  50982. camera.layers.enable( i );
  50983. camera.viewport = new Vector4();
  50984. cameras[ i ] = camera;
  50985. }
  50986. camera.matrix.fromArray( view.transform.matrix );
  50987. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  50988. camera.projectionMatrix.fromArray( view.projectionMatrix );
  50989. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  50990. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  50991. if ( i === 0 ) {
  50992. cameraXR.matrix.copy( camera.matrix );
  50993. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  50994. }
  50995. if ( cameraXRNeedsUpdate === true ) {
  50996. cameraXR.cameras.push( camera );
  50997. }
  50998. }
  50999. //
  51000. const enabledFeatures = session.enabledFeatures;
  51001. const gpuDepthSensingEnabled = enabledFeatures &&
  51002. enabledFeatures.includes( 'depth-sensing' ) &&
  51003. session.depthUsage == 'gpu-optimized';
  51004. if ( gpuDepthSensingEnabled && glBinding ) {
  51005. const depthData = glBinding.getDepthInformation( views[ 0 ] );
  51006. if ( depthData && depthData.isValid && depthData.texture ) {
  51007. depthSensing.init( depthData, session.renderState );
  51008. }
  51009. }
  51010. const cameraAccessEnabled = enabledFeatures &&
  51011. enabledFeatures.includes( 'camera-access' );
  51012. if ( cameraAccessEnabled ) {
  51013. renderer.state.unbindTexture();
  51014. if ( glBinding ) {
  51015. for ( let i = 0; i < views.length; i ++ ) {
  51016. const camera = views[ i ].camera;
  51017. if ( camera ) {
  51018. let cameraTex = cameraAccessTextures[ camera ];
  51019. if ( ! cameraTex ) {
  51020. cameraTex = new ExternalTexture();
  51021. cameraAccessTextures[ camera ] = cameraTex;
  51022. }
  51023. const glTexture = glBinding.getCameraImage( camera );
  51024. cameraTex.sourceTexture = glTexture;
  51025. }
  51026. }
  51027. }
  51028. }
  51029. }
  51030. //
  51031. for ( let i = 0; i < controllers.length; i ++ ) {
  51032. const inputSource = controllerInputSources[ i ];
  51033. const controller = controllers[ i ];
  51034. if ( inputSource !== null && controller !== undefined ) {
  51035. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  51036. }
  51037. }
  51038. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  51039. if ( frame.detectedPlanes ) {
  51040. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  51041. }
  51042. xrFrame = null;
  51043. }
  51044. const animation = new WebGLAnimation();
  51045. animation.setAnimationLoop( onAnimationFrame );
  51046. this.setAnimationLoop = function ( callback ) {
  51047. onAnimationFrameCallback = callback;
  51048. };
  51049. this.dispose = function () {};
  51050. }
  51051. }
  51052. const _e1 = /*@__PURE__*/ new Euler();
  51053. const _m1 = /*@__PURE__*/ new Matrix4();
  51054. function WebGLMaterials( renderer, properties ) {
  51055. function refreshTransformUniform( map, uniform ) {
  51056. if ( map.matrixAutoUpdate === true ) {
  51057. map.updateMatrix();
  51058. }
  51059. uniform.value.copy( map.matrix );
  51060. }
  51061. function refreshFogUniforms( uniforms, fog ) {
  51062. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  51063. if ( fog.isFog ) {
  51064. uniforms.fogNear.value = fog.near;
  51065. uniforms.fogFar.value = fog.far;
  51066. } else if ( fog.isFogExp2 ) {
  51067. uniforms.fogDensity.value = fog.density;
  51068. }
  51069. }
  51070. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  51071. if ( material.isMeshBasicMaterial ) {
  51072. refreshUniformsCommon( uniforms, material );
  51073. } else if ( material.isMeshLambertMaterial ) {
  51074. refreshUniformsCommon( uniforms, material );
  51075. } else if ( material.isMeshToonMaterial ) {
  51076. refreshUniformsCommon( uniforms, material );
  51077. refreshUniformsToon( uniforms, material );
  51078. } else if ( material.isMeshPhongMaterial ) {
  51079. refreshUniformsCommon( uniforms, material );
  51080. refreshUniformsPhong( uniforms, material );
  51081. } else if ( material.isMeshStandardMaterial ) {
  51082. refreshUniformsCommon( uniforms, material );
  51083. refreshUniformsStandard( uniforms, material );
  51084. if ( material.isMeshPhysicalMaterial ) {
  51085. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  51086. }
  51087. } else if ( material.isMeshMatcapMaterial ) {
  51088. refreshUniformsCommon( uniforms, material );
  51089. refreshUniformsMatcap( uniforms, material );
  51090. } else if ( material.isMeshDepthMaterial ) {
  51091. refreshUniformsCommon( uniforms, material );
  51092. } else if ( material.isMeshDistanceMaterial ) {
  51093. refreshUniformsCommon( uniforms, material );
  51094. refreshUniformsDistance( uniforms, material );
  51095. } else if ( material.isMeshNormalMaterial ) {
  51096. refreshUniformsCommon( uniforms, material );
  51097. } else if ( material.isLineBasicMaterial ) {
  51098. refreshUniformsLine( uniforms, material );
  51099. if ( material.isLineDashedMaterial ) {
  51100. refreshUniformsDash( uniforms, material );
  51101. }
  51102. } else if ( material.isPointsMaterial ) {
  51103. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  51104. } else if ( material.isSpriteMaterial ) {
  51105. refreshUniformsSprites( uniforms, material );
  51106. } else if ( material.isShadowMaterial ) {
  51107. uniforms.color.value.copy( material.color );
  51108. uniforms.opacity.value = material.opacity;
  51109. } else if ( material.isShaderMaterial ) {
  51110. material.uniformsNeedUpdate = false; // #15581
  51111. }
  51112. }
  51113. function refreshUniformsCommon( uniforms, material ) {
  51114. uniforms.opacity.value = material.opacity;
  51115. if ( material.color ) {
  51116. uniforms.diffuse.value.copy( material.color );
  51117. }
  51118. if ( material.emissive ) {
  51119. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  51120. }
  51121. if ( material.map ) {
  51122. uniforms.map.value = material.map;
  51123. refreshTransformUniform( material.map, uniforms.mapTransform );
  51124. }
  51125. if ( material.alphaMap ) {
  51126. uniforms.alphaMap.value = material.alphaMap;
  51127. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  51128. }
  51129. if ( material.bumpMap ) {
  51130. uniforms.bumpMap.value = material.bumpMap;
  51131. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  51132. uniforms.bumpScale.value = material.bumpScale;
  51133. if ( material.side === BackSide ) {
  51134. uniforms.bumpScale.value *= -1;
  51135. }
  51136. }
  51137. if ( material.normalMap ) {
  51138. uniforms.normalMap.value = material.normalMap;
  51139. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  51140. uniforms.normalScale.value.copy( material.normalScale );
  51141. if ( material.side === BackSide ) {
  51142. uniforms.normalScale.value.negate();
  51143. }
  51144. }
  51145. if ( material.displacementMap ) {
  51146. uniforms.displacementMap.value = material.displacementMap;
  51147. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  51148. uniforms.displacementScale.value = material.displacementScale;
  51149. uniforms.displacementBias.value = material.displacementBias;
  51150. }
  51151. if ( material.emissiveMap ) {
  51152. uniforms.emissiveMap.value = material.emissiveMap;
  51153. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  51154. }
  51155. if ( material.specularMap ) {
  51156. uniforms.specularMap.value = material.specularMap;
  51157. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  51158. }
  51159. if ( material.alphaTest > 0 ) {
  51160. uniforms.alphaTest.value = material.alphaTest;
  51161. }
  51162. const materialProperties = properties.get( material );
  51163. const envMap = materialProperties.envMap;
  51164. const envMapRotation = materialProperties.envMapRotation;
  51165. if ( envMap ) {
  51166. uniforms.envMap.value = envMap;
  51167. _e1.copy( envMapRotation );
  51168. // accommodate left-handed frame
  51169. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  51170. if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) {
  51171. // environment maps which are not cube render targets or PMREMs follow a different convention
  51172. _e1.y *= -1;
  51173. _e1.z *= -1;
  51174. }
  51175. uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) );
  51176. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  51177. uniforms.reflectivity.value = material.reflectivity;
  51178. uniforms.ior.value = material.ior;
  51179. uniforms.refractionRatio.value = material.refractionRatio;
  51180. }
  51181. if ( material.lightMap ) {
  51182. uniforms.lightMap.value = material.lightMap;
  51183. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  51184. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  51185. }
  51186. if ( material.aoMap ) {
  51187. uniforms.aoMap.value = material.aoMap;
  51188. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  51189. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  51190. }
  51191. }
  51192. function refreshUniformsLine( uniforms, material ) {
  51193. uniforms.diffuse.value.copy( material.color );
  51194. uniforms.opacity.value = material.opacity;
  51195. if ( material.map ) {
  51196. uniforms.map.value = material.map;
  51197. refreshTransformUniform( material.map, uniforms.mapTransform );
  51198. }
  51199. }
  51200. function refreshUniformsDash( uniforms, material ) {
  51201. uniforms.dashSize.value = material.dashSize;
  51202. uniforms.totalSize.value = material.dashSize + material.gapSize;
  51203. uniforms.scale.value = material.scale;
  51204. }
  51205. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  51206. uniforms.diffuse.value.copy( material.color );
  51207. uniforms.opacity.value = material.opacity;
  51208. uniforms.size.value = material.size * pixelRatio;
  51209. uniforms.scale.value = height * 0.5;
  51210. if ( material.map ) {
  51211. uniforms.map.value = material.map;
  51212. refreshTransformUniform( material.map, uniforms.uvTransform );
  51213. }
  51214. if ( material.alphaMap ) {
  51215. uniforms.alphaMap.value = material.alphaMap;
  51216. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  51217. }
  51218. if ( material.alphaTest > 0 ) {
  51219. uniforms.alphaTest.value = material.alphaTest;
  51220. }
  51221. }
  51222. function refreshUniformsSprites( uniforms, material ) {
  51223. uniforms.diffuse.value.copy( material.color );
  51224. uniforms.opacity.value = material.opacity;
  51225. uniforms.rotation.value = material.rotation;
  51226. if ( material.map ) {
  51227. uniforms.map.value = material.map;
  51228. refreshTransformUniform( material.map, uniforms.mapTransform );
  51229. }
  51230. if ( material.alphaMap ) {
  51231. uniforms.alphaMap.value = material.alphaMap;
  51232. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  51233. }
  51234. if ( material.alphaTest > 0 ) {
  51235. uniforms.alphaTest.value = material.alphaTest;
  51236. }
  51237. }
  51238. function refreshUniformsPhong( uniforms, material ) {
  51239. uniforms.specular.value.copy( material.specular );
  51240. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  51241. }
  51242. function refreshUniformsToon( uniforms, material ) {
  51243. if ( material.gradientMap ) {
  51244. uniforms.gradientMap.value = material.gradientMap;
  51245. }
  51246. }
  51247. function refreshUniformsStandard( uniforms, material ) {
  51248. uniforms.metalness.value = material.metalness;
  51249. if ( material.metalnessMap ) {
  51250. uniforms.metalnessMap.value = material.metalnessMap;
  51251. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  51252. }
  51253. uniforms.roughness.value = material.roughness;
  51254. if ( material.roughnessMap ) {
  51255. uniforms.roughnessMap.value = material.roughnessMap;
  51256. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  51257. }
  51258. if ( material.envMap ) {
  51259. //uniforms.envMap.value = material.envMap; // part of uniforms common
  51260. uniforms.envMapIntensity.value = material.envMapIntensity;
  51261. }
  51262. }
  51263. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  51264. uniforms.ior.value = material.ior; // also part of uniforms common
  51265. if ( material.sheen > 0 ) {
  51266. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  51267. uniforms.sheenRoughness.value = material.sheenRoughness;
  51268. if ( material.sheenColorMap ) {
  51269. uniforms.sheenColorMap.value = material.sheenColorMap;
  51270. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  51271. }
  51272. if ( material.sheenRoughnessMap ) {
  51273. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  51274. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  51275. }
  51276. }
  51277. if ( material.clearcoat > 0 ) {
  51278. uniforms.clearcoat.value = material.clearcoat;
  51279. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  51280. if ( material.clearcoatMap ) {
  51281. uniforms.clearcoatMap.value = material.clearcoatMap;
  51282. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  51283. }
  51284. if ( material.clearcoatRoughnessMap ) {
  51285. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  51286. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  51287. }
  51288. if ( material.clearcoatNormalMap ) {
  51289. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  51290. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  51291. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  51292. if ( material.side === BackSide ) {
  51293. uniforms.clearcoatNormalScale.value.negate();
  51294. }
  51295. }
  51296. }
  51297. if ( material.dispersion > 0 ) {
  51298. uniforms.dispersion.value = material.dispersion;
  51299. }
  51300. if ( material.iridescence > 0 ) {
  51301. uniforms.iridescence.value = material.iridescence;
  51302. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  51303. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  51304. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  51305. if ( material.iridescenceMap ) {
  51306. uniforms.iridescenceMap.value = material.iridescenceMap;
  51307. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  51308. }
  51309. if ( material.iridescenceThicknessMap ) {
  51310. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  51311. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  51312. }
  51313. }
  51314. if ( material.transmission > 0 ) {
  51315. uniforms.transmission.value = material.transmission;
  51316. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  51317. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  51318. if ( material.transmissionMap ) {
  51319. uniforms.transmissionMap.value = material.transmissionMap;
  51320. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  51321. }
  51322. uniforms.thickness.value = material.thickness;
  51323. if ( material.thicknessMap ) {
  51324. uniforms.thicknessMap.value = material.thicknessMap;
  51325. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  51326. }
  51327. uniforms.attenuationDistance.value = material.attenuationDistance;
  51328. uniforms.attenuationColor.value.copy( material.attenuationColor );
  51329. }
  51330. if ( material.anisotropy > 0 ) {
  51331. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  51332. if ( material.anisotropyMap ) {
  51333. uniforms.anisotropyMap.value = material.anisotropyMap;
  51334. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  51335. }
  51336. }
  51337. uniforms.specularIntensity.value = material.specularIntensity;
  51338. uniforms.specularColor.value.copy( material.specularColor );
  51339. if ( material.specularColorMap ) {
  51340. uniforms.specularColorMap.value = material.specularColorMap;
  51341. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  51342. }
  51343. if ( material.specularIntensityMap ) {
  51344. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  51345. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  51346. }
  51347. }
  51348. function refreshUniformsMatcap( uniforms, material ) {
  51349. if ( material.matcap ) {
  51350. uniforms.matcap.value = material.matcap;
  51351. }
  51352. }
  51353. function refreshUniformsDistance( uniforms, material ) {
  51354. const light = properties.get( material ).light;
  51355. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  51356. uniforms.nearDistance.value = light.shadow.camera.near;
  51357. uniforms.farDistance.value = light.shadow.camera.far;
  51358. }
  51359. return {
  51360. refreshFogUniforms: refreshFogUniforms,
  51361. refreshMaterialUniforms: refreshMaterialUniforms
  51362. };
  51363. }
  51364. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  51365. let buffers = {};
  51366. let updateList = {};
  51367. let allocatedBindingPoints = [];
  51368. const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program
  51369. function bind( uniformsGroup, program ) {
  51370. const webglProgram = program.program;
  51371. state.uniformBlockBinding( uniformsGroup, webglProgram );
  51372. }
  51373. function update( uniformsGroup, program ) {
  51374. let buffer = buffers[ uniformsGroup.id ];
  51375. if ( buffer === undefined ) {
  51376. prepareUniformsGroup( uniformsGroup );
  51377. buffer = createBuffer( uniformsGroup );
  51378. buffers[ uniformsGroup.id ] = buffer;
  51379. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  51380. }
  51381. // ensure to update the binding points/block indices mapping for this program
  51382. const webglProgram = program.program;
  51383. state.updateUBOMapping( uniformsGroup, webglProgram );
  51384. // update UBO once per frame
  51385. const frame = info.render.frame;
  51386. if ( updateList[ uniformsGroup.id ] !== frame ) {
  51387. updateBufferData( uniformsGroup );
  51388. updateList[ uniformsGroup.id ] = frame;
  51389. }
  51390. }
  51391. function createBuffer( uniformsGroup ) {
  51392. // the setup of an UBO is independent of a particular shader program but global
  51393. const bindingPointIndex = allocateBindingPointIndex();
  51394. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  51395. const buffer = gl.createBuffer();
  51396. const size = uniformsGroup.__size;
  51397. const usage = uniformsGroup.usage;
  51398. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  51399. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  51400. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  51401. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  51402. return buffer;
  51403. }
  51404. function allocateBindingPointIndex() {
  51405. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  51406. if ( allocatedBindingPoints.indexOf( i ) === -1 ) {
  51407. allocatedBindingPoints.push( i );
  51408. return i;
  51409. }
  51410. }
  51411. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  51412. return 0;
  51413. }
  51414. function updateBufferData( uniformsGroup ) {
  51415. const buffer = buffers[ uniformsGroup.id ];
  51416. const uniforms = uniformsGroup.uniforms;
  51417. const cache = uniformsGroup.__cache;
  51418. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  51419. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  51420. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  51421. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  51422. const uniform = uniformArray[ j ];
  51423. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  51424. const offset = uniform.__offset;
  51425. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  51426. let arrayOffset = 0;
  51427. for ( let k = 0; k < values.length; k ++ ) {
  51428. const value = values[ k ];
  51429. const info = getUniformSize( value );
  51430. // TODO add integer and struct support
  51431. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  51432. uniform.__data[ 0 ] = value;
  51433. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  51434. } else if ( value.isMatrix3 ) {
  51435. // manually converting 3x3 to 3x4
  51436. uniform.__data[ 0 ] = value.elements[ 0 ];
  51437. uniform.__data[ 1 ] = value.elements[ 1 ];
  51438. uniform.__data[ 2 ] = value.elements[ 2 ];
  51439. uniform.__data[ 3 ] = 0;
  51440. uniform.__data[ 4 ] = value.elements[ 3 ];
  51441. uniform.__data[ 5 ] = value.elements[ 4 ];
  51442. uniform.__data[ 6 ] = value.elements[ 5 ];
  51443. uniform.__data[ 7 ] = 0;
  51444. uniform.__data[ 8 ] = value.elements[ 6 ];
  51445. uniform.__data[ 9 ] = value.elements[ 7 ];
  51446. uniform.__data[ 10 ] = value.elements[ 8 ];
  51447. uniform.__data[ 11 ] = 0;
  51448. } else {
  51449. value.toArray( uniform.__data, arrayOffset );
  51450. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  51451. }
  51452. }
  51453. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  51454. }
  51455. }
  51456. }
  51457. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  51458. }
  51459. function hasUniformChanged( uniform, index, indexArray, cache ) {
  51460. const value = uniform.value;
  51461. const indexString = index + '_' + indexArray;
  51462. if ( cache[ indexString ] === undefined ) {
  51463. // cache entry does not exist so far
  51464. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  51465. cache[ indexString ] = value;
  51466. } else {
  51467. cache[ indexString ] = value.clone();
  51468. }
  51469. return true;
  51470. } else {
  51471. const cachedObject = cache[ indexString ];
  51472. // compare current value with cached entry
  51473. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  51474. if ( cachedObject !== value ) {
  51475. cache[ indexString ] = value;
  51476. return true;
  51477. }
  51478. } else {
  51479. if ( cachedObject.equals( value ) === false ) {
  51480. cachedObject.copy( value );
  51481. return true;
  51482. }
  51483. }
  51484. }
  51485. return false;
  51486. }
  51487. function prepareUniformsGroup( uniformsGroup ) {
  51488. // determine total buffer size according to the STD140 layout
  51489. // Hint: STD140 is the only supported layout in WebGL 2
  51490. const uniforms = uniformsGroup.uniforms;
  51491. let offset = 0; // global buffer offset in bytes
  51492. const chunkSize = 16; // size of a chunk in bytes
  51493. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  51494. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  51495. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  51496. const uniform = uniformArray[ j ];
  51497. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  51498. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  51499. const value = values[ k ];
  51500. const info = getUniformSize( value );
  51501. const chunkOffset = offset % chunkSize; // offset in the current chunk
  51502. const chunkPadding = chunkOffset % info.boundary; // required padding to match boundary
  51503. const chunkStart = chunkOffset + chunkPadding; // the start position in the current chunk for the data
  51504. offset += chunkPadding;
  51505. // Check for chunk overflow
  51506. if ( chunkStart !== 0 && ( chunkSize - chunkStart ) < info.storage ) {
  51507. // Add padding and adjust offset
  51508. offset += ( chunkSize - chunkStart );
  51509. }
  51510. // the following two properties will be used for partial buffer updates
  51511. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  51512. uniform.__offset = offset;
  51513. // Update the global offset
  51514. offset += info.storage;
  51515. }
  51516. }
  51517. }
  51518. // ensure correct final padding
  51519. const chunkOffset = offset % chunkSize;
  51520. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  51521. //
  51522. uniformsGroup.__size = offset;
  51523. uniformsGroup.__cache = {};
  51524. return this;
  51525. }
  51526. function getUniformSize( value ) {
  51527. const info = {
  51528. boundary: 0, // bytes
  51529. storage: 0 // bytes
  51530. };
  51531. // determine sizes according to STD140
  51532. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  51533. // float/int/bool
  51534. info.boundary = 4;
  51535. info.storage = 4;
  51536. } else if ( value.isVector2 ) {
  51537. // vec2
  51538. info.boundary = 8;
  51539. info.storage = 8;
  51540. } else if ( value.isVector3 || value.isColor ) {
  51541. // vec3
  51542. info.boundary = 16;
  51543. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  51544. } else if ( value.isVector4 ) {
  51545. // vec4
  51546. info.boundary = 16;
  51547. info.storage = 16;
  51548. } else if ( value.isMatrix3 ) {
  51549. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  51550. info.boundary = 48;
  51551. info.storage = 48;
  51552. } else if ( value.isMatrix4 ) {
  51553. // mat4
  51554. info.boundary = 64;
  51555. info.storage = 64;
  51556. } else if ( value.isTexture ) {
  51557. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  51558. } else {
  51559. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  51560. }
  51561. return info;
  51562. }
  51563. function onUniformsGroupsDispose( event ) {
  51564. const uniformsGroup = event.target;
  51565. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  51566. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  51567. allocatedBindingPoints.splice( index, 1 );
  51568. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  51569. delete buffers[ uniformsGroup.id ];
  51570. delete updateList[ uniformsGroup.id ];
  51571. }
  51572. function dispose() {
  51573. for ( const id in buffers ) {
  51574. gl.deleteBuffer( buffers[ id ] );
  51575. }
  51576. allocatedBindingPoints = [];
  51577. buffers = {};
  51578. updateList = {};
  51579. }
  51580. return {
  51581. bind: bind,
  51582. update: update,
  51583. dispose: dispose
  51584. };
  51585. }
  51586. /**
  51587. * This renderer uses WebGL 2 to display scenes.
  51588. *
  51589. * WebGL 1 is not supported since `r163`.
  51590. */
  51591. class WebGLRenderer {
  51592. /**
  51593. * Constructs a new WebGL renderer.
  51594. *
  51595. * @param {WebGLRenderer~Options} [parameters] - The configuration parameter.
  51596. */
  51597. constructor( parameters = {} ) {
  51598. const {
  51599. canvas = createCanvasElement(),
  51600. context = null,
  51601. depth = true,
  51602. stencil = false,
  51603. alpha = false,
  51604. antialias = false,
  51605. premultipliedAlpha = true,
  51606. preserveDrawingBuffer = false,
  51607. powerPreference = 'default',
  51608. failIfMajorPerformanceCaveat = false,
  51609. reversedDepthBuffer = false,
  51610. } = parameters;
  51611. /**
  51612. * This flag can be used for type testing.
  51613. *
  51614. * @type {boolean}
  51615. * @readonly
  51616. * @default true
  51617. */
  51618. this.isWebGLRenderer = true;
  51619. let _alpha;
  51620. if ( context !== null ) {
  51621. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  51622. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  51623. }
  51624. _alpha = context.getContextAttributes().alpha;
  51625. } else {
  51626. _alpha = alpha;
  51627. }
  51628. const uintClearColor = new Uint32Array( 4 );
  51629. const intClearColor = new Int32Array( 4 );
  51630. let currentRenderList = null;
  51631. let currentRenderState = null;
  51632. // render() can be called from within a callback triggered by another render.
  51633. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  51634. const renderListStack = [];
  51635. const renderStateStack = [];
  51636. // public properties
  51637. /**
  51638. * A canvas where the renderer draws its output.This is automatically created by the renderer
  51639. * in the constructor (if not provided already); you just need to add it to your page like so:
  51640. * ```js
  51641. * document.body.appendChild( renderer.domElement );
  51642. * ```
  51643. *
  51644. * @type {DOMElement}
  51645. */
  51646. this.domElement = canvas;
  51647. /**
  51648. * A object with debug configuration settings.
  51649. *
  51650. * - `checkShaderErrors`: If it is `true`, defines whether material shader programs are
  51651. * checked for errors during compilation and linkage process. It may be useful to disable
  51652. * this check in production for performance gain. It is strongly recommended to keep these
  51653. * checks enabled during development. If the shader does not compile and link - it will not
  51654. * work and associated material will not render.
  51655. * - `onShaderError(gl, program, glVertexShader,glFragmentShader)`: A callback function that
  51656. * can be used for custom error reporting. The callback receives the WebGL context, an instance
  51657. * of WebGLProgram as well two instances of WebGLShader representing the vertex and fragment shader.
  51658. * Assigning a custom function disables the default error reporting.
  51659. *
  51660. * @type {Object}
  51661. */
  51662. this.debug = {
  51663. /**
  51664. * Enables error checking and reporting when shader programs are being compiled.
  51665. * @type {boolean}
  51666. */
  51667. checkShaderErrors: true,
  51668. /**
  51669. * Callback for custom error reporting.
  51670. * @type {?Function}
  51671. */
  51672. onShaderError: null
  51673. };
  51674. // clearing
  51675. /**
  51676. * Whether the renderer should automatically clear its output before rendering a frame or not.
  51677. *
  51678. * @type {boolean}
  51679. * @default true
  51680. */
  51681. this.autoClear = true;
  51682. /**
  51683. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  51684. * the color buffer or not.
  51685. *
  51686. * @type {boolean}
  51687. * @default true
  51688. */
  51689. this.autoClearColor = true;
  51690. /**
  51691. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  51692. * the depth buffer or not.
  51693. *
  51694. * @type {boolean}
  51695. * @default true
  51696. */
  51697. this.autoClearDepth = true;
  51698. /**
  51699. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  51700. * the stencil buffer or not.
  51701. *
  51702. * @type {boolean}
  51703. * @default true
  51704. */
  51705. this.autoClearStencil = true;
  51706. // scene graph
  51707. /**
  51708. * Whether the renderer should sort objects or not.
  51709. *
  51710. * Note: Sorting is used to attempt to properly render objects that have some
  51711. * degree of transparency. By definition, sorting objects may not work in all
  51712. * cases. Depending on the needs of application, it may be necessary to turn
  51713. * off sorting and use other methods to deal with transparency rendering e.g.
  51714. * manually determining each object's rendering order.
  51715. *
  51716. * @type {boolean}
  51717. * @default true
  51718. */
  51719. this.sortObjects = true;
  51720. // user-defined clipping
  51721. /**
  51722. * User-defined clipping planes specified in world space. These planes apply globally.
  51723. * Points in space whose dot product with the plane is negative are cut away.
  51724. *
  51725. * @type {Array<Plane>}
  51726. */
  51727. this.clippingPlanes = [];
  51728. /**
  51729. * Whether the renderer respects object-level clipping planes or not.
  51730. *
  51731. * @type {boolean}
  51732. * @default false
  51733. */
  51734. this.localClippingEnabled = false;
  51735. // tone mapping
  51736. /**
  51737. * The tone mapping technique of the renderer.
  51738. *
  51739. * @type {(NoToneMapping|LinearToneMapping|ReinhardToneMapping|CineonToneMapping|ACESFilmicToneMapping|CustomToneMapping|AgXToneMapping|NeutralToneMapping)}
  51740. * @default NoToneMapping
  51741. */
  51742. this.toneMapping = NoToneMapping;
  51743. /**
  51744. * Exposure level of tone mapping.
  51745. *
  51746. * @type {number}
  51747. * @default 1
  51748. */
  51749. this.toneMappingExposure = 1.0;
  51750. // transmission
  51751. /**
  51752. * The normalized resolution scale for the transmission render target, measured in percentage
  51753. * of viewport dimensions. Lowering this value can result in significant performance improvements
  51754. * when using {@link MeshPhysicalMaterial#transmission}.
  51755. *
  51756. * @type {number}
  51757. * @default 1
  51758. */
  51759. this.transmissionResolutionScale = 1.0;
  51760. // internal properties
  51761. const _this = this;
  51762. let _isContextLost = false;
  51763. // internal state cache
  51764. this._outputColorSpace = SRGBColorSpace;
  51765. let _currentActiveCubeFace = 0;
  51766. let _currentActiveMipmapLevel = 0;
  51767. let _currentRenderTarget = null;
  51768. let _currentMaterialId = -1;
  51769. let _currentCamera = null;
  51770. const _currentViewport = new Vector4();
  51771. const _currentScissor = new Vector4();
  51772. let _currentScissorTest = null;
  51773. const _currentClearColor = new Color( 0x000000 );
  51774. let _currentClearAlpha = 0;
  51775. //
  51776. let _width = canvas.width;
  51777. let _height = canvas.height;
  51778. let _pixelRatio = 1;
  51779. let _opaqueSort = null;
  51780. let _transparentSort = null;
  51781. const _viewport = new Vector4( 0, 0, _width, _height );
  51782. const _scissor = new Vector4( 0, 0, _width, _height );
  51783. let _scissorTest = false;
  51784. // frustum
  51785. const _frustum = new Frustum();
  51786. // clipping
  51787. let _clippingEnabled = false;
  51788. let _localClippingEnabled = false;
  51789. // camera matrices cache
  51790. const _projScreenMatrix = new Matrix4();
  51791. const _vector3 = new Vector3();
  51792. const _vector4 = new Vector4();
  51793. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  51794. let _renderBackground = false;
  51795. function getTargetPixelRatio() {
  51796. return _currentRenderTarget === null ? _pixelRatio : 1;
  51797. }
  51798. // initialize
  51799. let _gl = context;
  51800. function getContext( contextName, contextAttributes ) {
  51801. return canvas.getContext( contextName, contextAttributes );
  51802. }
  51803. try {
  51804. const contextAttributes = {
  51805. alpha: true,
  51806. depth,
  51807. stencil,
  51808. antialias,
  51809. premultipliedAlpha,
  51810. preserveDrawingBuffer,
  51811. powerPreference,
  51812. failIfMajorPerformanceCaveat,
  51813. };
  51814. // OffscreenCanvas does not have setAttribute, see #22811
  51815. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  51816. // event listeners must be registered before WebGL context is created, see #12753
  51817. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  51818. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  51819. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  51820. if ( _gl === null ) {
  51821. const contextName = 'webgl2';
  51822. _gl = getContext( contextName, contextAttributes );
  51823. if ( _gl === null ) {
  51824. if ( getContext( contextName ) ) {
  51825. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  51826. } else {
  51827. throw new Error( 'Error creating WebGL context.' );
  51828. }
  51829. }
  51830. }
  51831. } catch ( error ) {
  51832. console.error( 'THREE.WebGLRenderer: ' + error.message );
  51833. throw error;
  51834. }
  51835. let extensions, capabilities, state, info;
  51836. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  51837. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  51838. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  51839. let utils, bindingStates, uniformsGroups;
  51840. function initGLContext() {
  51841. extensions = new WebGLExtensions( _gl );
  51842. extensions.init();
  51843. utils = new WebGLUtils( _gl, extensions );
  51844. capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils );
  51845. state = new WebGLState( _gl, extensions );
  51846. if ( capabilities.reversedDepthBuffer && reversedDepthBuffer ) {
  51847. state.buffers.depth.setReversed( true );
  51848. }
  51849. info = new WebGLInfo( _gl );
  51850. properties = new WebGLProperties();
  51851. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  51852. cubemaps = new WebGLCubeMaps( _this );
  51853. cubeuvmaps = new WebGLCubeUVMaps( _this );
  51854. attributes = new WebGLAttributes( _gl );
  51855. bindingStates = new WebGLBindingStates( _gl, attributes );
  51856. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  51857. objects = new WebGLObjects( _gl, geometries, attributes, info );
  51858. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  51859. clipping = new WebGLClipping( properties );
  51860. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  51861. materials = new WebGLMaterials( _this, properties );
  51862. renderLists = new WebGLRenderLists();
  51863. renderStates = new WebGLRenderStates( extensions );
  51864. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  51865. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  51866. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  51867. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  51868. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  51869. info.programs = programCache.programs;
  51870. /**
  51871. * Holds details about the capabilities of the current rendering context.
  51872. *
  51873. * @name WebGLRenderer#capabilities
  51874. * @type {WebGLRenderer~Capabilities}
  51875. */
  51876. _this.capabilities = capabilities;
  51877. /**
  51878. * Provides methods for retrieving and testing WebGL extensions.
  51879. *
  51880. * - `get(extensionName:string)`: Used to check whether a WebGL extension is supported
  51881. * and return the extension object if available.
  51882. * - `has(extensionName:string)`: returns `true` if the extension is supported.
  51883. *
  51884. * @name WebGLRenderer#extensions
  51885. * @type {Object}
  51886. */
  51887. _this.extensions = extensions;
  51888. /**
  51889. * Used to track properties of other objects like native WebGL objects.
  51890. *
  51891. * @name WebGLRenderer#properties
  51892. * @type {Object}
  51893. */
  51894. _this.properties = properties;
  51895. /**
  51896. * Manages the render lists of the renderer.
  51897. *
  51898. * @name WebGLRenderer#renderLists
  51899. * @type {Object}
  51900. */
  51901. _this.renderLists = renderLists;
  51902. /**
  51903. * Interface for managing shadows.
  51904. *
  51905. * @name WebGLRenderer#shadowMap
  51906. * @type {WebGLRenderer~ShadowMap}
  51907. */
  51908. _this.shadowMap = shadowMap;
  51909. /**
  51910. * Interface for managing the WebGL state.
  51911. *
  51912. * @name WebGLRenderer#state
  51913. * @type {Object}
  51914. */
  51915. _this.state = state;
  51916. /**
  51917. * Holds a series of statistical information about the GPU memory
  51918. * and the rendering process. Useful for debugging and monitoring.
  51919. *
  51920. * By default these data are reset at each render call but when having
  51921. * multiple render passes per frame (e.g. when using post processing) it can
  51922. * be preferred to reset with a custom pattern. First, set `autoReset` to
  51923. * `false`.
  51924. * ```js
  51925. * renderer.info.autoReset = false;
  51926. * ```
  51927. * Call `reset()` whenever you have finished to render a single frame.
  51928. * ```js
  51929. * renderer.info.reset();
  51930. * ```
  51931. *
  51932. * @name WebGLRenderer#info
  51933. * @type {WebGLRenderer~Info}
  51934. */
  51935. _this.info = info;
  51936. }
  51937. initGLContext();
  51938. // xr
  51939. const xr = new WebXRManager( _this, _gl );
  51940. /**
  51941. * A reference to the XR manager.
  51942. *
  51943. * @type {WebXRManager}
  51944. */
  51945. this.xr = xr;
  51946. /**
  51947. * Returns the rendering context.
  51948. *
  51949. * @return {WebGL2RenderingContext} The rendering context.
  51950. */
  51951. this.getContext = function () {
  51952. return _gl;
  51953. };
  51954. /**
  51955. * Returns the rendering context attributes.
  51956. *
  51957. * @return {WebGLContextAttributes} The rendering context attributes.
  51958. */
  51959. this.getContextAttributes = function () {
  51960. return _gl.getContextAttributes();
  51961. };
  51962. /**
  51963. * Simulates a loss of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  51964. */
  51965. this.forceContextLoss = function () {
  51966. const extension = extensions.get( 'WEBGL_lose_context' );
  51967. if ( extension ) extension.loseContext();
  51968. };
  51969. /**
  51970. * Simulates a restore of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  51971. */
  51972. this.forceContextRestore = function () {
  51973. const extension = extensions.get( 'WEBGL_lose_context' );
  51974. if ( extension ) extension.restoreContext();
  51975. };
  51976. /**
  51977. * Returns the pixel ratio.
  51978. *
  51979. * @return {number} The pixel ratio.
  51980. */
  51981. this.getPixelRatio = function () {
  51982. return _pixelRatio;
  51983. };
  51984. /**
  51985. * Sets the given pixel ratio and resizes the canvas if necessary.
  51986. *
  51987. * @param {number} value - The pixel ratio.
  51988. */
  51989. this.setPixelRatio = function ( value ) {
  51990. if ( value === undefined ) return;
  51991. _pixelRatio = value;
  51992. this.setSize( _width, _height, false );
  51993. };
  51994. /**
  51995. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  51996. *
  51997. * @param {Vector2} target - The method writes the result in this target object.
  51998. * @return {Vector2} The renderer's size in logical pixels.
  51999. */
  52000. this.getSize = function ( target ) {
  52001. return target.set( _width, _height );
  52002. };
  52003. /**
  52004. * Resizes the output canvas to (width, height) with device pixel ratio taken
  52005. * into account, and also sets the viewport to fit that size, starting in (0,
  52006. * 0). Setting `updateStyle` to false prevents any style changes to the output canvas.
  52007. *
  52008. * @param {number} width - The width in logical pixels.
  52009. * @param {number} height - The height in logical pixels.
  52010. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  52011. */
  52012. this.setSize = function ( width, height, updateStyle = true ) {
  52013. if ( xr.isPresenting ) {
  52014. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  52015. return;
  52016. }
  52017. _width = width;
  52018. _height = height;
  52019. canvas.width = Math.floor( width * _pixelRatio );
  52020. canvas.height = Math.floor( height * _pixelRatio );
  52021. if ( updateStyle === true ) {
  52022. canvas.style.width = width + 'px';
  52023. canvas.style.height = height + 'px';
  52024. }
  52025. this.setViewport( 0, 0, width, height );
  52026. };
  52027. /**
  52028. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  52029. *
  52030. * @param {Vector2} target - The method writes the result in this target object.
  52031. * @return {Vector2} The drawing buffer size.
  52032. */
  52033. this.getDrawingBufferSize = function ( target ) {
  52034. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  52035. };
  52036. /**
  52037. * This method allows to define the drawing buffer size by specifying
  52038. * width, height and pixel ratio all at once. The size of the drawing
  52039. * buffer is computed with this formula:
  52040. * ```js
  52041. * size.x = width * pixelRatio;
  52042. * size.y = height * pixelRatio;
  52043. * ```
  52044. *
  52045. * @param {number} width - The width in logical pixels.
  52046. * @param {number} height - The height in logical pixels.
  52047. * @param {number} pixelRatio - The pixel ratio.
  52048. */
  52049. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  52050. _width = width;
  52051. _height = height;
  52052. _pixelRatio = pixelRatio;
  52053. canvas.width = Math.floor( width * pixelRatio );
  52054. canvas.height = Math.floor( height * pixelRatio );
  52055. this.setViewport( 0, 0, width, height );
  52056. };
  52057. /**
  52058. * Returns the current viewport definition.
  52059. *
  52060. * @param {Vector2} target - The method writes the result in this target object.
  52061. * @return {Vector2} The current viewport definition.
  52062. */
  52063. this.getCurrentViewport = function ( target ) {
  52064. return target.copy( _currentViewport );
  52065. };
  52066. /**
  52067. * Returns the viewport definition.
  52068. *
  52069. * @param {Vector4} target - The method writes the result in this target object.
  52070. * @return {Vector4} The viewport definition.
  52071. */
  52072. this.getViewport = function ( target ) {
  52073. return target.copy( _viewport );
  52074. };
  52075. /**
  52076. * Sets the viewport to render from `(x, y)` to `(x + width, y + height)`.
  52077. *
  52078. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  52079. * Or alternatively a four-component vector specifying all the parameters of the viewport.
  52080. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  52081. * @param {number} width - The width of the viewport in logical pixel unit.
  52082. * @param {number} height - The height of the viewport in logical pixel unit.
  52083. */
  52084. this.setViewport = function ( x, y, width, height ) {
  52085. if ( x.isVector4 ) {
  52086. _viewport.set( x.x, x.y, x.z, x.w );
  52087. } else {
  52088. _viewport.set( x, y, width, height );
  52089. }
  52090. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  52091. };
  52092. /**
  52093. * Returns the scissor region.
  52094. *
  52095. * @param {Vector4} target - The method writes the result in this target object.
  52096. * @return {Vector4} The scissor region.
  52097. */
  52098. this.getScissor = function ( target ) {
  52099. return target.copy( _scissor );
  52100. };
  52101. /**
  52102. * Sets the scissor region to render from `(x, y)` to `(x + width, y + height)`.
  52103. *
  52104. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  52105. * Or alternatively a four-component vector specifying all the parameters of the scissor region.
  52106. * @param {number} y - The vertical coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  52107. * @param {number} width - The width of the scissor region in logical pixel unit.
  52108. * @param {number} height - The height of the scissor region in logical pixel unit.
  52109. */
  52110. this.setScissor = function ( x, y, width, height ) {
  52111. if ( x.isVector4 ) {
  52112. _scissor.set( x.x, x.y, x.z, x.w );
  52113. } else {
  52114. _scissor.set( x, y, width, height );
  52115. }
  52116. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  52117. };
  52118. /**
  52119. * Returns `true` if the scissor test is enabled.
  52120. *
  52121. * @return {boolean} Whether the scissor test is enabled or not.
  52122. */
  52123. this.getScissorTest = function () {
  52124. return _scissorTest;
  52125. };
  52126. /**
  52127. * Enable or disable the scissor test. When this is enabled, only the pixels
  52128. * within the defined scissor area will be affected by further renderer
  52129. * actions.
  52130. *
  52131. * @param {boolean} boolean - Whether the scissor test is enabled or not.
  52132. */
  52133. this.setScissorTest = function ( boolean ) {
  52134. state.setScissorTest( _scissorTest = boolean );
  52135. };
  52136. /**
  52137. * Sets a custom opaque sort function for the render lists. Pass `null`
  52138. * to use the default `painterSortStable` function.
  52139. *
  52140. * @param {?Function} method - The opaque sort function.
  52141. */
  52142. this.setOpaqueSort = function ( method ) {
  52143. _opaqueSort = method;
  52144. };
  52145. /**
  52146. * Sets a custom transparent sort function for the render lists. Pass `null`
  52147. * to use the default `reversePainterSortStable` function.
  52148. *
  52149. * @param {?Function} method - The opaque sort function.
  52150. */
  52151. this.setTransparentSort = function ( method ) {
  52152. _transparentSort = method;
  52153. };
  52154. // Clearing
  52155. /**
  52156. * Returns the clear color.
  52157. *
  52158. * @param {Color} target - The method writes the result in this target object.
  52159. * @return {Color} The clear color.
  52160. */
  52161. this.getClearColor = function ( target ) {
  52162. return target.copy( background.getClearColor() );
  52163. };
  52164. /**
  52165. * Sets the clear color and alpha.
  52166. *
  52167. * @param {Color} color - The clear color.
  52168. * @param {number} [alpha=1] - The clear alpha.
  52169. */
  52170. this.setClearColor = function () {
  52171. background.setClearColor( ...arguments );
  52172. };
  52173. /**
  52174. * Returns the clear alpha. Ranges within `[0,1]`.
  52175. *
  52176. * @return {number} The clear alpha.
  52177. */
  52178. this.getClearAlpha = function () {
  52179. return background.getClearAlpha();
  52180. };
  52181. /**
  52182. * Sets the clear alpha.
  52183. *
  52184. * @param {number} alpha - The clear alpha.
  52185. */
  52186. this.setClearAlpha = function () {
  52187. background.setClearAlpha( ...arguments );
  52188. };
  52189. /**
  52190. * Tells the renderer to clear its color, depth or stencil drawing buffer(s).
  52191. * This method initializes the buffers to the current clear color values.
  52192. *
  52193. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  52194. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  52195. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  52196. */
  52197. this.clear = function ( color = true, depth = true, stencil = true ) {
  52198. let bits = 0;
  52199. if ( color ) {
  52200. // check if we're trying to clear an integer target
  52201. let isIntegerFormat = false;
  52202. if ( _currentRenderTarget !== null ) {
  52203. const targetFormat = _currentRenderTarget.texture.format;
  52204. isIntegerFormat = targetFormat === RGBAIntegerFormat ||
  52205. targetFormat === RGIntegerFormat ||
  52206. targetFormat === RedIntegerFormat;
  52207. }
  52208. // use the appropriate clear functions to clear the target if it's a signed
  52209. // or unsigned integer target
  52210. if ( isIntegerFormat ) {
  52211. const targetType = _currentRenderTarget.texture.type;
  52212. const isUnsignedType = targetType === UnsignedByteType ||
  52213. targetType === UnsignedIntType ||
  52214. targetType === UnsignedShortType ||
  52215. targetType === UnsignedInt248Type ||
  52216. targetType === UnsignedShort4444Type ||
  52217. targetType === UnsignedShort5551Type;
  52218. const clearColor = background.getClearColor();
  52219. const a = background.getClearAlpha();
  52220. const r = clearColor.r;
  52221. const g = clearColor.g;
  52222. const b = clearColor.b;
  52223. if ( isUnsignedType ) {
  52224. uintClearColor[ 0 ] = r;
  52225. uintClearColor[ 1 ] = g;
  52226. uintClearColor[ 2 ] = b;
  52227. uintClearColor[ 3 ] = a;
  52228. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  52229. } else {
  52230. intClearColor[ 0 ] = r;
  52231. intClearColor[ 1 ] = g;
  52232. intClearColor[ 2 ] = b;
  52233. intClearColor[ 3 ] = a;
  52234. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  52235. }
  52236. } else {
  52237. bits |= _gl.COLOR_BUFFER_BIT;
  52238. }
  52239. }
  52240. if ( depth ) {
  52241. bits |= _gl.DEPTH_BUFFER_BIT;
  52242. }
  52243. if ( stencil ) {
  52244. bits |= _gl.STENCIL_BUFFER_BIT;
  52245. this.state.buffers.stencil.setMask( 0xffffffff );
  52246. }
  52247. _gl.clear( bits );
  52248. };
  52249. /**
  52250. * Clears the color buffer. Equivalent to calling `renderer.clear( true, false, false )`.
  52251. */
  52252. this.clearColor = function () {
  52253. this.clear( true, false, false );
  52254. };
  52255. /**
  52256. * Clears the depth buffer. Equivalent to calling `renderer.clear( false, true, false )`.
  52257. */
  52258. this.clearDepth = function () {
  52259. this.clear( false, true, false );
  52260. };
  52261. /**
  52262. * Clears the stencil buffer. Equivalent to calling `renderer.clear( false, false, true )`.
  52263. */
  52264. this.clearStencil = function () {
  52265. this.clear( false, false, true );
  52266. };
  52267. /**
  52268. * Frees the GPU-related resources allocated by this instance. Call this
  52269. * method whenever this instance is no longer used in your app.
  52270. */
  52271. this.dispose = function () {
  52272. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  52273. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  52274. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  52275. background.dispose();
  52276. renderLists.dispose();
  52277. renderStates.dispose();
  52278. properties.dispose();
  52279. cubemaps.dispose();
  52280. cubeuvmaps.dispose();
  52281. objects.dispose();
  52282. bindingStates.dispose();
  52283. uniformsGroups.dispose();
  52284. programCache.dispose();
  52285. xr.dispose();
  52286. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  52287. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  52288. animation.stop();
  52289. };
  52290. // Events
  52291. function onContextLost( event ) {
  52292. event.preventDefault();
  52293. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  52294. _isContextLost = true;
  52295. }
  52296. function onContextRestore( /* event */ ) {
  52297. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  52298. _isContextLost = false;
  52299. const infoAutoReset = info.autoReset;
  52300. const shadowMapEnabled = shadowMap.enabled;
  52301. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  52302. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  52303. const shadowMapType = shadowMap.type;
  52304. initGLContext();
  52305. info.autoReset = infoAutoReset;
  52306. shadowMap.enabled = shadowMapEnabled;
  52307. shadowMap.autoUpdate = shadowMapAutoUpdate;
  52308. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  52309. shadowMap.type = shadowMapType;
  52310. }
  52311. function onContextCreationError( event ) {
  52312. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  52313. }
  52314. function onMaterialDispose( event ) {
  52315. const material = event.target;
  52316. material.removeEventListener( 'dispose', onMaterialDispose );
  52317. deallocateMaterial( material );
  52318. }
  52319. // Buffer deallocation
  52320. function deallocateMaterial( material ) {
  52321. releaseMaterialProgramReferences( material );
  52322. properties.remove( material );
  52323. }
  52324. function releaseMaterialProgramReferences( material ) {
  52325. const programs = properties.get( material ).programs;
  52326. if ( programs !== undefined ) {
  52327. programs.forEach( function ( program ) {
  52328. programCache.releaseProgram( program );
  52329. } );
  52330. if ( material.isShaderMaterial ) {
  52331. programCache.releaseShaderCache( material );
  52332. }
  52333. }
  52334. }
  52335. // Buffer rendering
  52336. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  52337. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  52338. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  52339. const program = setProgram( camera, scene, geometry, material, object );
  52340. state.setMaterial( material, frontFaceCW );
  52341. //
  52342. let index = geometry.index;
  52343. let rangeFactor = 1;
  52344. if ( material.wireframe === true ) {
  52345. index = geometries.getWireframeAttribute( geometry );
  52346. if ( index === undefined ) return;
  52347. rangeFactor = 2;
  52348. }
  52349. //
  52350. const drawRange = geometry.drawRange;
  52351. const position = geometry.attributes.position;
  52352. let drawStart = drawRange.start * rangeFactor;
  52353. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  52354. if ( group !== null ) {
  52355. drawStart = Math.max( drawStart, group.start * rangeFactor );
  52356. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  52357. }
  52358. if ( index !== null ) {
  52359. drawStart = Math.max( drawStart, 0 );
  52360. drawEnd = Math.min( drawEnd, index.count );
  52361. } else if ( position !== undefined && position !== null ) {
  52362. drawStart = Math.max( drawStart, 0 );
  52363. drawEnd = Math.min( drawEnd, position.count );
  52364. }
  52365. const drawCount = drawEnd - drawStart;
  52366. if ( drawCount < 0 || drawCount === Infinity ) return;
  52367. //
  52368. bindingStates.setup( object, material, program, geometry, index );
  52369. let attribute;
  52370. let renderer = bufferRenderer;
  52371. if ( index !== null ) {
  52372. attribute = attributes.get( index );
  52373. renderer = indexedBufferRenderer;
  52374. renderer.setIndex( attribute );
  52375. }
  52376. //
  52377. if ( object.isMesh ) {
  52378. if ( material.wireframe === true ) {
  52379. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  52380. renderer.setMode( _gl.LINES );
  52381. } else {
  52382. renderer.setMode( _gl.TRIANGLES );
  52383. }
  52384. } else if ( object.isLine ) {
  52385. let lineWidth = material.linewidth;
  52386. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  52387. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  52388. if ( object.isLineSegments ) {
  52389. renderer.setMode( _gl.LINES );
  52390. } else if ( object.isLineLoop ) {
  52391. renderer.setMode( _gl.LINE_LOOP );
  52392. } else {
  52393. renderer.setMode( _gl.LINE_STRIP );
  52394. }
  52395. } else if ( object.isPoints ) {
  52396. renderer.setMode( _gl.POINTS );
  52397. } else if ( object.isSprite ) {
  52398. renderer.setMode( _gl.TRIANGLES );
  52399. }
  52400. if ( object.isBatchedMesh ) {
  52401. if ( object._multiDrawInstances !== null ) {
  52402. // @deprecated, r174
  52403. warnOnce( 'THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  52404. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  52405. } else {
  52406. if ( ! extensions.get( 'WEBGL_multi_draw' ) ) {
  52407. const starts = object._multiDrawStarts;
  52408. const counts = object._multiDrawCounts;
  52409. const drawCount = object._multiDrawCount;
  52410. const bytesPerElement = index ? attributes.get( index ).bytesPerElement : 1;
  52411. const uniforms = properties.get( material ).currentProgram.getUniforms();
  52412. for ( let i = 0; i < drawCount; i ++ ) {
  52413. uniforms.setValue( _gl, '_gl_DrawID', i );
  52414. renderer.render( starts[ i ] / bytesPerElement, counts[ i ] );
  52415. }
  52416. } else {
  52417. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  52418. }
  52419. }
  52420. } else if ( object.isInstancedMesh ) {
  52421. renderer.renderInstances( drawStart, drawCount, object.count );
  52422. } else if ( geometry.isInstancedBufferGeometry ) {
  52423. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  52424. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  52425. renderer.renderInstances( drawStart, drawCount, instanceCount );
  52426. } else {
  52427. renderer.render( drawStart, drawCount );
  52428. }
  52429. };
  52430. // Compile
  52431. function prepareMaterial( material, scene, object ) {
  52432. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  52433. material.side = BackSide;
  52434. material.needsUpdate = true;
  52435. getProgram( material, scene, object );
  52436. material.side = FrontSide;
  52437. material.needsUpdate = true;
  52438. getProgram( material, scene, object );
  52439. material.side = DoubleSide;
  52440. } else {
  52441. getProgram( material, scene, object );
  52442. }
  52443. }
  52444. /**
  52445. * Compiles all materials in the scene with the camera. This is useful to precompile shaders
  52446. * before the first rendering. If you want to add a 3D object to an existing scene, use the third
  52447. * optional parameter for applying the target scene.
  52448. *
  52449. * Note that the (target) scene's lighting and environment must be configured before calling this method.
  52450. *
  52451. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  52452. * @param {Camera} camera - The camera.
  52453. * @param {?Scene} [targetScene=null] - The target scene.
  52454. * @return {Set<Material>} The precompiled materials.
  52455. */
  52456. this.compile = function ( scene, camera, targetScene = null ) {
  52457. if ( targetScene === null ) targetScene = scene;
  52458. currentRenderState = renderStates.get( targetScene );
  52459. currentRenderState.init( camera );
  52460. renderStateStack.push( currentRenderState );
  52461. // gather lights from both the target scene and the new object that will be added to the scene.
  52462. targetScene.traverseVisible( function ( object ) {
  52463. if ( object.isLight && object.layers.test( camera.layers ) ) {
  52464. currentRenderState.pushLight( object );
  52465. if ( object.castShadow ) {
  52466. currentRenderState.pushShadow( object );
  52467. }
  52468. }
  52469. } );
  52470. if ( scene !== targetScene ) {
  52471. scene.traverseVisible( function ( object ) {
  52472. if ( object.isLight && object.layers.test( camera.layers ) ) {
  52473. currentRenderState.pushLight( object );
  52474. if ( object.castShadow ) {
  52475. currentRenderState.pushShadow( object );
  52476. }
  52477. }
  52478. } );
  52479. }
  52480. currentRenderState.setupLights();
  52481. // Only initialize materials in the new scene, not the targetScene.
  52482. const materials = new Set();
  52483. scene.traverse( function ( object ) {
  52484. if ( ! ( object.isMesh || object.isPoints || object.isLine || object.isSprite ) ) {
  52485. return;
  52486. }
  52487. const material = object.material;
  52488. if ( material ) {
  52489. if ( Array.isArray( material ) ) {
  52490. for ( let i = 0; i < material.length; i ++ ) {
  52491. const material2 = material[ i ];
  52492. prepareMaterial( material2, targetScene, object );
  52493. materials.add( material2 );
  52494. }
  52495. } else {
  52496. prepareMaterial( material, targetScene, object );
  52497. materials.add( material );
  52498. }
  52499. }
  52500. } );
  52501. currentRenderState = renderStateStack.pop();
  52502. return materials;
  52503. };
  52504. // compileAsync
  52505. /**
  52506. * Asynchronous version of {@link WebGLRenderer#compile}.
  52507. *
  52508. * This method makes use of the `KHR_parallel_shader_compile` WebGL extension. Hence,
  52509. * it is recommended to use this version of `compile()` whenever possible.
  52510. *
  52511. * @async
  52512. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  52513. * @param {Camera} camera - The camera.
  52514. * @param {?Scene} [targetScene=null] - The target scene.
  52515. * @return {Promise} A Promise that resolves when the given scene can be rendered without unnecessary stalling due to shader compilation.
  52516. */
  52517. this.compileAsync = function ( scene, camera, targetScene = null ) {
  52518. const materials = this.compile( scene, camera, targetScene );
  52519. // Wait for all the materials in the new object to indicate that they're
  52520. // ready to be used before resolving the promise.
  52521. return new Promise( ( resolve ) => {
  52522. function checkMaterialsReady() {
  52523. materials.forEach( function ( material ) {
  52524. const materialProperties = properties.get( material );
  52525. const program = materialProperties.currentProgram;
  52526. if ( program.isReady() ) {
  52527. // remove any programs that report they're ready to use from the list
  52528. materials.delete( material );
  52529. }
  52530. } );
  52531. // once the list of compiling materials is empty, call the callback
  52532. if ( materials.size === 0 ) {
  52533. resolve( scene );
  52534. return;
  52535. }
  52536. // if some materials are still not ready, wait a bit and check again
  52537. setTimeout( checkMaterialsReady, 10 );
  52538. }
  52539. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  52540. // If we can check the compilation status of the materials without
  52541. // blocking then do so right away.
  52542. checkMaterialsReady();
  52543. } else {
  52544. // Otherwise start by waiting a bit to give the materials we just
  52545. // initialized a chance to finish.
  52546. setTimeout( checkMaterialsReady, 10 );
  52547. }
  52548. } );
  52549. };
  52550. // Animation Loop
  52551. let onAnimationFrameCallback = null;
  52552. function onAnimationFrame( time ) {
  52553. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  52554. }
  52555. function onXRSessionStart() {
  52556. animation.stop();
  52557. }
  52558. function onXRSessionEnd() {
  52559. animation.start();
  52560. }
  52561. const animation = new WebGLAnimation();
  52562. animation.setAnimationLoop( onAnimationFrame );
  52563. if ( typeof self !== 'undefined' ) animation.setContext( self );
  52564. this.setAnimationLoop = function ( callback ) {
  52565. onAnimationFrameCallback = callback;
  52566. xr.setAnimationLoop( callback );
  52567. ( callback === null ) ? animation.stop() : animation.start();
  52568. };
  52569. xr.addEventListener( 'sessionstart', onXRSessionStart );
  52570. xr.addEventListener( 'sessionend', onXRSessionEnd );
  52571. // Rendering
  52572. /**
  52573. * Renders the given scene (or other type of 3D object) using the given camera.
  52574. *
  52575. * The render is done to a previously specified render target set by calling {@link WebGLRenderer#setRenderTarget}
  52576. * or to the canvas as usual.
  52577. *
  52578. * By default render buffers are cleared before rendering but you can prevent
  52579. * this by setting the property `autoClear` to `false`. If you want to prevent
  52580. * only certain buffers being cleared you can `autoClearColor`, `autoClearDepth`
  52581. * or `autoClearStencil` to `false`. To force a clear, use {@link WebGLRenderer#clear}.
  52582. *
  52583. * @param {Object3D} scene - The scene to render.
  52584. * @param {Camera} camera - The camera.
  52585. */
  52586. this.render = function ( scene, camera ) {
  52587. if ( camera !== undefined && camera.isCamera !== true ) {
  52588. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  52589. return;
  52590. }
  52591. if ( _isContextLost === true ) return;
  52592. // update scene graph
  52593. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  52594. // update camera matrices and frustum
  52595. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  52596. if ( xr.enabled === true && xr.isPresenting === true ) {
  52597. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  52598. camera = xr.getCamera(); // use XR camera for rendering
  52599. }
  52600. //
  52601. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  52602. currentRenderState = renderStates.get( scene, renderStateStack.length );
  52603. currentRenderState.init( camera );
  52604. renderStateStack.push( currentRenderState );
  52605. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  52606. _frustum.setFromProjectionMatrix( _projScreenMatrix, WebGLCoordinateSystem, camera.reversedDepth );
  52607. _localClippingEnabled = this.localClippingEnabled;
  52608. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  52609. currentRenderList = renderLists.get( scene, renderListStack.length );
  52610. currentRenderList.init();
  52611. renderListStack.push( currentRenderList );
  52612. if ( xr.enabled === true && xr.isPresenting === true ) {
  52613. const depthSensingMesh = _this.xr.getDepthSensingMesh();
  52614. if ( depthSensingMesh !== null ) {
  52615. projectObject( depthSensingMesh, camera, - Infinity, _this.sortObjects );
  52616. }
  52617. }
  52618. projectObject( scene, camera, 0, _this.sortObjects );
  52619. currentRenderList.finish();
  52620. if ( _this.sortObjects === true ) {
  52621. currentRenderList.sort( _opaqueSort, _transparentSort );
  52622. }
  52623. _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  52624. if ( _renderBackground ) {
  52625. background.addToRenderList( currentRenderList, scene );
  52626. }
  52627. //
  52628. this.info.render.frame ++;
  52629. if ( _clippingEnabled === true ) clipping.beginShadows();
  52630. const shadowsArray = currentRenderState.state.shadowsArray;
  52631. shadowMap.render( shadowsArray, scene, camera );
  52632. if ( _clippingEnabled === true ) clipping.endShadows();
  52633. //
  52634. if ( this.info.autoReset === true ) this.info.reset();
  52635. // render scene
  52636. const opaqueObjects = currentRenderList.opaque;
  52637. const transmissiveObjects = currentRenderList.transmissive;
  52638. currentRenderState.setupLights();
  52639. if ( camera.isArrayCamera ) {
  52640. const cameras = camera.cameras;
  52641. if ( transmissiveObjects.length > 0 ) {
  52642. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  52643. const camera2 = cameras[ i ];
  52644. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  52645. }
  52646. }
  52647. if ( _renderBackground ) background.render( scene );
  52648. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  52649. const camera2 = cameras[ i ];
  52650. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  52651. }
  52652. } else {
  52653. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  52654. if ( _renderBackground ) background.render( scene );
  52655. renderScene( currentRenderList, scene, camera );
  52656. }
  52657. //
  52658. if ( _currentRenderTarget !== null && _currentActiveMipmapLevel === 0 ) {
  52659. // resolve multisample renderbuffers to a single-sample texture if necessary
  52660. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  52661. // Generate mipmap if we're using any kind of mipmap filtering
  52662. textures.updateRenderTargetMipmap( _currentRenderTarget );
  52663. }
  52664. //
  52665. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  52666. // _gl.finish();
  52667. bindingStates.resetDefaultState();
  52668. _currentMaterialId = -1;
  52669. _currentCamera = null;
  52670. renderStateStack.pop();
  52671. if ( renderStateStack.length > 0 ) {
  52672. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  52673. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  52674. } else {
  52675. currentRenderState = null;
  52676. }
  52677. renderListStack.pop();
  52678. if ( renderListStack.length > 0 ) {
  52679. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  52680. } else {
  52681. currentRenderList = null;
  52682. }
  52683. };
  52684. function projectObject( object, camera, groupOrder, sortObjects ) {
  52685. if ( object.visible === false ) return;
  52686. const visible = object.layers.test( camera.layers );
  52687. if ( visible ) {
  52688. if ( object.isGroup ) {
  52689. groupOrder = object.renderOrder;
  52690. } else if ( object.isLOD ) {
  52691. if ( object.autoUpdate === true ) object.update( camera );
  52692. } else if ( object.isLight ) {
  52693. currentRenderState.pushLight( object );
  52694. if ( object.castShadow ) {
  52695. currentRenderState.pushShadow( object );
  52696. }
  52697. } else if ( object.isSprite ) {
  52698. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  52699. if ( sortObjects ) {
  52700. _vector4.setFromMatrixPosition( object.matrixWorld )
  52701. .applyMatrix4( _projScreenMatrix );
  52702. }
  52703. const geometry = objects.update( object );
  52704. const material = object.material;
  52705. if ( material.visible ) {
  52706. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  52707. }
  52708. }
  52709. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  52710. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  52711. const geometry = objects.update( object );
  52712. const material = object.material;
  52713. if ( sortObjects ) {
  52714. if ( object.boundingSphere !== undefined ) {
  52715. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  52716. _vector4.copy( object.boundingSphere.center );
  52717. } else {
  52718. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  52719. _vector4.copy( geometry.boundingSphere.center );
  52720. }
  52721. _vector4
  52722. .applyMatrix4( object.matrixWorld )
  52723. .applyMatrix4( _projScreenMatrix );
  52724. }
  52725. if ( Array.isArray( material ) ) {
  52726. const groups = geometry.groups;
  52727. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  52728. const group = groups[ i ];
  52729. const groupMaterial = material[ group.materialIndex ];
  52730. if ( groupMaterial && groupMaterial.visible ) {
  52731. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  52732. }
  52733. }
  52734. } else if ( material.visible ) {
  52735. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  52736. }
  52737. }
  52738. }
  52739. }
  52740. const children = object.children;
  52741. for ( let i = 0, l = children.length; i < l; i ++ ) {
  52742. projectObject( children[ i ], camera, groupOrder, sortObjects );
  52743. }
  52744. }
  52745. function renderScene( currentRenderList, scene, camera, viewport ) {
  52746. const opaqueObjects = currentRenderList.opaque;
  52747. const transmissiveObjects = currentRenderList.transmissive;
  52748. const transparentObjects = currentRenderList.transparent;
  52749. currentRenderState.setupLightsView( camera );
  52750. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  52751. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  52752. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  52753. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  52754. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  52755. // Ensure depth buffer writing is enabled so it can be cleared on next render
  52756. state.buffers.depth.setTest( true );
  52757. state.buffers.depth.setMask( true );
  52758. state.buffers.color.setMask( true );
  52759. state.setPolygonOffset( false );
  52760. }
  52761. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  52762. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  52763. if ( overrideMaterial !== null ) {
  52764. return;
  52765. }
  52766. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  52767. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  52768. generateMipmaps: true,
  52769. type: ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) ) ? HalfFloatType : UnsignedByteType,
  52770. minFilter: LinearMipmapLinearFilter,
  52771. samples: 4,
  52772. stencilBuffer: stencil,
  52773. resolveDepthBuffer: false,
  52774. resolveStencilBuffer: false,
  52775. colorSpace: ColorManagement.workingColorSpace,
  52776. } );
  52777. // debug
  52778. /*
  52779. const geometry = new PlaneGeometry();
  52780. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  52781. const mesh = new Mesh( geometry, material );
  52782. scene.add( mesh );
  52783. */
  52784. }
  52785. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  52786. const activeViewport = camera.viewport || _currentViewport;
  52787. transmissionRenderTarget.setSize( activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale );
  52788. //
  52789. const currentRenderTarget = _this.getRenderTarget();
  52790. const currentActiveCubeFace = _this.getActiveCubeFace();
  52791. const currentActiveMipmapLevel = _this.getActiveMipmapLevel();
  52792. _this.setRenderTarget( transmissionRenderTarget );
  52793. _this.getClearColor( _currentClearColor );
  52794. _currentClearAlpha = _this.getClearAlpha();
  52795. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  52796. _this.clear();
  52797. if ( _renderBackground ) background.render( scene );
  52798. // Turn off the features which can affect the frag color for opaque objects pass.
  52799. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  52800. const currentToneMapping = _this.toneMapping;
  52801. _this.toneMapping = NoToneMapping;
  52802. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  52803. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  52804. const currentCameraViewport = camera.viewport;
  52805. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  52806. currentRenderState.setupLightsView( camera );
  52807. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  52808. renderObjects( opaqueObjects, scene, camera );
  52809. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  52810. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  52811. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  52812. let renderTargetNeedsUpdate = false;
  52813. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  52814. const renderItem = transmissiveObjects[ i ];
  52815. const object = renderItem.object;
  52816. const geometry = renderItem.geometry;
  52817. const material = renderItem.material;
  52818. const group = renderItem.group;
  52819. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  52820. const currentSide = material.side;
  52821. material.side = BackSide;
  52822. material.needsUpdate = true;
  52823. renderObject( object, scene, camera, geometry, material, group );
  52824. material.side = currentSide;
  52825. material.needsUpdate = true;
  52826. renderTargetNeedsUpdate = true;
  52827. }
  52828. }
  52829. if ( renderTargetNeedsUpdate === true ) {
  52830. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  52831. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  52832. }
  52833. }
  52834. _this.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  52835. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  52836. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  52837. _this.toneMapping = currentToneMapping;
  52838. }
  52839. function renderObjects( renderList, scene, camera ) {
  52840. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  52841. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  52842. const renderItem = renderList[ i ];
  52843. const object = renderItem.object;
  52844. const geometry = renderItem.geometry;
  52845. const group = renderItem.group;
  52846. let material = renderItem.material;
  52847. if ( material.allowOverride === true && overrideMaterial !== null ) {
  52848. material = overrideMaterial;
  52849. }
  52850. if ( object.layers.test( camera.layers ) ) {
  52851. renderObject( object, scene, camera, geometry, material, group );
  52852. }
  52853. }
  52854. }
  52855. function renderObject( object, scene, camera, geometry, material, group ) {
  52856. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  52857. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  52858. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  52859. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  52860. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  52861. material.side = BackSide;
  52862. material.needsUpdate = true;
  52863. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  52864. material.side = FrontSide;
  52865. material.needsUpdate = true;
  52866. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  52867. material.side = DoubleSide;
  52868. } else {
  52869. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  52870. }
  52871. object.onAfterRender( _this, scene, camera, geometry, material, group );
  52872. }
  52873. function getProgram( material, scene, object ) {
  52874. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  52875. const materialProperties = properties.get( material );
  52876. const lights = currentRenderState.state.lights;
  52877. const shadowsArray = currentRenderState.state.shadowsArray;
  52878. const lightsStateVersion = lights.state.version;
  52879. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  52880. const programCacheKey = programCache.getProgramCacheKey( parameters );
  52881. let programs = materialProperties.programs;
  52882. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  52883. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  52884. materialProperties.fog = scene.fog;
  52885. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  52886. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  52887. if ( programs === undefined ) {
  52888. // new material
  52889. material.addEventListener( 'dispose', onMaterialDispose );
  52890. programs = new Map();
  52891. materialProperties.programs = programs;
  52892. }
  52893. let program = programs.get( programCacheKey );
  52894. if ( program !== undefined ) {
  52895. // early out if program and light state is identical
  52896. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  52897. updateCommonMaterialProperties( material, parameters );
  52898. return program;
  52899. }
  52900. } else {
  52901. parameters.uniforms = programCache.getUniforms( material );
  52902. material.onBeforeCompile( parameters, _this );
  52903. program = programCache.acquireProgram( parameters, programCacheKey );
  52904. programs.set( programCacheKey, program );
  52905. materialProperties.uniforms = parameters.uniforms;
  52906. }
  52907. const uniforms = materialProperties.uniforms;
  52908. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  52909. uniforms.clippingPlanes = clipping.uniform;
  52910. }
  52911. updateCommonMaterialProperties( material, parameters );
  52912. // store the light setup it was created for
  52913. materialProperties.needsLights = materialNeedsLights( material );
  52914. materialProperties.lightsStateVersion = lightsStateVersion;
  52915. if ( materialProperties.needsLights ) {
  52916. // wire up the material to this renderer's lighting state
  52917. uniforms.ambientLightColor.value = lights.state.ambient;
  52918. uniforms.lightProbe.value = lights.state.probe;
  52919. uniforms.directionalLights.value = lights.state.directional;
  52920. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  52921. uniforms.spotLights.value = lights.state.spot;
  52922. uniforms.spotLightShadows.value = lights.state.spotShadow;
  52923. uniforms.rectAreaLights.value = lights.state.rectArea;
  52924. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  52925. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  52926. uniforms.pointLights.value = lights.state.point;
  52927. uniforms.pointLightShadows.value = lights.state.pointShadow;
  52928. uniforms.hemisphereLights.value = lights.state.hemi;
  52929. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  52930. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  52931. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  52932. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  52933. uniforms.spotLightMap.value = lights.state.spotLightMap;
  52934. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  52935. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  52936. // TODO (abelnation): add area lights shadow info to uniforms
  52937. }
  52938. materialProperties.currentProgram = program;
  52939. materialProperties.uniformsList = null;
  52940. return program;
  52941. }
  52942. function getUniformList( materialProperties ) {
  52943. if ( materialProperties.uniformsList === null ) {
  52944. const progUniforms = materialProperties.currentProgram.getUniforms();
  52945. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  52946. }
  52947. return materialProperties.uniformsList;
  52948. }
  52949. function updateCommonMaterialProperties( material, parameters ) {
  52950. const materialProperties = properties.get( material );
  52951. materialProperties.outputColorSpace = parameters.outputColorSpace;
  52952. materialProperties.batching = parameters.batching;
  52953. materialProperties.batchingColor = parameters.batchingColor;
  52954. materialProperties.instancing = parameters.instancing;
  52955. materialProperties.instancingColor = parameters.instancingColor;
  52956. materialProperties.instancingMorph = parameters.instancingMorph;
  52957. materialProperties.skinning = parameters.skinning;
  52958. materialProperties.morphTargets = parameters.morphTargets;
  52959. materialProperties.morphNormals = parameters.morphNormals;
  52960. materialProperties.morphColors = parameters.morphColors;
  52961. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  52962. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  52963. materialProperties.numIntersection = parameters.numClipIntersection;
  52964. materialProperties.vertexAlphas = parameters.vertexAlphas;
  52965. materialProperties.vertexTangents = parameters.vertexTangents;
  52966. materialProperties.toneMapping = parameters.toneMapping;
  52967. }
  52968. function setProgram( camera, scene, geometry, material, object ) {
  52969. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  52970. textures.resetTextureUnits();
  52971. const fog = scene.fog;
  52972. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  52973. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  52974. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  52975. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  52976. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  52977. const morphTargets = !! geometry.morphAttributes.position;
  52978. const morphNormals = !! geometry.morphAttributes.normal;
  52979. const morphColors = !! geometry.morphAttributes.color;
  52980. let toneMapping = NoToneMapping;
  52981. if ( material.toneMapped ) {
  52982. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  52983. toneMapping = _this.toneMapping;
  52984. }
  52985. }
  52986. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  52987. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  52988. const materialProperties = properties.get( material );
  52989. const lights = currentRenderState.state.lights;
  52990. if ( _clippingEnabled === true ) {
  52991. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  52992. const useCache =
  52993. camera === _currentCamera &&
  52994. material.id === _currentMaterialId;
  52995. // we might want to call this function with some ClippingGroup
  52996. // object instead of the material, once it becomes feasible
  52997. // (#8465, #8379)
  52998. clipping.setState( material, camera, useCache );
  52999. }
  53000. }
  53001. //
  53002. let needsProgramChange = false;
  53003. if ( material.version === materialProperties.__version ) {
  53004. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  53005. needsProgramChange = true;
  53006. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  53007. needsProgramChange = true;
  53008. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  53009. needsProgramChange = true;
  53010. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  53011. needsProgramChange = true;
  53012. } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null ) {
  53013. needsProgramChange = true;
  53014. } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null ) {
  53015. needsProgramChange = true;
  53016. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  53017. needsProgramChange = true;
  53018. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  53019. needsProgramChange = true;
  53020. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  53021. needsProgramChange = true;
  53022. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  53023. needsProgramChange = true;
  53024. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  53025. needsProgramChange = true;
  53026. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  53027. needsProgramChange = true;
  53028. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  53029. needsProgramChange = true;
  53030. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  53031. needsProgramChange = true;
  53032. } else if ( materialProperties.envMap !== envMap ) {
  53033. needsProgramChange = true;
  53034. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  53035. needsProgramChange = true;
  53036. } else if ( materialProperties.numClippingPlanes !== undefined &&
  53037. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  53038. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  53039. needsProgramChange = true;
  53040. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  53041. needsProgramChange = true;
  53042. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  53043. needsProgramChange = true;
  53044. } else if ( materialProperties.morphTargets !== morphTargets ) {
  53045. needsProgramChange = true;
  53046. } else if ( materialProperties.morphNormals !== morphNormals ) {
  53047. needsProgramChange = true;
  53048. } else if ( materialProperties.morphColors !== morphColors ) {
  53049. needsProgramChange = true;
  53050. } else if ( materialProperties.toneMapping !== toneMapping ) {
  53051. needsProgramChange = true;
  53052. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  53053. needsProgramChange = true;
  53054. }
  53055. } else {
  53056. needsProgramChange = true;
  53057. materialProperties.__version = material.version;
  53058. }
  53059. //
  53060. let program = materialProperties.currentProgram;
  53061. if ( needsProgramChange === true ) {
  53062. program = getProgram( material, scene, object );
  53063. }
  53064. let refreshProgram = false;
  53065. let refreshMaterial = false;
  53066. let refreshLights = false;
  53067. const p_uniforms = program.getUniforms(),
  53068. m_uniforms = materialProperties.uniforms;
  53069. if ( state.useProgram( program.program ) ) {
  53070. refreshProgram = true;
  53071. refreshMaterial = true;
  53072. refreshLights = true;
  53073. }
  53074. if ( material.id !== _currentMaterialId ) {
  53075. _currentMaterialId = material.id;
  53076. refreshMaterial = true;
  53077. }
  53078. if ( refreshProgram || _currentCamera !== camera ) {
  53079. // common camera uniforms
  53080. const reversedDepthBuffer = state.buffers.depth.getReversed();
  53081. if ( reversedDepthBuffer && camera.reversedDepth !== true ) {
  53082. camera._reversedDepth = true;
  53083. camera.updateProjectionMatrix();
  53084. }
  53085. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  53086. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  53087. const uCamPos = p_uniforms.map.cameraPosition;
  53088. if ( uCamPos !== undefined ) {
  53089. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  53090. }
  53091. if ( capabilities.logarithmicDepthBuffer ) {
  53092. p_uniforms.setValue( _gl, 'logDepthBufFC',
  53093. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  53094. }
  53095. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  53096. if ( material.isMeshPhongMaterial ||
  53097. material.isMeshToonMaterial ||
  53098. material.isMeshLambertMaterial ||
  53099. material.isMeshBasicMaterial ||
  53100. material.isMeshStandardMaterial ||
  53101. material.isShaderMaterial ) {
  53102. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  53103. }
  53104. if ( _currentCamera !== camera ) {
  53105. _currentCamera = camera;
  53106. // lighting uniforms depend on the camera so enforce an update
  53107. // now, in case this material supports lights - or later, when
  53108. // the next material that does gets activated:
  53109. refreshMaterial = true; // set to true on material change
  53110. refreshLights = true; // remains set until update done
  53111. }
  53112. }
  53113. // skinning and morph target uniforms must be set even if material didn't change
  53114. // auto-setting of texture unit for bone and morph texture must go before other textures
  53115. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  53116. if ( object.isSkinnedMesh ) {
  53117. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  53118. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  53119. const skeleton = object.skeleton;
  53120. if ( skeleton ) {
  53121. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  53122. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  53123. }
  53124. }
  53125. if ( object.isBatchedMesh ) {
  53126. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  53127. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  53128. p_uniforms.setOptional( _gl, object, 'batchingIdTexture' );
  53129. p_uniforms.setValue( _gl, 'batchingIdTexture', object._indirectTexture, textures );
  53130. p_uniforms.setOptional( _gl, object, 'batchingColorTexture' );
  53131. if ( object._colorsTexture !== null ) {
  53132. p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures );
  53133. }
  53134. }
  53135. const morphAttributes = geometry.morphAttributes;
  53136. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  53137. morphtargets.update( object, geometry, program );
  53138. }
  53139. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  53140. materialProperties.receiveShadow = object.receiveShadow;
  53141. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  53142. }
  53143. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  53144. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  53145. m_uniforms.envMap.value = envMap;
  53146. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  53147. }
  53148. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  53149. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  53150. }
  53151. if ( refreshMaterial ) {
  53152. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  53153. if ( materialProperties.needsLights ) {
  53154. // the current material requires lighting info
  53155. // note: all lighting uniforms are always set correctly
  53156. // they simply reference the renderer's state for their
  53157. // values
  53158. //
  53159. // use the current material's .needsUpdate flags to set
  53160. // the GL state when required
  53161. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  53162. }
  53163. // refresh uniforms common to several materials
  53164. if ( fog && material.fog === true ) {
  53165. materials.refreshFogUniforms( m_uniforms, fog );
  53166. }
  53167. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  53168. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  53169. }
  53170. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  53171. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  53172. material.uniformsNeedUpdate = false;
  53173. }
  53174. if ( material.isSpriteMaterial ) {
  53175. p_uniforms.setValue( _gl, 'center', object.center );
  53176. }
  53177. // common matrices
  53178. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  53179. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  53180. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  53181. // UBOs
  53182. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  53183. const groups = material.uniformsGroups;
  53184. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  53185. const group = groups[ i ];
  53186. uniformsGroups.update( group, program );
  53187. uniformsGroups.bind( group, program );
  53188. }
  53189. }
  53190. return program;
  53191. }
  53192. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  53193. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  53194. uniforms.ambientLightColor.needsUpdate = value;
  53195. uniforms.lightProbe.needsUpdate = value;
  53196. uniforms.directionalLights.needsUpdate = value;
  53197. uniforms.directionalLightShadows.needsUpdate = value;
  53198. uniforms.pointLights.needsUpdate = value;
  53199. uniforms.pointLightShadows.needsUpdate = value;
  53200. uniforms.spotLights.needsUpdate = value;
  53201. uniforms.spotLightShadows.needsUpdate = value;
  53202. uniforms.rectAreaLights.needsUpdate = value;
  53203. uniforms.hemisphereLights.needsUpdate = value;
  53204. }
  53205. function materialNeedsLights( material ) {
  53206. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  53207. material.isMeshStandardMaterial || material.isShadowMaterial ||
  53208. ( material.isShaderMaterial && material.lights === true );
  53209. }
  53210. /**
  53211. * Returns the active cube face.
  53212. *
  53213. * @return {number} The active cube face.
  53214. */
  53215. this.getActiveCubeFace = function () {
  53216. return _currentActiveCubeFace;
  53217. };
  53218. /**
  53219. * Returns the active mipmap level.
  53220. *
  53221. * @return {number} The active mipmap level.
  53222. */
  53223. this.getActiveMipmapLevel = function () {
  53224. return _currentActiveMipmapLevel;
  53225. };
  53226. /**
  53227. * Returns the active render target.
  53228. *
  53229. * @return {?WebGLRenderTarget} The active render target. Returns `null` if no render target
  53230. * is currently set.
  53231. */
  53232. this.getRenderTarget = function () {
  53233. return _currentRenderTarget;
  53234. };
  53235. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  53236. const renderTargetProperties = properties.get( renderTarget );
  53237. renderTargetProperties.__autoAllocateDepthBuffer = renderTarget.resolveDepthBuffer === false;
  53238. if ( renderTargetProperties.__autoAllocateDepthBuffer === false ) {
  53239. // The multisample_render_to_texture extension doesn't work properly if there
  53240. // are midframe flushes and an external depth buffer. Disable use of the extension.
  53241. renderTargetProperties.__useRenderToTexture = false;
  53242. }
  53243. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  53244. properties.get( renderTarget.depthTexture ).__webglTexture = renderTargetProperties.__autoAllocateDepthBuffer ? undefined : depthTexture;
  53245. renderTargetProperties.__hasExternalTextures = true;
  53246. };
  53247. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  53248. const renderTargetProperties = properties.get( renderTarget );
  53249. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  53250. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  53251. };
  53252. const _scratchFrameBuffer = _gl.createFramebuffer();
  53253. /**
  53254. * Sets the active rendertarget.
  53255. *
  53256. * @param {?WebGLRenderTarget} renderTarget - The render target to set. When `null` is given,
  53257. * the canvas is set as the active render target instead.
  53258. * @param {number} [activeCubeFace=0] - The active cube face when using a cube render target.
  53259. * Indicates the z layer to render in to when using 3D or array render targets.
  53260. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  53261. */
  53262. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  53263. _currentRenderTarget = renderTarget;
  53264. _currentActiveCubeFace = activeCubeFace;
  53265. _currentActiveMipmapLevel = activeMipmapLevel;
  53266. let useDefaultFramebuffer = true;
  53267. let framebuffer = null;
  53268. let isCube = false;
  53269. let isRenderTarget3D = false;
  53270. if ( renderTarget ) {
  53271. const renderTargetProperties = properties.get( renderTarget );
  53272. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  53273. // We need to make sure to rebind the framebuffer.
  53274. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  53275. useDefaultFramebuffer = false;
  53276. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  53277. textures.setupRenderTarget( renderTarget );
  53278. } else if ( renderTargetProperties.__hasExternalTextures ) {
  53279. // Color and depth texture must be rebound in order for the swapchain to update.
  53280. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  53281. } else if ( renderTarget.depthBuffer ) {
  53282. // check if the depth texture is already bound to the frame buffer and that it's been initialized
  53283. const depthTexture = renderTarget.depthTexture;
  53284. if ( renderTargetProperties.__boundDepthTexture !== depthTexture ) {
  53285. // check if the depth texture is compatible
  53286. if (
  53287. depthTexture !== null &&
  53288. properties.has( depthTexture ) &&
  53289. ( renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height )
  53290. ) {
  53291. throw new Error( 'WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.' );
  53292. }
  53293. // Swap the depth buffer to the currently attached one
  53294. textures.setupDepthRenderbuffer( renderTarget );
  53295. }
  53296. }
  53297. const texture = renderTarget.texture;
  53298. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  53299. isRenderTarget3D = true;
  53300. }
  53301. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  53302. if ( renderTarget.isWebGLCubeRenderTarget ) {
  53303. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  53304. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  53305. } else {
  53306. framebuffer = __webglFramebuffer[ activeCubeFace ];
  53307. }
  53308. isCube = true;
  53309. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  53310. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  53311. } else {
  53312. if ( Array.isArray( __webglFramebuffer ) ) {
  53313. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  53314. } else {
  53315. framebuffer = __webglFramebuffer;
  53316. }
  53317. }
  53318. _currentViewport.copy( renderTarget.viewport );
  53319. _currentScissor.copy( renderTarget.scissor );
  53320. _currentScissorTest = renderTarget.scissorTest;
  53321. } else {
  53322. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  53323. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  53324. _currentScissorTest = _scissorTest;
  53325. }
  53326. // Use a scratch frame buffer if rendering to a mip level to avoid depth buffers
  53327. // being bound that are different sizes.
  53328. if ( activeMipmapLevel !== 0 ) {
  53329. framebuffer = _scratchFrameBuffer;
  53330. }
  53331. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  53332. if ( framebufferBound && useDefaultFramebuffer ) {
  53333. state.drawBuffers( renderTarget, framebuffer );
  53334. }
  53335. state.viewport( _currentViewport );
  53336. state.scissor( _currentScissor );
  53337. state.setScissorTest( _currentScissorTest );
  53338. if ( isCube ) {
  53339. const textureProperties = properties.get( renderTarget.texture );
  53340. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  53341. } else if ( isRenderTarget3D ) {
  53342. const layer = activeCubeFace;
  53343. for ( let i = 0; i < renderTarget.textures.length; i ++ ) {
  53344. const textureProperties = properties.get( renderTarget.textures[ i ] );
  53345. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, textureProperties.__webglTexture, activeMipmapLevel, layer );
  53346. }
  53347. } else if ( renderTarget !== null && activeMipmapLevel !== 0 ) {
  53348. // Only bind the frame buffer if we are using a scratch frame buffer to render to a mipmap.
  53349. // If we rebind the texture when using a multi sample buffer then an error about inconsistent samples will be thrown.
  53350. const textureProperties = properties.get( renderTarget.texture );
  53351. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel );
  53352. }
  53353. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  53354. };
  53355. /**
  53356. * Reads the pixel data from the given render target into the given buffer.
  53357. *
  53358. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  53359. * @param {number} x - The `x` coordinate of the copy region's origin.
  53360. * @param {number} y - The `y` coordinate of the copy region's origin.
  53361. * @param {number} width - The width of the copy region.
  53362. * @param {number} height - The height of the copy region.
  53363. * @param {TypedArray} buffer - The result buffer.
  53364. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  53365. * @param {number} [textureIndex=0] - The texture index of an MRT render target.
  53366. */
  53367. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) {
  53368. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  53369. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  53370. return;
  53371. }
  53372. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  53373. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  53374. framebuffer = framebuffer[ activeCubeFaceIndex ];
  53375. }
  53376. if ( framebuffer ) {
  53377. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  53378. try {
  53379. const texture = renderTarget.textures[ textureIndex ];
  53380. const textureFormat = texture.format;
  53381. const textureType = texture.type;
  53382. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  53383. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  53384. return;
  53385. }
  53386. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  53387. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  53388. return;
  53389. }
  53390. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  53391. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  53392. // when using MRT, select the correct color buffer for the subsequent read command
  53393. if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex );
  53394. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  53395. }
  53396. } finally {
  53397. // restore framebuffer of current render target if necessary
  53398. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  53399. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  53400. }
  53401. }
  53402. };
  53403. /**
  53404. * Asynchronous, non-blocking version of {@link WebGLRenderer#readRenderTargetPixels}.
  53405. *
  53406. * It is recommended to use this version of `readRenderTargetPixels()` whenever possible.
  53407. *
  53408. * @async
  53409. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  53410. * @param {number} x - The `x` coordinate of the copy region's origin.
  53411. * @param {number} y - The `y` coordinate of the copy region's origin.
  53412. * @param {number} width - The width of the copy region.
  53413. * @param {number} height - The height of the copy region.
  53414. * @param {TypedArray} buffer - The result buffer.
  53415. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  53416. * @param {number} [textureIndex=0] - The texture index of an MRT render target.
  53417. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  53418. */
  53419. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) {
  53420. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  53421. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  53422. }
  53423. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  53424. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  53425. framebuffer = framebuffer[ activeCubeFaceIndex ];
  53426. }
  53427. if ( framebuffer ) {
  53428. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  53429. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  53430. // set the active frame buffer to the one we want to read
  53431. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  53432. const texture = renderTarget.textures[ textureIndex ];
  53433. const textureFormat = texture.format;
  53434. const textureType = texture.type;
  53435. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  53436. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  53437. }
  53438. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  53439. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  53440. }
  53441. const glBuffer = _gl.createBuffer();
  53442. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  53443. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  53444. // when using MRT, select the correct color buffer for the subsequent read command
  53445. if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex );
  53446. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  53447. // reset the frame buffer to the currently set buffer before waiting
  53448. const currFramebuffer = _currentRenderTarget !== null ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  53449. state.bindFramebuffer( _gl.FRAMEBUFFER, currFramebuffer );
  53450. // check if the commands have finished every 8 ms
  53451. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  53452. _gl.flush();
  53453. await probeAsync( _gl, sync, 4 );
  53454. // read the data and delete the buffer
  53455. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  53456. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  53457. _gl.deleteBuffer( glBuffer );
  53458. _gl.deleteSync( sync );
  53459. return buffer;
  53460. } else {
  53461. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.' );
  53462. }
  53463. }
  53464. };
  53465. /**
  53466. * Copies pixels from the current bound framebuffer into the given texture.
  53467. *
  53468. * @param {FramebufferTexture} texture - The texture.
  53469. * @param {?Vector2} [position=null] - The start position of the copy operation.
  53470. * @param {number} [level=0] - The mip level. The default represents the base mip.
  53471. */
  53472. this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) {
  53473. const levelScale = Math.pow( 2, - level );
  53474. const width = Math.floor( texture.image.width * levelScale );
  53475. const height = Math.floor( texture.image.height * levelScale );
  53476. const x = position !== null ? position.x : 0;
  53477. const y = position !== null ? position.y : 0;
  53478. textures.setTexture2D( texture, 0 );
  53479. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height );
  53480. state.unbindTexture();
  53481. };
  53482. const _srcFramebuffer = _gl.createFramebuffer();
  53483. const _dstFramebuffer = _gl.createFramebuffer();
  53484. /**
  53485. * Copies data of the given source texture into a destination texture.
  53486. *
  53487. * When using render target textures as `srcTexture` and `dstTexture`, you must make sure both render targets are initialized
  53488. * {@link WebGLRenderer#initRenderTarget}.
  53489. *
  53490. * @param {Texture} srcTexture - The source texture.
  53491. * @param {Texture} dstTexture - The destination texture.
  53492. * @param {?(Box2|Box3)} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  53493. * @param {?(Vector2|Vector3)} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  53494. * @param {number} [srcLevel=0] - The source mipmap level to copy.
  53495. * @param {?number} [dstLevel=null] - The destination mipmap level.
  53496. */
  53497. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = null ) {
  53498. // support the previous signature with just a single dst mipmap level
  53499. if ( dstLevel === null ) {
  53500. if ( srcLevel !== 0 ) {
  53501. // @deprecated, r171
  53502. warnOnce( 'WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels.' );
  53503. dstLevel = srcLevel;
  53504. srcLevel = 0;
  53505. } else {
  53506. dstLevel = 0;
  53507. }
  53508. }
  53509. // gather the necessary dimensions to copy
  53510. let width, height, depth, minX, minY, minZ;
  53511. let dstX, dstY, dstZ;
  53512. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  53513. if ( srcRegion !== null ) {
  53514. width = srcRegion.max.x - srcRegion.min.x;
  53515. height = srcRegion.max.y - srcRegion.min.y;
  53516. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  53517. minX = srcRegion.min.x;
  53518. minY = srcRegion.min.y;
  53519. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  53520. } else {
  53521. const levelScale = Math.pow( 2, - srcLevel );
  53522. width = Math.floor( image.width * levelScale );
  53523. height = Math.floor( image.height * levelScale );
  53524. if ( srcTexture.isDataArrayTexture ) {
  53525. depth = image.depth;
  53526. } else if ( srcTexture.isData3DTexture ) {
  53527. depth = Math.floor( image.depth * levelScale );
  53528. } else {
  53529. depth = 1;
  53530. }
  53531. minX = 0;
  53532. minY = 0;
  53533. minZ = 0;
  53534. }
  53535. if ( dstPosition !== null ) {
  53536. dstX = dstPosition.x;
  53537. dstY = dstPosition.y;
  53538. dstZ = dstPosition.z;
  53539. } else {
  53540. dstX = 0;
  53541. dstY = 0;
  53542. dstZ = 0;
  53543. }
  53544. // Set up the destination target
  53545. const glFormat = utils.convert( dstTexture.format );
  53546. const glType = utils.convert( dstTexture.type );
  53547. let glTarget;
  53548. if ( dstTexture.isData3DTexture ) {
  53549. textures.setTexture3D( dstTexture, 0 );
  53550. glTarget = _gl.TEXTURE_3D;
  53551. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  53552. textures.setTexture2DArray( dstTexture, 0 );
  53553. glTarget = _gl.TEXTURE_2D_ARRAY;
  53554. } else {
  53555. textures.setTexture2D( dstTexture, 0 );
  53556. glTarget = _gl.TEXTURE_2D;
  53557. }
  53558. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  53559. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  53560. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  53561. // used for copying data from cpu
  53562. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  53563. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  53564. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  53565. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  53566. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  53567. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  53568. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  53569. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  53570. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  53571. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  53572. // set up the src texture
  53573. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture;
  53574. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture;
  53575. if ( srcTexture.isDepthTexture ) {
  53576. const srcTextureProperties = properties.get( srcTexture );
  53577. const dstTextureProperties = properties.get( dstTexture );
  53578. const srcRenderTargetProperties = properties.get( srcTextureProperties.__renderTarget );
  53579. const dstRenderTargetProperties = properties.get( dstTextureProperties.__renderTarget );
  53580. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer );
  53581. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer );
  53582. for ( let i = 0; i < depth; i ++ ) {
  53583. // if the source or destination are a 3d target then a layer needs to be bound
  53584. if ( isSrc3D ) {
  53585. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( srcTexture ).__webglTexture, srcLevel, minZ + i );
  53586. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( dstTexture ).__webglTexture, dstLevel, dstZ + i );
  53587. }
  53588. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST );
  53589. }
  53590. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  53591. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  53592. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has( srcTexture ) ) {
  53593. // get the appropriate frame buffers
  53594. const srcTextureProperties = properties.get( srcTexture );
  53595. const dstTextureProperties = properties.get( dstTexture );
  53596. // bind the frame buffer targets
  53597. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, _srcFramebuffer );
  53598. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, _dstFramebuffer );
  53599. for ( let i = 0; i < depth; i ++ ) {
  53600. // assign the correct layers and mip maps to the frame buffers
  53601. if ( isSrc3D ) {
  53602. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i );
  53603. } else {
  53604. _gl.framebufferTexture2D( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel );
  53605. }
  53606. if ( isDst3D ) {
  53607. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i );
  53608. } else {
  53609. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel );
  53610. }
  53611. // copy the data using the fastest function that can achieve the copy
  53612. if ( srcLevel !== 0 ) {
  53613. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.COLOR_BUFFER_BIT, _gl.NEAREST );
  53614. } else if ( isDst3D ) {
  53615. _gl.copyTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  53616. } else {
  53617. _gl.copyTexSubImage2D( glTarget, dstLevel, dstX, dstY, minX, minY, width, height );
  53618. }
  53619. }
  53620. // unbind read, draw buffers
  53621. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  53622. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  53623. } else {
  53624. if ( isDst3D ) {
  53625. // copy data into the 3d texture
  53626. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  53627. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  53628. } else if ( dstTexture.isCompressedArrayTexture ) {
  53629. _gl.compressedTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  53630. } else {
  53631. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  53632. }
  53633. } else {
  53634. // copy data into the 2d texture
  53635. if ( srcTexture.isDataTexture ) {
  53636. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  53637. } else if ( srcTexture.isCompressedTexture ) {
  53638. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  53639. } else {
  53640. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  53641. }
  53642. }
  53643. }
  53644. // reset values
  53645. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  53646. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  53647. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  53648. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  53649. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  53650. // Generate mipmaps only when copying level 0
  53651. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  53652. _gl.generateMipmap( glTarget );
  53653. }
  53654. state.unbindTexture();
  53655. };
  53656. /**
  53657. * Initializes the given WebGLRenderTarget memory. Useful for initializing a render target so data
  53658. * can be copied into it using {@link WebGLRenderer#copyTextureToTexture} before it has been
  53659. * rendered to.
  53660. *
  53661. * @param {WebGLRenderTarget} target - The render target.
  53662. */
  53663. this.initRenderTarget = function ( target ) {
  53664. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  53665. textures.setupRenderTarget( target );
  53666. }
  53667. };
  53668. /**
  53669. * Initializes the given texture. Useful for preloading a texture rather than waiting until first
  53670. * render (which can cause noticeable lags due to decode and GPU upload overhead).
  53671. *
  53672. * @param {Texture} texture - The texture.
  53673. */
  53674. this.initTexture = function ( texture ) {
  53675. if ( texture.isCubeTexture ) {
  53676. textures.setTextureCube( texture, 0 );
  53677. } else if ( texture.isData3DTexture ) {
  53678. textures.setTexture3D( texture, 0 );
  53679. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  53680. textures.setTexture2DArray( texture, 0 );
  53681. } else {
  53682. textures.setTexture2D( texture, 0 );
  53683. }
  53684. state.unbindTexture();
  53685. };
  53686. /**
  53687. * Can be used to reset the internal WebGL state. This method is mostly
  53688. * relevant for applications which share a single WebGL context across
  53689. * multiple WebGL libraries.
  53690. */
  53691. this.resetState = function () {
  53692. _currentActiveCubeFace = 0;
  53693. _currentActiveMipmapLevel = 0;
  53694. _currentRenderTarget = null;
  53695. state.reset();
  53696. bindingStates.reset();
  53697. };
  53698. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  53699. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  53700. }
  53701. }
  53702. /**
  53703. * Defines the coordinate system of the renderer.
  53704. *
  53705. * In `WebGLRenderer`, the value is always `WebGLCoordinateSystem`.
  53706. *
  53707. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  53708. * @default WebGLCoordinateSystem
  53709. * @readonly
  53710. */
  53711. get coordinateSystem() {
  53712. return WebGLCoordinateSystem;
  53713. }
  53714. /**
  53715. * Defines the output color space of the renderer.
  53716. *
  53717. * @type {SRGBColorSpace|LinearSRGBColorSpace}
  53718. * @default SRGBColorSpace
  53719. */
  53720. get outputColorSpace() {
  53721. return this._outputColorSpace;
  53722. }
  53723. set outputColorSpace( colorSpace ) {
  53724. this._outputColorSpace = colorSpace;
  53725. const gl = this.getContext();
  53726. gl.drawingBufferColorSpace = ColorManagement._getDrawingBufferColorSpace( colorSpace );
  53727. gl.unpackColorSpace = ColorManagement._getUnpackColorSpace();
  53728. }
  53729. }
  53730. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  53731. exports.AddEquation = AddEquation;
  53732. exports.AddOperation = AddOperation;
  53733. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  53734. exports.AdditiveBlending = AdditiveBlending;
  53735. exports.AgXToneMapping = AgXToneMapping;
  53736. exports.AlphaFormat = AlphaFormat;
  53737. exports.AlwaysCompare = AlwaysCompare;
  53738. exports.AlwaysDepth = AlwaysDepth;
  53739. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  53740. exports.AmbientLight = AmbientLight;
  53741. exports.AnimationAction = AnimationAction;
  53742. exports.AnimationClip = AnimationClip;
  53743. exports.AnimationLoader = AnimationLoader;
  53744. exports.AnimationMixer = AnimationMixer;
  53745. exports.AnimationObjectGroup = AnimationObjectGroup;
  53746. exports.AnimationUtils = AnimationUtils;
  53747. exports.ArcCurve = ArcCurve;
  53748. exports.ArrayCamera = ArrayCamera;
  53749. exports.ArrowHelper = ArrowHelper;
  53750. exports.AttachedBindMode = AttachedBindMode;
  53751. exports.Audio = Audio;
  53752. exports.AudioAnalyser = AudioAnalyser;
  53753. exports.AudioContext = AudioContext;
  53754. exports.AudioListener = AudioListener;
  53755. exports.AudioLoader = AudioLoader;
  53756. exports.AxesHelper = AxesHelper;
  53757. exports.BackSide = BackSide;
  53758. exports.BasicDepthPacking = BasicDepthPacking;
  53759. exports.BasicShadowMap = BasicShadowMap;
  53760. exports.BatchedMesh = BatchedMesh;
  53761. exports.Bone = Bone;
  53762. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  53763. exports.Box2 = Box2;
  53764. exports.Box3 = Box3;
  53765. exports.Box3Helper = Box3Helper;
  53766. exports.BoxGeometry = BoxGeometry;
  53767. exports.BoxHelper = BoxHelper;
  53768. exports.BufferAttribute = BufferAttribute;
  53769. exports.BufferGeometry = BufferGeometry;
  53770. exports.BufferGeometryLoader = BufferGeometryLoader;
  53771. exports.ByteType = ByteType;
  53772. exports.Cache = Cache;
  53773. exports.Camera = Camera;
  53774. exports.CameraHelper = CameraHelper;
  53775. exports.CanvasTexture = CanvasTexture;
  53776. exports.CapsuleGeometry = CapsuleGeometry;
  53777. exports.CatmullRomCurve3 = CatmullRomCurve3;
  53778. exports.CineonToneMapping = CineonToneMapping;
  53779. exports.CircleGeometry = CircleGeometry;
  53780. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  53781. exports.Clock = Clock;
  53782. exports.Color = Color;
  53783. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  53784. exports.ColorManagement = ColorManagement;
  53785. exports.CompressedArrayTexture = CompressedArrayTexture;
  53786. exports.CompressedCubeTexture = CompressedCubeTexture;
  53787. exports.CompressedTexture = CompressedTexture;
  53788. exports.CompressedTextureLoader = CompressedTextureLoader;
  53789. exports.ConeGeometry = ConeGeometry;
  53790. exports.ConstantAlphaFactor = ConstantAlphaFactor;
  53791. exports.ConstantColorFactor = ConstantColorFactor;
  53792. exports.Controls = Controls;
  53793. exports.CubeCamera = CubeCamera;
  53794. exports.CubeReflectionMapping = CubeReflectionMapping;
  53795. exports.CubeRefractionMapping = CubeRefractionMapping;
  53796. exports.CubeTexture = CubeTexture;
  53797. exports.CubeTextureLoader = CubeTextureLoader;
  53798. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  53799. exports.CubicBezierCurve = CubicBezierCurve;
  53800. exports.CubicBezierCurve3 = CubicBezierCurve3;
  53801. exports.CubicInterpolant = CubicInterpolant;
  53802. exports.CullFaceBack = CullFaceBack;
  53803. exports.CullFaceFront = CullFaceFront;
  53804. exports.CullFaceFrontBack = CullFaceFrontBack;
  53805. exports.CullFaceNone = CullFaceNone;
  53806. exports.Curve = Curve;
  53807. exports.CurvePath = CurvePath;
  53808. exports.CustomBlending = CustomBlending;
  53809. exports.CustomToneMapping = CustomToneMapping;
  53810. exports.CylinderGeometry = CylinderGeometry;
  53811. exports.Cylindrical = Cylindrical;
  53812. exports.Data3DTexture = Data3DTexture;
  53813. exports.DataArrayTexture = DataArrayTexture;
  53814. exports.DataTexture = DataTexture;
  53815. exports.DataTextureLoader = DataTextureLoader;
  53816. exports.DataUtils = DataUtils;
  53817. exports.DecrementStencilOp = DecrementStencilOp;
  53818. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  53819. exports.DefaultLoadingManager = DefaultLoadingManager;
  53820. exports.DepthFormat = DepthFormat;
  53821. exports.DepthStencilFormat = DepthStencilFormat;
  53822. exports.DepthTexture = DepthTexture;
  53823. exports.DetachedBindMode = DetachedBindMode;
  53824. exports.DirectionalLight = DirectionalLight;
  53825. exports.DirectionalLightHelper = DirectionalLightHelper;
  53826. exports.DiscreteInterpolant = DiscreteInterpolant;
  53827. exports.DodecahedronGeometry = DodecahedronGeometry;
  53828. exports.DoubleSide = DoubleSide;
  53829. exports.DstAlphaFactor = DstAlphaFactor;
  53830. exports.DstColorFactor = DstColorFactor;
  53831. exports.DynamicCopyUsage = DynamicCopyUsage;
  53832. exports.DynamicDrawUsage = DynamicDrawUsage;
  53833. exports.DynamicReadUsage = DynamicReadUsage;
  53834. exports.EdgesGeometry = EdgesGeometry;
  53835. exports.EllipseCurve = EllipseCurve;
  53836. exports.EqualCompare = EqualCompare;
  53837. exports.EqualDepth = EqualDepth;
  53838. exports.EqualStencilFunc = EqualStencilFunc;
  53839. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  53840. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  53841. exports.Euler = Euler;
  53842. exports.EventDispatcher = EventDispatcher;
  53843. exports.ExtrudeGeometry = ExtrudeGeometry;
  53844. exports.FileLoader = FileLoader;
  53845. exports.Float16BufferAttribute = Float16BufferAttribute;
  53846. exports.Float32BufferAttribute = Float32BufferAttribute;
  53847. exports.FloatType = FloatType;
  53848. exports.Fog = Fog;
  53849. exports.FogExp2 = FogExp2;
  53850. exports.FramebufferTexture = FramebufferTexture;
  53851. exports.FrontSide = FrontSide;
  53852. exports.Frustum = Frustum;
  53853. exports.FrustumArray = FrustumArray;
  53854. exports.GLBufferAttribute = GLBufferAttribute;
  53855. exports.GLSL1 = GLSL1;
  53856. exports.GLSL3 = GLSL3;
  53857. exports.GreaterCompare = GreaterCompare;
  53858. exports.GreaterDepth = GreaterDepth;
  53859. exports.GreaterEqualCompare = GreaterEqualCompare;
  53860. exports.GreaterEqualDepth = GreaterEqualDepth;
  53861. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  53862. exports.GreaterStencilFunc = GreaterStencilFunc;
  53863. exports.GridHelper = GridHelper;
  53864. exports.Group = Group;
  53865. exports.HalfFloatType = HalfFloatType;
  53866. exports.HemisphereLight = HemisphereLight;
  53867. exports.HemisphereLightHelper = HemisphereLightHelper;
  53868. exports.IcosahedronGeometry = IcosahedronGeometry;
  53869. exports.ImageBitmapLoader = ImageBitmapLoader;
  53870. exports.ImageLoader = ImageLoader;
  53871. exports.ImageUtils = ImageUtils;
  53872. exports.IncrementStencilOp = IncrementStencilOp;
  53873. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  53874. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  53875. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  53876. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  53877. exports.InstancedMesh = InstancedMesh;
  53878. exports.Int16BufferAttribute = Int16BufferAttribute;
  53879. exports.Int32BufferAttribute = Int32BufferAttribute;
  53880. exports.Int8BufferAttribute = Int8BufferAttribute;
  53881. exports.IntType = IntType;
  53882. exports.InterleavedBuffer = InterleavedBuffer;
  53883. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  53884. exports.Interpolant = Interpolant;
  53885. exports.InterpolateDiscrete = InterpolateDiscrete;
  53886. exports.InterpolateLinear = InterpolateLinear;
  53887. exports.InterpolateSmooth = InterpolateSmooth;
  53888. exports.InterpolationSamplingMode = InterpolationSamplingMode;
  53889. exports.InterpolationSamplingType = InterpolationSamplingType;
  53890. exports.InvertStencilOp = InvertStencilOp;
  53891. exports.KeepStencilOp = KeepStencilOp;
  53892. exports.KeyframeTrack = KeyframeTrack;
  53893. exports.LOD = LOD;
  53894. exports.LatheGeometry = LatheGeometry;
  53895. exports.Layers = Layers;
  53896. exports.LessCompare = LessCompare;
  53897. exports.LessDepth = LessDepth;
  53898. exports.LessEqualCompare = LessEqualCompare;
  53899. exports.LessEqualDepth = LessEqualDepth;
  53900. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  53901. exports.LessStencilFunc = LessStencilFunc;
  53902. exports.Light = Light;
  53903. exports.LightProbe = LightProbe;
  53904. exports.Line = Line;
  53905. exports.Line3 = Line3;
  53906. exports.LineBasicMaterial = LineBasicMaterial;
  53907. exports.LineCurve = LineCurve;
  53908. exports.LineCurve3 = LineCurve3;
  53909. exports.LineDashedMaterial = LineDashedMaterial;
  53910. exports.LineLoop = LineLoop;
  53911. exports.LineSegments = LineSegments;
  53912. exports.LinearFilter = LinearFilter;
  53913. exports.LinearInterpolant = LinearInterpolant;
  53914. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  53915. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  53916. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  53917. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  53918. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  53919. exports.LinearToneMapping = LinearToneMapping;
  53920. exports.LinearTransfer = LinearTransfer;
  53921. exports.Loader = Loader;
  53922. exports.LoaderUtils = LoaderUtils;
  53923. exports.LoadingManager = LoadingManager;
  53924. exports.LoopOnce = LoopOnce;
  53925. exports.LoopPingPong = LoopPingPong;
  53926. exports.LoopRepeat = LoopRepeat;
  53927. exports.MOUSE = MOUSE;
  53928. exports.Material = Material;
  53929. exports.MaterialLoader = MaterialLoader;
  53930. exports.MathUtils = MathUtils;
  53931. exports.Matrix2 = Matrix2;
  53932. exports.Matrix3 = Matrix3;
  53933. exports.Matrix4 = Matrix4;
  53934. exports.MaxEquation = MaxEquation;
  53935. exports.Mesh = Mesh;
  53936. exports.MeshBasicMaterial = MeshBasicMaterial;
  53937. exports.MeshDepthMaterial = MeshDepthMaterial;
  53938. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  53939. exports.MeshLambertMaterial = MeshLambertMaterial;
  53940. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  53941. exports.MeshNormalMaterial = MeshNormalMaterial;
  53942. exports.MeshPhongMaterial = MeshPhongMaterial;
  53943. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  53944. exports.MeshStandardMaterial = MeshStandardMaterial;
  53945. exports.MeshToonMaterial = MeshToonMaterial;
  53946. exports.MinEquation = MinEquation;
  53947. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  53948. exports.MixOperation = MixOperation;
  53949. exports.MultiplyBlending = MultiplyBlending;
  53950. exports.MultiplyOperation = MultiplyOperation;
  53951. exports.NearestFilter = NearestFilter;
  53952. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  53953. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  53954. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  53955. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  53956. exports.NeutralToneMapping = NeutralToneMapping;
  53957. exports.NeverCompare = NeverCompare;
  53958. exports.NeverDepth = NeverDepth;
  53959. exports.NeverStencilFunc = NeverStencilFunc;
  53960. exports.NoBlending = NoBlending;
  53961. exports.NoColorSpace = NoColorSpace;
  53962. exports.NoToneMapping = NoToneMapping;
  53963. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  53964. exports.NormalBlending = NormalBlending;
  53965. exports.NotEqualCompare = NotEqualCompare;
  53966. exports.NotEqualDepth = NotEqualDepth;
  53967. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  53968. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  53969. exports.Object3D = Object3D;
  53970. exports.ObjectLoader = ObjectLoader;
  53971. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  53972. exports.OctahedronGeometry = OctahedronGeometry;
  53973. exports.OneFactor = OneFactor;
  53974. exports.OneMinusConstantAlphaFactor = OneMinusConstantAlphaFactor;
  53975. exports.OneMinusConstantColorFactor = OneMinusConstantColorFactor;
  53976. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  53977. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  53978. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  53979. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  53980. exports.OrthographicCamera = OrthographicCamera;
  53981. exports.PCFShadowMap = PCFShadowMap;
  53982. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  53983. exports.PMREMGenerator = PMREMGenerator;
  53984. exports.Path = Path;
  53985. exports.PerspectiveCamera = PerspectiveCamera;
  53986. exports.Plane = Plane;
  53987. exports.PlaneGeometry = PlaneGeometry;
  53988. exports.PlaneHelper = PlaneHelper;
  53989. exports.PointLight = PointLight;
  53990. exports.PointLightHelper = PointLightHelper;
  53991. exports.Points = Points;
  53992. exports.PointsMaterial = PointsMaterial;
  53993. exports.PolarGridHelper = PolarGridHelper;
  53994. exports.PolyhedronGeometry = PolyhedronGeometry;
  53995. exports.PositionalAudio = PositionalAudio;
  53996. exports.PropertyBinding = PropertyBinding;
  53997. exports.PropertyMixer = PropertyMixer;
  53998. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  53999. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  54000. exports.Quaternion = Quaternion;
  54001. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  54002. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  54003. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  54004. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  54005. exports.REVISION = REVISION;
  54006. exports.RGBADepthPacking = RGBADepthPacking;
  54007. exports.RGBAFormat = RGBAFormat;
  54008. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  54009. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  54010. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  54011. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  54012. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  54013. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  54014. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  54015. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  54016. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  54017. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  54018. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  54019. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  54020. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  54021. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  54022. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  54023. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  54024. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  54025. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  54026. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  54027. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  54028. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  54029. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  54030. exports.RGBDepthPacking = RGBDepthPacking;
  54031. exports.RGBFormat = RGBFormat;
  54032. exports.RGBIntegerFormat = RGBIntegerFormat;
  54033. exports.RGB_BPTC_SIGNED_Format = RGB_BPTC_SIGNED_Format;
  54034. exports.RGB_BPTC_UNSIGNED_Format = RGB_BPTC_UNSIGNED_Format;
  54035. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  54036. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  54037. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  54038. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  54039. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  54040. exports.RGDepthPacking = RGDepthPacking;
  54041. exports.RGFormat = RGFormat;
  54042. exports.RGIntegerFormat = RGIntegerFormat;
  54043. exports.RawShaderMaterial = RawShaderMaterial;
  54044. exports.Ray = Ray;
  54045. exports.Raycaster = Raycaster;
  54046. exports.RectAreaLight = RectAreaLight;
  54047. exports.RedFormat = RedFormat;
  54048. exports.RedIntegerFormat = RedIntegerFormat;
  54049. exports.ReinhardToneMapping = ReinhardToneMapping;
  54050. exports.RenderTarget = RenderTarget;
  54051. exports.RenderTarget3D = RenderTarget3D;
  54052. exports.RepeatWrapping = RepeatWrapping;
  54053. exports.ReplaceStencilOp = ReplaceStencilOp;
  54054. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  54055. exports.RingGeometry = RingGeometry;
  54056. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  54057. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  54058. exports.SRGBColorSpace = SRGBColorSpace;
  54059. exports.SRGBTransfer = SRGBTransfer;
  54060. exports.Scene = Scene;
  54061. exports.ShaderChunk = ShaderChunk;
  54062. exports.ShaderLib = ShaderLib;
  54063. exports.ShaderMaterial = ShaderMaterial;
  54064. exports.ShadowMaterial = ShadowMaterial;
  54065. exports.Shape = Shape;
  54066. exports.ShapeGeometry = ShapeGeometry;
  54067. exports.ShapePath = ShapePath;
  54068. exports.ShapeUtils = ShapeUtils;
  54069. exports.ShortType = ShortType;
  54070. exports.Skeleton = Skeleton;
  54071. exports.SkeletonHelper = SkeletonHelper;
  54072. exports.SkinnedMesh = SkinnedMesh;
  54073. exports.Source = Source;
  54074. exports.Sphere = Sphere;
  54075. exports.SphereGeometry = SphereGeometry;
  54076. exports.Spherical = Spherical;
  54077. exports.SphericalHarmonics3 = SphericalHarmonics3;
  54078. exports.SplineCurve = SplineCurve;
  54079. exports.SpotLight = SpotLight;
  54080. exports.SpotLightHelper = SpotLightHelper;
  54081. exports.Sprite = Sprite;
  54082. exports.SpriteMaterial = SpriteMaterial;
  54083. exports.SrcAlphaFactor = SrcAlphaFactor;
  54084. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  54085. exports.SrcColorFactor = SrcColorFactor;
  54086. exports.StaticCopyUsage = StaticCopyUsage;
  54087. exports.StaticDrawUsage = StaticDrawUsage;
  54088. exports.StaticReadUsage = StaticReadUsage;
  54089. exports.StereoCamera = StereoCamera;
  54090. exports.StreamCopyUsage = StreamCopyUsage;
  54091. exports.StreamDrawUsage = StreamDrawUsage;
  54092. exports.StreamReadUsage = StreamReadUsage;
  54093. exports.StringKeyframeTrack = StringKeyframeTrack;
  54094. exports.SubtractEquation = SubtractEquation;
  54095. exports.SubtractiveBlending = SubtractiveBlending;
  54096. exports.TOUCH = TOUCH;
  54097. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  54098. exports.TetrahedronGeometry = TetrahedronGeometry;
  54099. exports.Texture = Texture;
  54100. exports.TextureLoader = TextureLoader;
  54101. exports.TextureUtils = TextureUtils;
  54102. exports.Timer = Timer;
  54103. exports.TimestampQuery = TimestampQuery;
  54104. exports.TorusGeometry = TorusGeometry;
  54105. exports.TorusKnotGeometry = TorusKnotGeometry;
  54106. exports.Triangle = Triangle;
  54107. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  54108. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  54109. exports.TrianglesDrawMode = TrianglesDrawMode;
  54110. exports.TubeGeometry = TubeGeometry;
  54111. exports.UVMapping = UVMapping;
  54112. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  54113. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  54114. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  54115. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  54116. exports.Uniform = Uniform;
  54117. exports.UniformsGroup = UniformsGroup;
  54118. exports.UniformsLib = UniformsLib;
  54119. exports.UniformsUtils = UniformsUtils;
  54120. exports.UnsignedByteType = UnsignedByteType;
  54121. exports.UnsignedInt248Type = UnsignedInt248Type;
  54122. exports.UnsignedInt5999Type = UnsignedInt5999Type;
  54123. exports.UnsignedIntType = UnsignedIntType;
  54124. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  54125. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  54126. exports.UnsignedShortType = UnsignedShortType;
  54127. exports.VSMShadowMap = VSMShadowMap;
  54128. exports.Vector2 = Vector2;
  54129. exports.Vector3 = Vector3;
  54130. exports.Vector4 = Vector4;
  54131. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  54132. exports.VideoFrameTexture = VideoFrameTexture;
  54133. exports.VideoTexture = VideoTexture;
  54134. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  54135. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  54136. exports.WebGLCoordinateSystem = WebGLCoordinateSystem;
  54137. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  54138. exports.WebGLRenderTarget = WebGLRenderTarget;
  54139. exports.WebGLRenderer = WebGLRenderer;
  54140. exports.WebGLUtils = WebGLUtils;
  54141. exports.WebGPUCoordinateSystem = WebGPUCoordinateSystem;
  54142. exports.WebXRController = WebXRController;
  54143. exports.WireframeGeometry = WireframeGeometry;
  54144. exports.WrapAroundEnding = WrapAroundEnding;
  54145. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  54146. exports.ZeroFactor = ZeroFactor;
  54147. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  54148. exports.ZeroStencilOp = ZeroStencilOp;
  54149. exports.createCanvasElement = createCanvasElement;
粤ICP备19079148号