three.cjs 1.9 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. 'use strict';
  7. const REVISION = '176';
  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. FLAT_FIRST: 'flat first',
  1426. FLAT_EITHER: 'flat 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. * Represents a 3x3 matrix.
  2793. *
  2794. * A Note on Row-Major and Column-Major Ordering:
  2795. *
  2796. * The constructor and {@link Matrix3#set} method take arguments in
  2797. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  2798. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  2799. * This means that calling:
  2800. * ```js
  2801. * const m = new THREE.Matrix();
  2802. * m.set( 11, 12, 13,
  2803. * 21, 22, 23,
  2804. * 31, 32, 33 );
  2805. * ```
  2806. * will result in the elements array containing:
  2807. * ```js
  2808. * m.elements = [ 11, 21, 31,
  2809. * 12, 22, 32,
  2810. * 13, 23, 33 ];
  2811. * ```
  2812. * and internally all calculations are performed using column-major ordering.
  2813. * However, as the actual ordering makes no difference mathematically and
  2814. * most people are used to thinking about matrices in row-major order, the
  2815. * three.js documentation shows matrices in row-major order. Just bear in
  2816. * mind that if you are reading the source code, you'll have to take the
  2817. * transpose of any matrices outlined here to make sense of the calculations.
  2818. */
  2819. class Matrix3 {
  2820. /**
  2821. * Constructs a new 3x3 matrix. The arguments are supposed to be
  2822. * in row-major order. If no arguments are provided, the constructor
  2823. * initializes the matrix as an identity matrix.
  2824. *
  2825. * @param {number} [n11] - 1-1 matrix element.
  2826. * @param {number} [n12] - 1-2 matrix element.
  2827. * @param {number} [n13] - 1-3 matrix element.
  2828. * @param {number} [n21] - 2-1 matrix element.
  2829. * @param {number} [n22] - 2-2 matrix element.
  2830. * @param {number} [n23] - 2-3 matrix element.
  2831. * @param {number} [n31] - 3-1 matrix element.
  2832. * @param {number} [n32] - 3-2 matrix element.
  2833. * @param {number} [n33] - 3-3 matrix element.
  2834. */
  2835. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2836. /**
  2837. * This flag can be used for type testing.
  2838. *
  2839. * @type {boolean}
  2840. * @readonly
  2841. * @default true
  2842. */
  2843. Matrix3.prototype.isMatrix3 = true;
  2844. /**
  2845. * A column-major list of matrix values.
  2846. *
  2847. * @type {Array<number>}
  2848. */
  2849. this.elements = [
  2850. 1, 0, 0,
  2851. 0, 1, 0,
  2852. 0, 0, 1
  2853. ];
  2854. if ( n11 !== undefined ) {
  2855. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  2856. }
  2857. }
  2858. /**
  2859. * Sets the elements of the matrix.The arguments are supposed to be
  2860. * in row-major order.
  2861. *
  2862. * @param {number} [n11] - 1-1 matrix element.
  2863. * @param {number} [n12] - 1-2 matrix element.
  2864. * @param {number} [n13] - 1-3 matrix element.
  2865. * @param {number} [n21] - 2-1 matrix element.
  2866. * @param {number} [n22] - 2-2 matrix element.
  2867. * @param {number} [n23] - 2-3 matrix element.
  2868. * @param {number} [n31] - 3-1 matrix element.
  2869. * @param {number} [n32] - 3-2 matrix element.
  2870. * @param {number} [n33] - 3-3 matrix element.
  2871. * @return {Matrix3} A reference to this matrix.
  2872. */
  2873. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2874. const te = this.elements;
  2875. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  2876. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  2877. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  2878. return this;
  2879. }
  2880. /**
  2881. * Sets this matrix to the 3x3 identity matrix.
  2882. *
  2883. * @return {Matrix3} A reference to this matrix.
  2884. */
  2885. identity() {
  2886. this.set(
  2887. 1, 0, 0,
  2888. 0, 1, 0,
  2889. 0, 0, 1
  2890. );
  2891. return this;
  2892. }
  2893. /**
  2894. * Copies the values of the given matrix to this instance.
  2895. *
  2896. * @param {Matrix3} m - The matrix to copy.
  2897. * @return {Matrix3} A reference to this matrix.
  2898. */
  2899. copy( m ) {
  2900. const te = this.elements;
  2901. const me = m.elements;
  2902. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  2903. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  2904. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  2905. return this;
  2906. }
  2907. /**
  2908. * Extracts the basis of this matrix into the three axis vectors provided.
  2909. *
  2910. * @param {Vector3} xAxis - The basis's x axis.
  2911. * @param {Vector3} yAxis - The basis's y axis.
  2912. * @param {Vector3} zAxis - The basis's z axis.
  2913. * @return {Matrix3} A reference to this matrix.
  2914. */
  2915. extractBasis( xAxis, yAxis, zAxis ) {
  2916. xAxis.setFromMatrix3Column( this, 0 );
  2917. yAxis.setFromMatrix3Column( this, 1 );
  2918. zAxis.setFromMatrix3Column( this, 2 );
  2919. return this;
  2920. }
  2921. /**
  2922. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  2923. *
  2924. * @param {Matrix4} m - The 4x4 matrix.
  2925. * @return {Matrix3} A reference to this matrix.
  2926. */
  2927. setFromMatrix4( m ) {
  2928. const me = m.elements;
  2929. this.set(
  2930. me[ 0 ], me[ 4 ], me[ 8 ],
  2931. me[ 1 ], me[ 5 ], me[ 9 ],
  2932. me[ 2 ], me[ 6 ], me[ 10 ]
  2933. );
  2934. return this;
  2935. }
  2936. /**
  2937. * Post-multiplies this matrix by the given 3x3 matrix.
  2938. *
  2939. * @param {Matrix3} m - The matrix to multiply with.
  2940. * @return {Matrix3} A reference to this matrix.
  2941. */
  2942. multiply( m ) {
  2943. return this.multiplyMatrices( this, m );
  2944. }
  2945. /**
  2946. * Pre-multiplies this matrix by the given 3x3 matrix.
  2947. *
  2948. * @param {Matrix3} m - The matrix to multiply with.
  2949. * @return {Matrix3} A reference to this matrix.
  2950. */
  2951. premultiply( m ) {
  2952. return this.multiplyMatrices( m, this );
  2953. }
  2954. /**
  2955. * Multiples the given 3x3 matrices and stores the result
  2956. * in this matrix.
  2957. *
  2958. * @param {Matrix3} a - The first matrix.
  2959. * @param {Matrix3} b - The second matrix.
  2960. * @return {Matrix3} A reference to this matrix.
  2961. */
  2962. multiplyMatrices( a, b ) {
  2963. const ae = a.elements;
  2964. const be = b.elements;
  2965. const te = this.elements;
  2966. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  2967. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  2968. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  2969. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  2970. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  2971. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  2972. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  2973. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  2974. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  2975. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  2976. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  2977. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  2978. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  2979. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  2980. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  2981. return this;
  2982. }
  2983. /**
  2984. * Multiplies every component of the matrix by the given scalar.
  2985. *
  2986. * @param {number} s - The scalar.
  2987. * @return {Matrix3} A reference to this matrix.
  2988. */
  2989. multiplyScalar( s ) {
  2990. const te = this.elements;
  2991. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  2992. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  2993. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  2994. return this;
  2995. }
  2996. /**
  2997. * Computes and returns the determinant of this matrix.
  2998. *
  2999. * @return {number} The determinant.
  3000. */
  3001. determinant() {
  3002. const te = this.elements;
  3003. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  3004. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  3005. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  3006. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  3007. }
  3008. /**
  3009. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  3010. * You can not invert with a determinant of zero. If you attempt this, the method produces
  3011. * a zero matrix instead.
  3012. *
  3013. * @return {Matrix3} A reference to this matrix.
  3014. */
  3015. invert() {
  3016. const te = this.elements,
  3017. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  3018. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  3019. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  3020. t11 = n33 * n22 - n32 * n23,
  3021. t12 = n32 * n13 - n33 * n12,
  3022. t13 = n23 * n12 - n22 * n13,
  3023. det = n11 * t11 + n21 * t12 + n31 * t13;
  3024. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3025. const detInv = 1 / det;
  3026. te[ 0 ] = t11 * detInv;
  3027. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  3028. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  3029. te[ 3 ] = t12 * detInv;
  3030. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  3031. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  3032. te[ 6 ] = t13 * detInv;
  3033. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  3034. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  3035. return this;
  3036. }
  3037. /**
  3038. * Transposes this matrix in place.
  3039. *
  3040. * @return {Matrix3} A reference to this matrix.
  3041. */
  3042. transpose() {
  3043. let tmp;
  3044. const m = this.elements;
  3045. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  3046. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  3047. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  3048. return this;
  3049. }
  3050. /**
  3051. * Computes the normal matrix which is the inverse transpose of the upper
  3052. * left 3x3 portion of the given 4x4 matrix.
  3053. *
  3054. * @param {Matrix4} matrix4 - The 4x4 matrix.
  3055. * @return {Matrix3} A reference to this matrix.
  3056. */
  3057. getNormalMatrix( matrix4 ) {
  3058. return this.setFromMatrix4( matrix4 ).invert().transpose();
  3059. }
  3060. /**
  3061. * Transposes this matrix into the supplied array, and returns itself unchanged.
  3062. *
  3063. * @param {Array<number>} r - An array to store the transposed matrix elements.
  3064. * @return {Matrix3} A reference to this matrix.
  3065. */
  3066. transposeIntoArray( r ) {
  3067. const m = this.elements;
  3068. r[ 0 ] = m[ 0 ];
  3069. r[ 1 ] = m[ 3 ];
  3070. r[ 2 ] = m[ 6 ];
  3071. r[ 3 ] = m[ 1 ];
  3072. r[ 4 ] = m[ 4 ];
  3073. r[ 5 ] = m[ 7 ];
  3074. r[ 6 ] = m[ 2 ];
  3075. r[ 7 ] = m[ 5 ];
  3076. r[ 8 ] = m[ 8 ];
  3077. return this;
  3078. }
  3079. /**
  3080. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  3081. *
  3082. * @param {number} tx - Offset x.
  3083. * @param {number} ty - Offset y.
  3084. * @param {number} sx - Repeat x.
  3085. * @param {number} sy - Repeat y.
  3086. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  3087. * @param {number} cx - Center x of rotation.
  3088. * @param {number} cy - Center y of rotation
  3089. * @return {Matrix3} A reference to this matrix.
  3090. */
  3091. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  3092. const c = Math.cos( rotation );
  3093. const s = Math.sin( rotation );
  3094. this.set(
  3095. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  3096. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  3097. 0, 0, 1
  3098. );
  3099. return this;
  3100. }
  3101. /**
  3102. * Scales this matrix with the given scalar values.
  3103. *
  3104. * @param {number} sx - The amount to scale in the X axis.
  3105. * @param {number} sy - The amount to scale in the Y axis.
  3106. * @return {Matrix3} A reference to this matrix.
  3107. */
  3108. scale( sx, sy ) {
  3109. this.premultiply( _m3.makeScale( sx, sy ) );
  3110. return this;
  3111. }
  3112. /**
  3113. * Rotates this matrix by the given angle.
  3114. *
  3115. * @param {number} theta - The rotation in radians.
  3116. * @return {Matrix3} A reference to this matrix.
  3117. */
  3118. rotate( theta ) {
  3119. this.premultiply( _m3.makeRotation( - theta ) );
  3120. return this;
  3121. }
  3122. /**
  3123. * Translates this matrix by the given scalar values.
  3124. *
  3125. * @param {number} tx - The amount to translate in the X axis.
  3126. * @param {number} ty - The amount to translate in the Y axis.
  3127. * @return {Matrix3} A reference to this matrix.
  3128. */
  3129. translate( tx, ty ) {
  3130. this.premultiply( _m3.makeTranslation( tx, ty ) );
  3131. return this;
  3132. }
  3133. // for 2D Transforms
  3134. /**
  3135. * Sets this matrix as a 2D translation transform.
  3136. *
  3137. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  3138. * @param {number} y - The amount to translate in the Y axis.
  3139. * @return {Matrix3} A reference to this matrix.
  3140. */
  3141. makeTranslation( x, y ) {
  3142. if ( x.isVector2 ) {
  3143. this.set(
  3144. 1, 0, x.x,
  3145. 0, 1, x.y,
  3146. 0, 0, 1
  3147. );
  3148. } else {
  3149. this.set(
  3150. 1, 0, x,
  3151. 0, 1, y,
  3152. 0, 0, 1
  3153. );
  3154. }
  3155. return this;
  3156. }
  3157. /**
  3158. * Sets this matrix as a 2D rotational transformation.
  3159. *
  3160. * @param {number} theta - The rotation in radians.
  3161. * @return {Matrix3} A reference to this matrix.
  3162. */
  3163. makeRotation( theta ) {
  3164. // counterclockwise
  3165. const c = Math.cos( theta );
  3166. const s = Math.sin( theta );
  3167. this.set(
  3168. c, - s, 0,
  3169. s, c, 0,
  3170. 0, 0, 1
  3171. );
  3172. return this;
  3173. }
  3174. /**
  3175. * Sets this matrix as a 2D scale transform.
  3176. *
  3177. * @param {number} x - The amount to scale in the X axis.
  3178. * @param {number} y - The amount to scale in the Y axis.
  3179. * @return {Matrix3} A reference to this matrix.
  3180. */
  3181. makeScale( x, y ) {
  3182. this.set(
  3183. x, 0, 0,
  3184. 0, y, 0,
  3185. 0, 0, 1
  3186. );
  3187. return this;
  3188. }
  3189. /**
  3190. * Returns `true` if this matrix is equal with the given one.
  3191. *
  3192. * @param {Matrix3} matrix - The matrix to test for equality.
  3193. * @return {boolean} Whether this matrix is equal with the given one.
  3194. */
  3195. equals( matrix ) {
  3196. const te = this.elements;
  3197. const me = matrix.elements;
  3198. for ( let i = 0; i < 9; i ++ ) {
  3199. if ( te[ i ] !== me[ i ] ) return false;
  3200. }
  3201. return true;
  3202. }
  3203. /**
  3204. * Sets the elements of the matrix from the given array.
  3205. *
  3206. * @param {Array<number>} array - The matrix elements in column-major order.
  3207. * @param {number} [offset=0] - Index of the first element in the array.
  3208. * @return {Matrix3} A reference to this matrix.
  3209. */
  3210. fromArray( array, offset = 0 ) {
  3211. for ( let i = 0; i < 9; i ++ ) {
  3212. this.elements[ i ] = array[ i + offset ];
  3213. }
  3214. return this;
  3215. }
  3216. /**
  3217. * Writes the elements of this matrix to the given array. If no array is provided,
  3218. * the method returns a new instance.
  3219. *
  3220. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  3221. * @param {number} [offset=0] - Index of the first element in the array.
  3222. * @return {Array<number>} The matrix elements in column-major order.
  3223. */
  3224. toArray( array = [], offset = 0 ) {
  3225. const te = this.elements;
  3226. array[ offset ] = te[ 0 ];
  3227. array[ offset + 1 ] = te[ 1 ];
  3228. array[ offset + 2 ] = te[ 2 ];
  3229. array[ offset + 3 ] = te[ 3 ];
  3230. array[ offset + 4 ] = te[ 4 ];
  3231. array[ offset + 5 ] = te[ 5 ];
  3232. array[ offset + 6 ] = te[ 6 ];
  3233. array[ offset + 7 ] = te[ 7 ];
  3234. array[ offset + 8 ] = te[ 8 ];
  3235. return array;
  3236. }
  3237. /**
  3238. * Returns a matrix with copied values from this instance.
  3239. *
  3240. * @return {Matrix3} A clone of this instance.
  3241. */
  3242. clone() {
  3243. return new this.constructor().fromArray( this.elements );
  3244. }
  3245. }
  3246. const _m3 = /*@__PURE__*/ new Matrix3();
  3247. function arrayNeedsUint32( array ) {
  3248. // assumes larger values usually on last
  3249. for ( let i = array.length - 1; i >= 0; -- i ) {
  3250. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  3251. }
  3252. return false;
  3253. }
  3254. const TYPED_ARRAYS = {
  3255. Int8Array: Int8Array,
  3256. Uint8Array: Uint8Array,
  3257. Uint8ClampedArray: Uint8ClampedArray,
  3258. Int16Array: Int16Array,
  3259. Uint16Array: Uint16Array,
  3260. Int32Array: Int32Array,
  3261. Uint32Array: Uint32Array,
  3262. Float32Array: Float32Array,
  3263. Float64Array: Float64Array
  3264. };
  3265. function getTypedArray( type, buffer ) {
  3266. return new TYPED_ARRAYS[ type ]( buffer );
  3267. }
  3268. function createElementNS( name ) {
  3269. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  3270. }
  3271. function createCanvasElement() {
  3272. const canvas = createElementNS( 'canvas' );
  3273. canvas.style.display = 'block';
  3274. return canvas;
  3275. }
  3276. const _cache = {};
  3277. function warnOnce( message ) {
  3278. if ( message in _cache ) return;
  3279. _cache[ message ] = true;
  3280. console.warn( message );
  3281. }
  3282. function probeAsync( gl, sync, interval ) {
  3283. return new Promise( function ( resolve, reject ) {
  3284. function probe() {
  3285. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  3286. case gl.WAIT_FAILED:
  3287. reject();
  3288. break;
  3289. case gl.TIMEOUT_EXPIRED:
  3290. setTimeout( probe, interval );
  3291. break;
  3292. default:
  3293. resolve();
  3294. }
  3295. }
  3296. setTimeout( probe, interval );
  3297. } );
  3298. }
  3299. function toNormalizedProjectionMatrix( projectionMatrix ) {
  3300. const m = projectionMatrix.elements;
  3301. // Convert [-1, 1] to [0, 1] projection matrix
  3302. m[ 2 ] = 0.5 * m[ 2 ] + 0.5 * m[ 3 ];
  3303. m[ 6 ] = 0.5 * m[ 6 ] + 0.5 * m[ 7 ];
  3304. m[ 10 ] = 0.5 * m[ 10 ] + 0.5 * m[ 11 ];
  3305. m[ 14 ] = 0.5 * m[ 14 ] + 0.5 * m[ 15 ];
  3306. }
  3307. function toReversedProjectionMatrix( projectionMatrix ) {
  3308. const m = projectionMatrix.elements;
  3309. const isPerspectiveMatrix = m[ 11 ] === -1;
  3310. // Reverse [0, 1] projection matrix
  3311. if ( isPerspectiveMatrix ) {
  3312. m[ 10 ] = - m[ 10 ] - 1;
  3313. m[ 14 ] = - m[ 14 ];
  3314. } else {
  3315. m[ 10 ] = - m[ 10 ];
  3316. m[ 14 ] = - m[ 14 ] + 1;
  3317. }
  3318. }
  3319. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  3320. 0.4123908, 0.3575843, 0.1804808,
  3321. 0.2126390, 0.7151687, 0.0721923,
  3322. 0.0193308, 0.1191948, 0.9505322
  3323. );
  3324. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  3325. 3.2409699, -1.5373832, -0.4986108,
  3326. -0.9692436, 1.8759675, 0.0415551,
  3327. 0.0556301, -0.203977, 1.0569715
  3328. );
  3329. function createColorManagement() {
  3330. const ColorManagement = {
  3331. enabled: true,
  3332. workingColorSpace: LinearSRGBColorSpace,
  3333. /**
  3334. * Implementations of supported color spaces.
  3335. *
  3336. * Required:
  3337. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  3338. * - whitePoint: reference white [ x y ]
  3339. * - transfer: transfer function (pre-defined)
  3340. * - toXYZ: Matrix3 RGB to XYZ transform
  3341. * - fromXYZ: Matrix3 XYZ to RGB transform
  3342. * - luminanceCoefficients: RGB luminance coefficients
  3343. *
  3344. * Optional:
  3345. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace }
  3346. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  3347. *
  3348. * Reference:
  3349. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  3350. */
  3351. spaces: {},
  3352. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  3353. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  3354. return color;
  3355. }
  3356. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  3357. color.r = SRGBToLinear( color.r );
  3358. color.g = SRGBToLinear( color.g );
  3359. color.b = SRGBToLinear( color.b );
  3360. }
  3361. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  3362. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  3363. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  3364. }
  3365. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  3366. color.r = LinearToSRGB( color.r );
  3367. color.g = LinearToSRGB( color.g );
  3368. color.b = LinearToSRGB( color.b );
  3369. }
  3370. return color;
  3371. },
  3372. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  3373. return this.convert( color, this.workingColorSpace, targetColorSpace );
  3374. },
  3375. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  3376. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  3377. },
  3378. getPrimaries: function ( colorSpace ) {
  3379. return this.spaces[ colorSpace ].primaries;
  3380. },
  3381. getTransfer: function ( colorSpace ) {
  3382. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  3383. return this.spaces[ colorSpace ].transfer;
  3384. },
  3385. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  3386. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  3387. },
  3388. define: function ( colorSpaces ) {
  3389. Object.assign( this.spaces, colorSpaces );
  3390. },
  3391. // Internal APIs
  3392. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  3393. return targetMatrix
  3394. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  3395. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  3396. },
  3397. _getDrawingBufferColorSpace: function ( colorSpace ) {
  3398. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  3399. },
  3400. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  3401. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  3402. }
  3403. };
  3404. /******************************************************************************
  3405. * sRGB definitions
  3406. */
  3407. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  3408. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  3409. const D65 = [ 0.3127, 0.3290 ];
  3410. ColorManagement.define( {
  3411. [ LinearSRGBColorSpace ]: {
  3412. primaries: REC709_PRIMARIES,
  3413. whitePoint: D65,
  3414. transfer: LinearTransfer,
  3415. toXYZ: LINEAR_REC709_TO_XYZ,
  3416. fromXYZ: XYZ_TO_LINEAR_REC709,
  3417. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  3418. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  3419. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  3420. },
  3421. [ SRGBColorSpace ]: {
  3422. primaries: REC709_PRIMARIES,
  3423. whitePoint: D65,
  3424. transfer: SRGBTransfer,
  3425. toXYZ: LINEAR_REC709_TO_XYZ,
  3426. fromXYZ: XYZ_TO_LINEAR_REC709,
  3427. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  3428. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  3429. },
  3430. } );
  3431. return ColorManagement;
  3432. }
  3433. const ColorManagement = /*@__PURE__*/ createColorManagement();
  3434. function SRGBToLinear( c ) {
  3435. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  3436. }
  3437. function LinearToSRGB( c ) {
  3438. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  3439. }
  3440. let _canvas;
  3441. /**
  3442. * A class containing utility functions for images.
  3443. *
  3444. * @hideconstructor
  3445. */
  3446. class ImageUtils {
  3447. /**
  3448. * Returns a data URI containing a representation of the given image.
  3449. *
  3450. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  3451. * @param {string} [type='image/png'] - Indicates the image format.
  3452. * @return {string} The data URI.
  3453. */
  3454. static getDataURL( image, type = 'image/png' ) {
  3455. if ( /^data:/i.test( image.src ) ) {
  3456. return image.src;
  3457. }
  3458. if ( typeof HTMLCanvasElement === 'undefined' ) {
  3459. return image.src;
  3460. }
  3461. let canvas;
  3462. if ( image instanceof HTMLCanvasElement ) {
  3463. canvas = image;
  3464. } else {
  3465. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  3466. _canvas.width = image.width;
  3467. _canvas.height = image.height;
  3468. const context = _canvas.getContext( '2d' );
  3469. if ( image instanceof ImageData ) {
  3470. context.putImageData( image, 0, 0 );
  3471. } else {
  3472. context.drawImage( image, 0, 0, image.width, image.height );
  3473. }
  3474. canvas = _canvas;
  3475. }
  3476. return canvas.toDataURL( type );
  3477. }
  3478. /**
  3479. * Converts the given sRGB image data to linear color space.
  3480. *
  3481. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  3482. * @return {HTMLCanvasElement|Object} The converted image.
  3483. */
  3484. static sRGBToLinear( image ) {
  3485. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  3486. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  3487. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  3488. const canvas = createElementNS( 'canvas' );
  3489. canvas.width = image.width;
  3490. canvas.height = image.height;
  3491. const context = canvas.getContext( '2d' );
  3492. context.drawImage( image, 0, 0, image.width, image.height );
  3493. const imageData = context.getImageData( 0, 0, image.width, image.height );
  3494. const data = imageData.data;
  3495. for ( let i = 0; i < data.length; i ++ ) {
  3496. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  3497. }
  3498. context.putImageData( imageData, 0, 0 );
  3499. return canvas;
  3500. } else if ( image.data ) {
  3501. const data = image.data.slice( 0 );
  3502. for ( let i = 0; i < data.length; i ++ ) {
  3503. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  3504. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  3505. } else {
  3506. // assuming float
  3507. data[ i ] = SRGBToLinear( data[ i ] );
  3508. }
  3509. }
  3510. return {
  3511. data: data,
  3512. width: image.width,
  3513. height: image.height
  3514. };
  3515. } else {
  3516. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  3517. return image;
  3518. }
  3519. }
  3520. }
  3521. let _sourceId = 0;
  3522. /**
  3523. * Represents the data source of a texture.
  3524. *
  3525. * The main purpose of this class is to decouple the data definition from the texture
  3526. * definition so the same data can be used with multiple texture instances.
  3527. */
  3528. class Source {
  3529. /**
  3530. * Constructs a new video texture.
  3531. *
  3532. * @param {any} [data=null] - The data definition of a texture.
  3533. */
  3534. constructor( data = null ) {
  3535. /**
  3536. * This flag can be used for type testing.
  3537. *
  3538. * @type {boolean}
  3539. * @readonly
  3540. * @default true
  3541. */
  3542. this.isSource = true;
  3543. /**
  3544. * The ID of the source.
  3545. *
  3546. * @name Source#id
  3547. * @type {number}
  3548. * @readonly
  3549. */
  3550. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  3551. /**
  3552. * The UUID of the source.
  3553. *
  3554. * @type {string}
  3555. * @readonly
  3556. */
  3557. this.uuid = generateUUID();
  3558. /**
  3559. * The data definition of a texture.
  3560. *
  3561. * @type {any}
  3562. */
  3563. this.data = data;
  3564. /**
  3565. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  3566. * provides more control on how texture data should be processed. When `dataReady` is set
  3567. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  3568. * the data into the GPU memory.
  3569. *
  3570. * @type {boolean}
  3571. * @default true
  3572. */
  3573. this.dataReady = true;
  3574. /**
  3575. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  3576. *
  3577. * @type {number}
  3578. * @readonly
  3579. * @default 0
  3580. */
  3581. this.version = 0;
  3582. }
  3583. /**
  3584. * When the property is set to `true`, the engine allocates the memory
  3585. * for the texture (if necessary) and triggers the actual texture upload
  3586. * to the GPU next time the source is used.
  3587. *
  3588. * @type {boolean}
  3589. * @default false
  3590. * @param {boolean} value
  3591. */
  3592. set needsUpdate( value ) {
  3593. if ( value === true ) this.version ++;
  3594. }
  3595. /**
  3596. * Serializes the source into JSON.
  3597. *
  3598. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  3599. * @return {Object} A JSON object representing the serialized source.
  3600. * @see {@link ObjectLoader#parse}
  3601. */
  3602. toJSON( meta ) {
  3603. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  3604. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  3605. return meta.images[ this.uuid ];
  3606. }
  3607. const output = {
  3608. uuid: this.uuid,
  3609. url: ''
  3610. };
  3611. const data = this.data;
  3612. if ( data !== null ) {
  3613. let url;
  3614. if ( Array.isArray( data ) ) {
  3615. // cube texture
  3616. url = [];
  3617. for ( let i = 0, l = data.length; i < l; i ++ ) {
  3618. if ( data[ i ].isDataTexture ) {
  3619. url.push( serializeImage( data[ i ].image ) );
  3620. } else {
  3621. url.push( serializeImage( data[ i ] ) );
  3622. }
  3623. }
  3624. } else {
  3625. // texture
  3626. url = serializeImage( data );
  3627. }
  3628. output.url = url;
  3629. }
  3630. if ( ! isRootObject ) {
  3631. meta.images[ this.uuid ] = output;
  3632. }
  3633. return output;
  3634. }
  3635. }
  3636. function serializeImage( image ) {
  3637. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  3638. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  3639. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  3640. // default images
  3641. return ImageUtils.getDataURL( image );
  3642. } else {
  3643. if ( image.data ) {
  3644. // images of DataTexture
  3645. return {
  3646. data: Array.from( image.data ),
  3647. width: image.width,
  3648. height: image.height,
  3649. type: image.data.constructor.name
  3650. };
  3651. } else {
  3652. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  3653. return {};
  3654. }
  3655. }
  3656. }
  3657. let _textureId = 0;
  3658. /**
  3659. * Base class for all textures.
  3660. *
  3661. * Note: After the initial use of a texture, its dimensions, format, and type
  3662. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  3663. *
  3664. * @augments EventDispatcher
  3665. */
  3666. class Texture extends EventDispatcher {
  3667. /**
  3668. * Constructs a new texture.
  3669. *
  3670. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  3671. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  3672. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  3673. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  3674. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  3675. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  3676. * @param {number} [format=RGBAFormat] - The texture format.
  3677. * @param {number} [type=UnsignedByteType] - The texture type.
  3678. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  3679. * @param {string} [colorSpace=NoColorSpace] - The color space.
  3680. */
  3681. 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 ) {
  3682. super();
  3683. /**
  3684. * This flag can be used for type testing.
  3685. *
  3686. * @type {boolean}
  3687. * @readonly
  3688. * @default true
  3689. */
  3690. this.isTexture = true;
  3691. /**
  3692. * The ID of the texture.
  3693. *
  3694. * @name Texture#id
  3695. * @type {number}
  3696. * @readonly
  3697. */
  3698. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  3699. /**
  3700. * The UUID of the material.
  3701. *
  3702. * @type {string}
  3703. * @readonly
  3704. */
  3705. this.uuid = generateUUID();
  3706. /**
  3707. * The name of the material.
  3708. *
  3709. * @type {string}
  3710. */
  3711. this.name = '';
  3712. /**
  3713. * The data definition of a texture. A reference to the data source can be
  3714. * shared across textures. This is often useful in context of spritesheets
  3715. * where multiple textures render the same data but with different texture
  3716. * transformations.
  3717. *
  3718. * @type {Source}
  3719. */
  3720. this.source = new Source( image );
  3721. /**
  3722. * An array holding user-defined mipmaps.
  3723. *
  3724. * @type {Array<Object>}
  3725. */
  3726. this.mipmaps = [];
  3727. /**
  3728. * How the texture is applied to the object. The value `UVMapping`
  3729. * is the default, where texture or uv coordinates are used to apply the map.
  3730. *
  3731. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  3732. * @default UVMapping
  3733. */
  3734. this.mapping = mapping;
  3735. /**
  3736. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  3737. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  3738. *
  3739. * @type {number}
  3740. * @default 0
  3741. */
  3742. this.channel = 0;
  3743. /**
  3744. * This defines how the texture is wrapped horizontally and corresponds to
  3745. * *U* in UV mapping.
  3746. *
  3747. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  3748. * @default ClampToEdgeWrapping
  3749. */
  3750. this.wrapS = wrapS;
  3751. /**
  3752. * This defines how the texture is wrapped horizontally and corresponds to
  3753. * *V* in UV mapping.
  3754. *
  3755. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  3756. * @default ClampToEdgeWrapping
  3757. */
  3758. this.wrapT = wrapT;
  3759. /**
  3760. * How the texture is sampled when a texel covers more than one pixel.
  3761. *
  3762. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  3763. * @default LinearFilter
  3764. */
  3765. this.magFilter = magFilter;
  3766. /**
  3767. * How the texture is sampled when a texel covers less than one pixel.
  3768. *
  3769. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  3770. * @default LinearMipmapLinearFilter
  3771. */
  3772. this.minFilter = minFilter;
  3773. /**
  3774. * The number of samples taken along the axis through the pixel that has the
  3775. * highest density of texels. By default, this value is `1`. A higher value
  3776. * gives a less blurry result than a basic mipmap, at the cost of more
  3777. * texture samples being used.
  3778. *
  3779. * @type {number}
  3780. * @default 0
  3781. */
  3782. this.anisotropy = anisotropy;
  3783. /**
  3784. * The format of the texture.
  3785. *
  3786. * @type {number}
  3787. * @default RGBAFormat
  3788. */
  3789. this.format = format;
  3790. /**
  3791. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  3792. * defines how the texture data is going to be stored on the GPU.
  3793. *
  3794. * This property allows to overwrite the default format.
  3795. *
  3796. * @type {?string}
  3797. * @default null
  3798. */
  3799. this.internalFormat = null;
  3800. /**
  3801. * The data type of the texture.
  3802. *
  3803. * @type {number}
  3804. * @default UnsignedByteType
  3805. */
  3806. this.type = type;
  3807. /**
  3808. * How much a single repetition of the texture is offset from the beginning,
  3809. * in each direction U and V. Typical range is `0.0` to `1.0`.
  3810. *
  3811. * @type {Vector2}
  3812. * @default (0,0)
  3813. */
  3814. this.offset = new Vector2( 0, 0 );
  3815. /**
  3816. * How many times the texture is repeated across the surface, in each
  3817. * direction U and V. If repeat is set greater than `1` in either direction,
  3818. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  3819. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  3820. *
  3821. * @type {Vector2}
  3822. * @default (1,1)
  3823. */
  3824. this.repeat = new Vector2( 1, 1 );
  3825. /**
  3826. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  3827. * to the center of the texture. Default is `(0, 0)`, the lower left.
  3828. *
  3829. * @type {Vector2}
  3830. * @default (0,0)
  3831. */
  3832. this.center = new Vector2( 0, 0 );
  3833. /**
  3834. * How much the texture is rotated around the center point, in radians.
  3835. * Positive values are counter-clockwise.
  3836. *
  3837. * @type {number}
  3838. * @default 0
  3839. */
  3840. this.rotation = 0;
  3841. /**
  3842. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  3843. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  3844. * {@link Texture#rotation}, and {@link Texture#center}.
  3845. *
  3846. * Set this to `false` if you are specifying the uv-transform matrix directly.
  3847. *
  3848. * @type {boolean}
  3849. * @default true
  3850. */
  3851. this.matrixAutoUpdate = true;
  3852. /**
  3853. * The uv-transformation matrix of the texture.
  3854. *
  3855. * @type {Matrix3}
  3856. */
  3857. this.matrix = new Matrix3();
  3858. /**
  3859. * Whether to generate mipmaps (if possible) for a texture.
  3860. *
  3861. * Set this to `false` if you are creating mipmaps manually.
  3862. *
  3863. * @type {boolean}
  3864. * @default true
  3865. */
  3866. this.generateMipmaps = true;
  3867. /**
  3868. * If set to `true`, the alpha channel, if present, is multiplied into the
  3869. * color channels when the texture is uploaded to the GPU.
  3870. *
  3871. * Note that this property has no effect when using `ImageBitmap`. You need to
  3872. * configure premultiply alpha on bitmap creation instead.
  3873. *
  3874. * @type {boolean}
  3875. * @default false
  3876. */
  3877. this.premultiplyAlpha = false;
  3878. /**
  3879. * If set to `true`, the texture is flipped along the vertical axis when
  3880. * uploaded to the GPU.
  3881. *
  3882. * Note that this property has no effect when using `ImageBitmap`. You need to
  3883. * configure the flip on bitmap creation instead.
  3884. *
  3885. * @type {boolean}
  3886. * @default true
  3887. */
  3888. this.flipY = true;
  3889. /**
  3890. * Specifies the alignment requirements for the start of each pixel row in memory.
  3891. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  3892. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  3893. *
  3894. * @type {number}
  3895. * @default 4
  3896. */
  3897. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  3898. /**
  3899. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  3900. *
  3901. * @type {string}
  3902. * @default NoColorSpace
  3903. */
  3904. this.colorSpace = colorSpace;
  3905. /**
  3906. * An object that can be used to store custom data about the texture. It
  3907. * should not hold references to functions as these will not be cloned.
  3908. *
  3909. * @type {Object}
  3910. */
  3911. this.userData = {};
  3912. /**
  3913. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  3914. *
  3915. * @type {number}
  3916. * @readonly
  3917. * @default 0
  3918. */
  3919. this.version = 0;
  3920. /**
  3921. * A callback function, called when the texture is updated (e.g., when
  3922. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  3923. *
  3924. * @type {?Function}
  3925. * @default null
  3926. */
  3927. this.onUpdate = null;
  3928. /**
  3929. * An optional back reference to the textures render target.
  3930. *
  3931. * @type {?(RenderTarget|WebGLRenderTarget)}
  3932. * @default null
  3933. */
  3934. this.renderTarget = null;
  3935. /**
  3936. * Indicates whether a texture belongs to a render target or not.
  3937. *
  3938. * @type {boolean}
  3939. * @readonly
  3940. * @default false
  3941. */
  3942. this.isRenderTargetTexture = false;
  3943. /**
  3944. * Indicates if a texture should be handled like a texture array.
  3945. *
  3946. * @type {boolean}
  3947. * @readonly
  3948. * @default false
  3949. */
  3950. this.isTextureArray = false;
  3951. /**
  3952. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  3953. * (only relevant for render target textures).
  3954. *
  3955. * @type {number}
  3956. * @readonly
  3957. * @default 0
  3958. */
  3959. this.pmremVersion = 0;
  3960. }
  3961. /**
  3962. * The image object holding the texture data.
  3963. *
  3964. * @type {?Object}
  3965. */
  3966. get image() {
  3967. return this.source.data;
  3968. }
  3969. set image( value = null ) {
  3970. this.source.data = value;
  3971. }
  3972. /**
  3973. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  3974. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  3975. */
  3976. updateMatrix() {
  3977. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  3978. }
  3979. /**
  3980. * Returns a new texture with copied values from this instance.
  3981. *
  3982. * @return {Texture} A clone of this instance.
  3983. */
  3984. clone() {
  3985. return new this.constructor().copy( this );
  3986. }
  3987. /**
  3988. * Copies the values of the given texture to this instance.
  3989. *
  3990. * @param {Texture} source - The texture to copy.
  3991. * @return {Texture} A reference to this instance.
  3992. */
  3993. copy( source ) {
  3994. this.name = source.name;
  3995. this.source = source.source;
  3996. this.mipmaps = source.mipmaps.slice( 0 );
  3997. this.mapping = source.mapping;
  3998. this.channel = source.channel;
  3999. this.wrapS = source.wrapS;
  4000. this.wrapT = source.wrapT;
  4001. this.magFilter = source.magFilter;
  4002. this.minFilter = source.minFilter;
  4003. this.anisotropy = source.anisotropy;
  4004. this.format = source.format;
  4005. this.internalFormat = source.internalFormat;
  4006. this.type = source.type;
  4007. this.offset.copy( source.offset );
  4008. this.repeat.copy( source.repeat );
  4009. this.center.copy( source.center );
  4010. this.rotation = source.rotation;
  4011. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4012. this.matrix.copy( source.matrix );
  4013. this.generateMipmaps = source.generateMipmaps;
  4014. this.premultiplyAlpha = source.premultiplyAlpha;
  4015. this.flipY = source.flipY;
  4016. this.unpackAlignment = source.unpackAlignment;
  4017. this.colorSpace = source.colorSpace;
  4018. this.renderTarget = source.renderTarget;
  4019. this.isRenderTargetTexture = source.isRenderTargetTexture;
  4020. this.isTextureArray = source.isTextureArray;
  4021. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4022. this.needsUpdate = true;
  4023. return this;
  4024. }
  4025. /**
  4026. * Serializes the texture into JSON.
  4027. *
  4028. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  4029. * @return {Object} A JSON object representing the serialized texture.
  4030. * @see {@link ObjectLoader#parse}
  4031. */
  4032. toJSON( meta ) {
  4033. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4034. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  4035. return meta.textures[ this.uuid ];
  4036. }
  4037. const output = {
  4038. metadata: {
  4039. version: 4.6,
  4040. type: 'Texture',
  4041. generator: 'Texture.toJSON'
  4042. },
  4043. uuid: this.uuid,
  4044. name: this.name,
  4045. image: this.source.toJSON( meta ).uuid,
  4046. mapping: this.mapping,
  4047. channel: this.channel,
  4048. repeat: [ this.repeat.x, this.repeat.y ],
  4049. offset: [ this.offset.x, this.offset.y ],
  4050. center: [ this.center.x, this.center.y ],
  4051. rotation: this.rotation,
  4052. wrap: [ this.wrapS, this.wrapT ],
  4053. format: this.format,
  4054. internalFormat: this.internalFormat,
  4055. type: this.type,
  4056. colorSpace: this.colorSpace,
  4057. minFilter: this.minFilter,
  4058. magFilter: this.magFilter,
  4059. anisotropy: this.anisotropy,
  4060. flipY: this.flipY,
  4061. generateMipmaps: this.generateMipmaps,
  4062. premultiplyAlpha: this.premultiplyAlpha,
  4063. unpackAlignment: this.unpackAlignment
  4064. };
  4065. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  4066. if ( ! isRootObject ) {
  4067. meta.textures[ this.uuid ] = output;
  4068. }
  4069. return output;
  4070. }
  4071. /**
  4072. * Frees the GPU-related resources allocated by this instance. Call this
  4073. * method whenever this instance is no longer used in your app.
  4074. *
  4075. * @fires Texture#dispose
  4076. */
  4077. dispose() {
  4078. /**
  4079. * Fires when the texture has been disposed of.
  4080. *
  4081. * @event Texture#dispose
  4082. * @type {Object}
  4083. */
  4084. this.dispatchEvent( { type: 'dispose' } );
  4085. }
  4086. /**
  4087. * Transforms the given uv vector with the textures uv transformation matrix.
  4088. *
  4089. * @param {Vector2} uv - The uv vector.
  4090. * @return {Vector2} The transformed uv vector.
  4091. */
  4092. transformUv( uv ) {
  4093. if ( this.mapping !== UVMapping ) return uv;
  4094. uv.applyMatrix3( this.matrix );
  4095. if ( uv.x < 0 || uv.x > 1 ) {
  4096. switch ( this.wrapS ) {
  4097. case RepeatWrapping:
  4098. uv.x = uv.x - Math.floor( uv.x );
  4099. break;
  4100. case ClampToEdgeWrapping:
  4101. uv.x = uv.x < 0 ? 0 : 1;
  4102. break;
  4103. case MirroredRepeatWrapping:
  4104. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  4105. uv.x = Math.ceil( uv.x ) - uv.x;
  4106. } else {
  4107. uv.x = uv.x - Math.floor( uv.x );
  4108. }
  4109. break;
  4110. }
  4111. }
  4112. if ( uv.y < 0 || uv.y > 1 ) {
  4113. switch ( this.wrapT ) {
  4114. case RepeatWrapping:
  4115. uv.y = uv.y - Math.floor( uv.y );
  4116. break;
  4117. case ClampToEdgeWrapping:
  4118. uv.y = uv.y < 0 ? 0 : 1;
  4119. break;
  4120. case MirroredRepeatWrapping:
  4121. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  4122. uv.y = Math.ceil( uv.y ) - uv.y;
  4123. } else {
  4124. uv.y = uv.y - Math.floor( uv.y );
  4125. }
  4126. break;
  4127. }
  4128. }
  4129. if ( this.flipY ) {
  4130. uv.y = 1 - uv.y;
  4131. }
  4132. return uv;
  4133. }
  4134. /**
  4135. * Setting this property to `true` indicates the engine the texture
  4136. * must be updated in the next render. This triggers a texture upload
  4137. * to the GPU and ensures correct texture parameter configuration.
  4138. *
  4139. * @type {boolean}
  4140. * @default false
  4141. * @param {boolean} value
  4142. */
  4143. set needsUpdate( value ) {
  4144. if ( value === true ) {
  4145. this.version ++;
  4146. this.source.needsUpdate = true;
  4147. }
  4148. }
  4149. /**
  4150. * Setting this property to `true` indicates the engine the PMREM
  4151. * must be regenerated.
  4152. *
  4153. * @type {boolean}
  4154. * @default false
  4155. * @param {boolean} value
  4156. */
  4157. set needsPMREMUpdate( value ) {
  4158. if ( value === true ) {
  4159. this.pmremVersion ++;
  4160. }
  4161. }
  4162. }
  4163. /**
  4164. * The default image for all textures.
  4165. *
  4166. * @static
  4167. * @type {?Image}
  4168. * @default null
  4169. */
  4170. Texture.DEFAULT_IMAGE = null;
  4171. /**
  4172. * The default mapping for all textures.
  4173. *
  4174. * @static
  4175. * @type {number}
  4176. * @default UVMapping
  4177. */
  4178. Texture.DEFAULT_MAPPING = UVMapping;
  4179. /**
  4180. * The default anisotropy value for all textures.
  4181. *
  4182. * @static
  4183. * @type {number}
  4184. * @default 1
  4185. */
  4186. Texture.DEFAULT_ANISOTROPY = 1;
  4187. /**
  4188. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  4189. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  4190. *
  4191. * - A point in 4D space.
  4192. * - A direction and length in 4D space. In three.js the length will
  4193. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  4194. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  4195. * - Any arbitrary ordered quadruplet of numbers.
  4196. *
  4197. * There are other things a 4D vector can be used to represent, however these
  4198. * are the most common uses in *three.js*.
  4199. *
  4200. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  4201. * the corresponding order.
  4202. * ```js
  4203. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  4204. *
  4205. * //no arguments; will be initialised to (0, 0, 0, 1)
  4206. * const b = new THREE.Vector4( );
  4207. *
  4208. * const d = a.dot( b );
  4209. * ```
  4210. */
  4211. class Vector4 {
  4212. /**
  4213. * Constructs a new 4D vector.
  4214. *
  4215. * @param {number} [x=0] - The x value of this vector.
  4216. * @param {number} [y=0] - The y value of this vector.
  4217. * @param {number} [z=0] - The z value of this vector.
  4218. * @param {number} [w=1] - The w value of this vector.
  4219. */
  4220. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  4221. /**
  4222. * This flag can be used for type testing.
  4223. *
  4224. * @type {boolean}
  4225. * @readonly
  4226. * @default true
  4227. */
  4228. Vector4.prototype.isVector4 = true;
  4229. /**
  4230. * The x value of this vector.
  4231. *
  4232. * @type {number}
  4233. */
  4234. this.x = x;
  4235. /**
  4236. * The y value of this vector.
  4237. *
  4238. * @type {number}
  4239. */
  4240. this.y = y;
  4241. /**
  4242. * The z value of this vector.
  4243. *
  4244. * @type {number}
  4245. */
  4246. this.z = z;
  4247. /**
  4248. * The w value of this vector.
  4249. *
  4250. * @type {number}
  4251. */
  4252. this.w = w;
  4253. }
  4254. /**
  4255. * Alias for {@link Vector4#z}.
  4256. *
  4257. * @type {number}
  4258. */
  4259. get width() {
  4260. return this.z;
  4261. }
  4262. set width( value ) {
  4263. this.z = value;
  4264. }
  4265. /**
  4266. * Alias for {@link Vector4#w}.
  4267. *
  4268. * @type {number}
  4269. */
  4270. get height() {
  4271. return this.w;
  4272. }
  4273. set height( value ) {
  4274. this.w = value;
  4275. }
  4276. /**
  4277. * Sets the vector components.
  4278. *
  4279. * @param {number} x - The value of the x component.
  4280. * @param {number} y - The value of the y component.
  4281. * @param {number} z - The value of the z component.
  4282. * @param {number} w - The value of the w component.
  4283. * @return {Vector4} A reference to this vector.
  4284. */
  4285. set( x, y, z, w ) {
  4286. this.x = x;
  4287. this.y = y;
  4288. this.z = z;
  4289. this.w = w;
  4290. return this;
  4291. }
  4292. /**
  4293. * Sets the vector components to the same value.
  4294. *
  4295. * @param {number} scalar - The value to set for all vector components.
  4296. * @return {Vector4} A reference to this vector.
  4297. */
  4298. setScalar( scalar ) {
  4299. this.x = scalar;
  4300. this.y = scalar;
  4301. this.z = scalar;
  4302. this.w = scalar;
  4303. return this;
  4304. }
  4305. /**
  4306. * Sets the vector's x component to the given value
  4307. *
  4308. * @param {number} x - The value to set.
  4309. * @return {Vector4} A reference to this vector.
  4310. */
  4311. setX( x ) {
  4312. this.x = x;
  4313. return this;
  4314. }
  4315. /**
  4316. * Sets the vector's y component to the given value
  4317. *
  4318. * @param {number} y - The value to set.
  4319. * @return {Vector4} A reference to this vector.
  4320. */
  4321. setY( y ) {
  4322. this.y = y;
  4323. return this;
  4324. }
  4325. /**
  4326. * Sets the vector's z component to the given value
  4327. *
  4328. * @param {number} z - The value to set.
  4329. * @return {Vector4} A reference to this vector.
  4330. */
  4331. setZ( z ) {
  4332. this.z = z;
  4333. return this;
  4334. }
  4335. /**
  4336. * Sets the vector's w component to the given value
  4337. *
  4338. * @param {number} w - The value to set.
  4339. * @return {Vector4} A reference to this vector.
  4340. */
  4341. setW( w ) {
  4342. this.w = w;
  4343. return this;
  4344. }
  4345. /**
  4346. * Allows to set a vector component with an index.
  4347. *
  4348. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  4349. * `2` equals to z, `3` equals to w.
  4350. * @param {number} value - The value to set.
  4351. * @return {Vector4} A reference to this vector.
  4352. */
  4353. setComponent( index, value ) {
  4354. switch ( index ) {
  4355. case 0: this.x = value; break;
  4356. case 1: this.y = value; break;
  4357. case 2: this.z = value; break;
  4358. case 3: this.w = value; break;
  4359. default: throw new Error( 'index is out of range: ' + index );
  4360. }
  4361. return this;
  4362. }
  4363. /**
  4364. * Returns the value of the vector component which matches the given index.
  4365. *
  4366. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  4367. * `2` equals to z, `3` equals to w.
  4368. * @return {number} A vector component value.
  4369. */
  4370. getComponent( index ) {
  4371. switch ( index ) {
  4372. case 0: return this.x;
  4373. case 1: return this.y;
  4374. case 2: return this.z;
  4375. case 3: return this.w;
  4376. default: throw new Error( 'index is out of range: ' + index );
  4377. }
  4378. }
  4379. /**
  4380. * Returns a new vector with copied values from this instance.
  4381. *
  4382. * @return {Vector4} A clone of this instance.
  4383. */
  4384. clone() {
  4385. return new this.constructor( this.x, this.y, this.z, this.w );
  4386. }
  4387. /**
  4388. * Copies the values of the given vector to this instance.
  4389. *
  4390. * @param {Vector3|Vector4} v - The vector to copy.
  4391. * @return {Vector4} A reference to this vector.
  4392. */
  4393. copy( v ) {
  4394. this.x = v.x;
  4395. this.y = v.y;
  4396. this.z = v.z;
  4397. this.w = ( v.w !== undefined ) ? v.w : 1;
  4398. return this;
  4399. }
  4400. /**
  4401. * Adds the given vector to this instance.
  4402. *
  4403. * @param {Vector4} v - The vector to add.
  4404. * @return {Vector4} A reference to this vector.
  4405. */
  4406. add( v ) {
  4407. this.x += v.x;
  4408. this.y += v.y;
  4409. this.z += v.z;
  4410. this.w += v.w;
  4411. return this;
  4412. }
  4413. /**
  4414. * Adds the given scalar value to all components of this instance.
  4415. *
  4416. * @param {number} s - The scalar to add.
  4417. * @return {Vector4} A reference to this vector.
  4418. */
  4419. addScalar( s ) {
  4420. this.x += s;
  4421. this.y += s;
  4422. this.z += s;
  4423. this.w += s;
  4424. return this;
  4425. }
  4426. /**
  4427. * Adds the given vectors and stores the result in this instance.
  4428. *
  4429. * @param {Vector4} a - The first vector.
  4430. * @param {Vector4} b - The second vector.
  4431. * @return {Vector4} A reference to this vector.
  4432. */
  4433. addVectors( a, b ) {
  4434. this.x = a.x + b.x;
  4435. this.y = a.y + b.y;
  4436. this.z = a.z + b.z;
  4437. this.w = a.w + b.w;
  4438. return this;
  4439. }
  4440. /**
  4441. * Adds the given vector scaled by the given factor to this instance.
  4442. *
  4443. * @param {Vector4} v - The vector.
  4444. * @param {number} s - The factor that scales `v`.
  4445. * @return {Vector4} A reference to this vector.
  4446. */
  4447. addScaledVector( v, s ) {
  4448. this.x += v.x * s;
  4449. this.y += v.y * s;
  4450. this.z += v.z * s;
  4451. this.w += v.w * s;
  4452. return this;
  4453. }
  4454. /**
  4455. * Subtracts the given vector from this instance.
  4456. *
  4457. * @param {Vector4} v - The vector to subtract.
  4458. * @return {Vector4} A reference to this vector.
  4459. */
  4460. sub( v ) {
  4461. this.x -= v.x;
  4462. this.y -= v.y;
  4463. this.z -= v.z;
  4464. this.w -= v.w;
  4465. return this;
  4466. }
  4467. /**
  4468. * Subtracts the given scalar value from all components of this instance.
  4469. *
  4470. * @param {number} s - The scalar to subtract.
  4471. * @return {Vector4} A reference to this vector.
  4472. */
  4473. subScalar( s ) {
  4474. this.x -= s;
  4475. this.y -= s;
  4476. this.z -= s;
  4477. this.w -= s;
  4478. return this;
  4479. }
  4480. /**
  4481. * Subtracts the given vectors and stores the result in this instance.
  4482. *
  4483. * @param {Vector4} a - The first vector.
  4484. * @param {Vector4} b - The second vector.
  4485. * @return {Vector4} A reference to this vector.
  4486. */
  4487. subVectors( a, b ) {
  4488. this.x = a.x - b.x;
  4489. this.y = a.y - b.y;
  4490. this.z = a.z - b.z;
  4491. this.w = a.w - b.w;
  4492. return this;
  4493. }
  4494. /**
  4495. * Multiplies the given vector with this instance.
  4496. *
  4497. * @param {Vector4} v - The vector to multiply.
  4498. * @return {Vector4} A reference to this vector.
  4499. */
  4500. multiply( v ) {
  4501. this.x *= v.x;
  4502. this.y *= v.y;
  4503. this.z *= v.z;
  4504. this.w *= v.w;
  4505. return this;
  4506. }
  4507. /**
  4508. * Multiplies the given scalar value with all components of this instance.
  4509. *
  4510. * @param {number} scalar - The scalar to multiply.
  4511. * @return {Vector4} A reference to this vector.
  4512. */
  4513. multiplyScalar( scalar ) {
  4514. this.x *= scalar;
  4515. this.y *= scalar;
  4516. this.z *= scalar;
  4517. this.w *= scalar;
  4518. return this;
  4519. }
  4520. /**
  4521. * Multiplies this vector with the given 4x4 matrix.
  4522. *
  4523. * @param {Matrix4} m - The 4x4 matrix.
  4524. * @return {Vector4} A reference to this vector.
  4525. */
  4526. applyMatrix4( m ) {
  4527. const x = this.x, y = this.y, z = this.z, w = this.w;
  4528. const e = m.elements;
  4529. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  4530. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  4531. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  4532. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  4533. return this;
  4534. }
  4535. /**
  4536. * Divides this instance by the given vector.
  4537. *
  4538. * @param {Vector4} v - The vector to divide.
  4539. * @return {Vector4} A reference to this vector.
  4540. */
  4541. divide( v ) {
  4542. this.x /= v.x;
  4543. this.y /= v.y;
  4544. this.z /= v.z;
  4545. this.w /= v.w;
  4546. return this;
  4547. }
  4548. /**
  4549. * Divides this vector by the given scalar.
  4550. *
  4551. * @param {number} scalar - The scalar to divide.
  4552. * @return {Vector4} A reference to this vector.
  4553. */
  4554. divideScalar( scalar ) {
  4555. return this.multiplyScalar( 1 / scalar );
  4556. }
  4557. /**
  4558. * Sets the x, y and z components of this
  4559. * vector to the quaternion's axis and w to the angle.
  4560. *
  4561. * @param {Quaternion} q - The Quaternion to set.
  4562. * @return {Vector4} A reference to this vector.
  4563. */
  4564. setAxisAngleFromQuaternion( q ) {
  4565. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  4566. // q is assumed to be normalized
  4567. this.w = 2 * Math.acos( q.w );
  4568. const s = Math.sqrt( 1 - q.w * q.w );
  4569. if ( s < 0.0001 ) {
  4570. this.x = 1;
  4571. this.y = 0;
  4572. this.z = 0;
  4573. } else {
  4574. this.x = q.x / s;
  4575. this.y = q.y / s;
  4576. this.z = q.z / s;
  4577. }
  4578. return this;
  4579. }
  4580. /**
  4581. * Sets the x, y and z components of this
  4582. * vector to the axis of rotation and w to the angle.
  4583. *
  4584. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  4585. * @return {Vector4} A reference to this vector.
  4586. */
  4587. setAxisAngleFromRotationMatrix( m ) {
  4588. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  4589. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4590. let angle, x, y, z; // variables for result
  4591. const epsilon = 0.01, // margin to allow for rounding errors
  4592. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  4593. te = m.elements,
  4594. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  4595. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  4596. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4597. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  4598. ( Math.abs( m13 - m31 ) < epsilon ) &&
  4599. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  4600. // singularity found
  4601. // first check for identity matrix which must have +1 for all terms
  4602. // in leading diagonal and zero in other terms
  4603. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  4604. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  4605. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  4606. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  4607. // this singularity is identity matrix so angle = 0
  4608. this.set( 1, 0, 0, 0 );
  4609. return this; // zero angle, arbitrary axis
  4610. }
  4611. // otherwise this singularity is angle = 180
  4612. angle = Math.PI;
  4613. const xx = ( m11 + 1 ) / 2;
  4614. const yy = ( m22 + 1 ) / 2;
  4615. const zz = ( m33 + 1 ) / 2;
  4616. const xy = ( m12 + m21 ) / 4;
  4617. const xz = ( m13 + m31 ) / 4;
  4618. const yz = ( m23 + m32 ) / 4;
  4619. if ( ( xx > yy ) && ( xx > zz ) ) {
  4620. // m11 is the largest diagonal term
  4621. if ( xx < epsilon ) {
  4622. x = 0;
  4623. y = 0.707106781;
  4624. z = 0.707106781;
  4625. } else {
  4626. x = Math.sqrt( xx );
  4627. y = xy / x;
  4628. z = xz / x;
  4629. }
  4630. } else if ( yy > zz ) {
  4631. // m22 is the largest diagonal term
  4632. if ( yy < epsilon ) {
  4633. x = 0.707106781;
  4634. y = 0;
  4635. z = 0.707106781;
  4636. } else {
  4637. y = Math.sqrt( yy );
  4638. x = xy / y;
  4639. z = yz / y;
  4640. }
  4641. } else {
  4642. // m33 is the largest diagonal term so base result on this
  4643. if ( zz < epsilon ) {
  4644. x = 0.707106781;
  4645. y = 0.707106781;
  4646. z = 0;
  4647. } else {
  4648. z = Math.sqrt( zz );
  4649. x = xz / z;
  4650. y = yz / z;
  4651. }
  4652. }
  4653. this.set( x, y, z, angle );
  4654. return this; // return 180 deg rotation
  4655. }
  4656. // as we have reached here there are no singularities so we can handle normally
  4657. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  4658. ( m13 - m31 ) * ( m13 - m31 ) +
  4659. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  4660. if ( Math.abs( s ) < 0.001 ) s = 1;
  4661. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  4662. // caught by singularity test above, but I've left it in just in case
  4663. this.x = ( m32 - m23 ) / s;
  4664. this.y = ( m13 - m31 ) / s;
  4665. this.z = ( m21 - m12 ) / s;
  4666. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  4667. return this;
  4668. }
  4669. /**
  4670. * Sets the vector components to the position elements of the
  4671. * given transformation matrix.
  4672. *
  4673. * @param {Matrix4} m - The 4x4 matrix.
  4674. * @return {Vector4} A reference to this vector.
  4675. */
  4676. setFromMatrixPosition( m ) {
  4677. const e = m.elements;
  4678. this.x = e[ 12 ];
  4679. this.y = e[ 13 ];
  4680. this.z = e[ 14 ];
  4681. this.w = e[ 15 ];
  4682. return this;
  4683. }
  4684. /**
  4685. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  4686. * value, replace that value with the corresponding min value.
  4687. *
  4688. * @param {Vector4} v - The vector.
  4689. * @return {Vector4} A reference to this vector.
  4690. */
  4691. min( v ) {
  4692. this.x = Math.min( this.x, v.x );
  4693. this.y = Math.min( this.y, v.y );
  4694. this.z = Math.min( this.z, v.z );
  4695. this.w = Math.min( this.w, v.w );
  4696. return this;
  4697. }
  4698. /**
  4699. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  4700. * value, replace that value with the corresponding max value.
  4701. *
  4702. * @param {Vector4} v - The vector.
  4703. * @return {Vector4} A reference to this vector.
  4704. */
  4705. max( v ) {
  4706. this.x = Math.max( this.x, v.x );
  4707. this.y = Math.max( this.y, v.y );
  4708. this.z = Math.max( this.z, v.z );
  4709. this.w = Math.max( this.w, v.w );
  4710. return this;
  4711. }
  4712. /**
  4713. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  4714. * value, it is replaced by the corresponding value.
  4715. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  4716. * it is replaced by the corresponding value.
  4717. *
  4718. * @param {Vector4} min - The minimum x, y and z values.
  4719. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  4720. * @return {Vector4} A reference to this vector.
  4721. */
  4722. clamp( min, max ) {
  4723. // assumes min < max, componentwise
  4724. this.x = clamp( this.x, min.x, max.x );
  4725. this.y = clamp( this.y, min.y, max.y );
  4726. this.z = clamp( this.z, min.z, max.z );
  4727. this.w = clamp( this.w, min.w, max.w );
  4728. return this;
  4729. }
  4730. /**
  4731. * If this vector's x, y, z or w values are greater than the max value, they are
  4732. * replaced by the max value.
  4733. * If this vector's x, y, z or w values are less than the min value, they are
  4734. * replaced by the min value.
  4735. *
  4736. * @param {number} minVal - The minimum value the components will be clamped to.
  4737. * @param {number} maxVal - The maximum value the components will be clamped to.
  4738. * @return {Vector4} A reference to this vector.
  4739. */
  4740. clampScalar( minVal, maxVal ) {
  4741. this.x = clamp( this.x, minVal, maxVal );
  4742. this.y = clamp( this.y, minVal, maxVal );
  4743. this.z = clamp( this.z, minVal, maxVal );
  4744. this.w = clamp( this.w, minVal, maxVal );
  4745. return this;
  4746. }
  4747. /**
  4748. * If this vector's length is greater than the max value, it is replaced by
  4749. * the max value.
  4750. * If this vector's length is less than the min value, it is replaced by the
  4751. * min value.
  4752. *
  4753. * @param {number} min - The minimum value the vector length will be clamped to.
  4754. * @param {number} max - The maximum value the vector length will be clamped to.
  4755. * @return {Vector4} A reference to this vector.
  4756. */
  4757. clampLength( min, max ) {
  4758. const length = this.length();
  4759. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  4760. }
  4761. /**
  4762. * The components of this vector are rounded down to the nearest integer value.
  4763. *
  4764. * @return {Vector4} A reference to this vector.
  4765. */
  4766. floor() {
  4767. this.x = Math.floor( this.x );
  4768. this.y = Math.floor( this.y );
  4769. this.z = Math.floor( this.z );
  4770. this.w = Math.floor( this.w );
  4771. return this;
  4772. }
  4773. /**
  4774. * The components of this vector are rounded up to the nearest integer value.
  4775. *
  4776. * @return {Vector4} A reference to this vector.
  4777. */
  4778. ceil() {
  4779. this.x = Math.ceil( this.x );
  4780. this.y = Math.ceil( this.y );
  4781. this.z = Math.ceil( this.z );
  4782. this.w = Math.ceil( this.w );
  4783. return this;
  4784. }
  4785. /**
  4786. * The components of this vector are rounded to the nearest integer value
  4787. *
  4788. * @return {Vector4} A reference to this vector.
  4789. */
  4790. round() {
  4791. this.x = Math.round( this.x );
  4792. this.y = Math.round( this.y );
  4793. this.z = Math.round( this.z );
  4794. this.w = Math.round( this.w );
  4795. return this;
  4796. }
  4797. /**
  4798. * The components of this vector are rounded towards zero (up if negative,
  4799. * down if positive) to an integer value.
  4800. *
  4801. * @return {Vector4} A reference to this vector.
  4802. */
  4803. roundToZero() {
  4804. this.x = Math.trunc( this.x );
  4805. this.y = Math.trunc( this.y );
  4806. this.z = Math.trunc( this.z );
  4807. this.w = Math.trunc( this.w );
  4808. return this;
  4809. }
  4810. /**
  4811. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  4812. *
  4813. * @return {Vector4} A reference to this vector.
  4814. */
  4815. negate() {
  4816. this.x = - this.x;
  4817. this.y = - this.y;
  4818. this.z = - this.z;
  4819. this.w = - this.w;
  4820. return this;
  4821. }
  4822. /**
  4823. * Calculates the dot product of the given vector with this instance.
  4824. *
  4825. * @param {Vector4} v - The vector to compute the dot product with.
  4826. * @return {number} The result of the dot product.
  4827. */
  4828. dot( v ) {
  4829. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  4830. }
  4831. /**
  4832. * Computes the square of the Euclidean length (straight-line length) from
  4833. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  4834. * compare the length squared instead as it is slightly more efficient to calculate.
  4835. *
  4836. * @return {number} The square length of this vector.
  4837. */
  4838. lengthSq() {
  4839. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  4840. }
  4841. /**
  4842. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  4843. *
  4844. * @return {number} The length of this vector.
  4845. */
  4846. length() {
  4847. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  4848. }
  4849. /**
  4850. * Computes the Manhattan length of this vector.
  4851. *
  4852. * @return {number} The length of this vector.
  4853. */
  4854. manhattanLength() {
  4855. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  4856. }
  4857. /**
  4858. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4859. * with the same direction as this one, but with a vector length of `1`.
  4860. *
  4861. * @return {Vector4} A reference to this vector.
  4862. */
  4863. normalize() {
  4864. return this.divideScalar( this.length() || 1 );
  4865. }
  4866. /**
  4867. * Sets this vector to a vector with the same direction as this one, but
  4868. * with the specified length.
  4869. *
  4870. * @param {number} length - The new length of this vector.
  4871. * @return {Vector4} A reference to this vector.
  4872. */
  4873. setLength( length ) {
  4874. return this.normalize().multiplyScalar( length );
  4875. }
  4876. /**
  4877. * Linearly interpolates between the given vector and this instance, where
  4878. * alpha is the percent distance along the line - alpha = 0 will be this
  4879. * vector, and alpha = 1 will be the given one.
  4880. *
  4881. * @param {Vector4} v - The vector to interpolate towards.
  4882. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4883. * @return {Vector4} A reference to this vector.
  4884. */
  4885. lerp( v, alpha ) {
  4886. this.x += ( v.x - this.x ) * alpha;
  4887. this.y += ( v.y - this.y ) * alpha;
  4888. this.z += ( v.z - this.z ) * alpha;
  4889. this.w += ( v.w - this.w ) * alpha;
  4890. return this;
  4891. }
  4892. /**
  4893. * Linearly interpolates between the given vectors, where alpha is the percent
  4894. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4895. * be the second one. The result is stored in this instance.
  4896. *
  4897. * @param {Vector4} v1 - The first vector.
  4898. * @param {Vector4} v2 - The second vector.
  4899. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4900. * @return {Vector4} A reference to this vector.
  4901. */
  4902. lerpVectors( v1, v2, alpha ) {
  4903. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4904. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4905. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4906. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  4907. return this;
  4908. }
  4909. /**
  4910. * Returns `true` if this vector is equal with the given one.
  4911. *
  4912. * @param {Vector4} v - The vector to test for equality.
  4913. * @return {boolean} Whether this vector is equal with the given one.
  4914. */
  4915. equals( v ) {
  4916. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  4917. }
  4918. /**
  4919. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  4920. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  4921. *
  4922. * @param {Array<number>} array - An array holding the vector component values.
  4923. * @param {number} [offset=0] - The offset into the array.
  4924. * @return {Vector4} A reference to this vector.
  4925. */
  4926. fromArray( array, offset = 0 ) {
  4927. this.x = array[ offset ];
  4928. this.y = array[ offset + 1 ];
  4929. this.z = array[ offset + 2 ];
  4930. this.w = array[ offset + 3 ];
  4931. return this;
  4932. }
  4933. /**
  4934. * Writes the components of this vector to the given array. If no array is provided,
  4935. * the method returns a new instance.
  4936. *
  4937. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  4938. * @param {number} [offset=0] - Index of the first element in the array.
  4939. * @return {Array<number>} The vector components.
  4940. */
  4941. toArray( array = [], offset = 0 ) {
  4942. array[ offset ] = this.x;
  4943. array[ offset + 1 ] = this.y;
  4944. array[ offset + 2 ] = this.z;
  4945. array[ offset + 3 ] = this.w;
  4946. return array;
  4947. }
  4948. /**
  4949. * Sets the components of this vector from the given buffer attribute.
  4950. *
  4951. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  4952. * @param {number} index - The index into the attribute.
  4953. * @return {Vector4} A reference to this vector.
  4954. */
  4955. fromBufferAttribute( attribute, index ) {
  4956. this.x = attribute.getX( index );
  4957. this.y = attribute.getY( index );
  4958. this.z = attribute.getZ( index );
  4959. this.w = attribute.getW( index );
  4960. return this;
  4961. }
  4962. /**
  4963. * Sets each component of this vector to a pseudo-random value between `0` and
  4964. * `1`, excluding `1`.
  4965. *
  4966. * @return {Vector4} A reference to this vector.
  4967. */
  4968. random() {
  4969. this.x = Math.random();
  4970. this.y = Math.random();
  4971. this.z = Math.random();
  4972. this.w = Math.random();
  4973. return this;
  4974. }
  4975. *[ Symbol.iterator ]() {
  4976. yield this.x;
  4977. yield this.y;
  4978. yield this.z;
  4979. yield this.w;
  4980. }
  4981. }
  4982. /**
  4983. * A render target is a buffer where the video card draws pixels for a scene
  4984. * that is being rendered in the background. It is used in different effects,
  4985. * such as applying postprocessing to a rendered image before displaying it
  4986. * on the screen.
  4987. *
  4988. * @augments EventDispatcher
  4989. */
  4990. class RenderTarget extends EventDispatcher {
  4991. /**
  4992. * Render target options.
  4993. *
  4994. * @typedef {Object} RenderTarget~Options
  4995. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  4996. * @property {number} [magFilter=LinearFilter] - The mag filter.
  4997. * @property {number} [minFilter=LinearFilter] - The min filter.
  4998. * @property {number} [format=RGBAFormat] - The texture format.
  4999. * @property {number} [type=UnsignedByteType] - The texture type.
  5000. * @property {?string} [internalFormat=null] - The texture's internal format.
  5001. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  5002. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  5003. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  5004. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  5005. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  5006. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  5007. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  5008. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  5009. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  5010. * @property {number} [samples=0] - The MSAA samples count.
  5011. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  5012. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering.
  5013. */
  5014. /**
  5015. * Constructs a new render target.
  5016. *
  5017. * @param {number} [width=1] - The width of the render target.
  5018. * @param {number} [height=1] - The height of the render target.
  5019. * @param {RenderTarget~Options} [options] - The configuration object.
  5020. */
  5021. constructor( width = 1, height = 1, options = {} ) {
  5022. super();
  5023. /**
  5024. * This flag can be used for type testing.
  5025. *
  5026. * @type {boolean}
  5027. * @readonly
  5028. * @default true
  5029. */
  5030. this.isRenderTarget = true;
  5031. /**
  5032. * The width of the render target.
  5033. *
  5034. * @type {number}
  5035. * @default 1
  5036. */
  5037. this.width = width;
  5038. /**
  5039. * The height of the render target.
  5040. *
  5041. * @type {number}
  5042. * @default 1
  5043. */
  5044. this.height = height;
  5045. /**
  5046. * The depth of the render target.
  5047. *
  5048. * @type {number}
  5049. * @default 1
  5050. */
  5051. this.depth = options.depth ? options.depth : 1;
  5052. /**
  5053. * A rectangular area inside the render target's viewport. Fragments that are
  5054. * outside the area will be discarded.
  5055. *
  5056. * @type {Vector4}
  5057. * @default (0,0,width,height)
  5058. */
  5059. this.scissor = new Vector4( 0, 0, width, height );
  5060. /**
  5061. * Indicates whether the scissor test should be enabled when rendering into
  5062. * this render target or not.
  5063. *
  5064. * @type {boolean}
  5065. * @default false
  5066. */
  5067. this.scissorTest = false;
  5068. /**
  5069. * A rectangular area representing the render target's viewport.
  5070. *
  5071. * @type {Vector4}
  5072. * @default (0,0,width,height)
  5073. */
  5074. this.viewport = new Vector4( 0, 0, width, height );
  5075. const image = { width: width, height: height, depth: this.depth };
  5076. options = Object.assign( {
  5077. generateMipmaps: false,
  5078. internalFormat: null,
  5079. minFilter: LinearFilter,
  5080. depthBuffer: true,
  5081. stencilBuffer: false,
  5082. resolveDepthBuffer: true,
  5083. resolveStencilBuffer: true,
  5084. depthTexture: null,
  5085. samples: 0,
  5086. count: 1,
  5087. multiview: false
  5088. }, options );
  5089. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  5090. texture.flipY = false;
  5091. texture.generateMipmaps = options.generateMipmaps;
  5092. texture.internalFormat = options.internalFormat;
  5093. /**
  5094. * An array of textures. Each color attachment is represented as a separate texture.
  5095. * Has at least a single entry for the default color attachment.
  5096. *
  5097. * @type {Array<Texture>}
  5098. */
  5099. this.textures = [];
  5100. const count = options.count;
  5101. for ( let i = 0; i < count; i ++ ) {
  5102. this.textures[ i ] = texture.clone();
  5103. this.textures[ i ].isRenderTargetTexture = true;
  5104. this.textures[ i ].renderTarget = this;
  5105. }
  5106. /**
  5107. * Whether to allocate a depth buffer or not.
  5108. *
  5109. * @type {boolean}
  5110. * @default true
  5111. */
  5112. this.depthBuffer = options.depthBuffer;
  5113. /**
  5114. * Whether to allocate a stencil buffer or not.
  5115. *
  5116. * @type {boolean}
  5117. * @default false
  5118. */
  5119. this.stencilBuffer = options.stencilBuffer;
  5120. /**
  5121. * Whether to resolve the depth buffer or not.
  5122. *
  5123. * @type {boolean}
  5124. * @default true
  5125. */
  5126. this.resolveDepthBuffer = options.resolveDepthBuffer;
  5127. /**
  5128. * Whether to resolve the stencil buffer or not.
  5129. *
  5130. * @type {boolean}
  5131. * @default true
  5132. */
  5133. this.resolveStencilBuffer = options.resolveStencilBuffer;
  5134. this._depthTexture = null;
  5135. this.depthTexture = options.depthTexture;
  5136. /**
  5137. * The number of MSAA samples.
  5138. *
  5139. * A value of `0` disables MSAA.
  5140. *
  5141. * @type {number}
  5142. * @default 0
  5143. */
  5144. this.samples = options.samples;
  5145. /**
  5146. * Whether to this target is used in multiview rendering.
  5147. *
  5148. * @type {boolean}
  5149. * @default false
  5150. */
  5151. this.multiview = options.multiview;
  5152. }
  5153. /**
  5154. * The texture representing the default color attachment.
  5155. *
  5156. * @type {Texture}
  5157. */
  5158. get texture() {
  5159. return this.textures[ 0 ];
  5160. }
  5161. set texture( value ) {
  5162. this.textures[ 0 ] = value;
  5163. }
  5164. set depthTexture( current ) {
  5165. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  5166. if ( current !== null ) current.renderTarget = this;
  5167. this._depthTexture = current;
  5168. }
  5169. /**
  5170. * Instead of saving the depth in a renderbuffer, a texture
  5171. * can be used instead which is useful for further processing
  5172. * e.g. in context of post-processing.
  5173. *
  5174. * @type {?DepthTexture}
  5175. * @default null
  5176. */
  5177. get depthTexture() {
  5178. return this._depthTexture;
  5179. }
  5180. /**
  5181. * Sets the size of this render target.
  5182. *
  5183. * @param {number} width - The width.
  5184. * @param {number} height - The height.
  5185. * @param {number} [depth=1] - The depth.
  5186. */
  5187. setSize( width, height, depth = 1 ) {
  5188. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  5189. this.width = width;
  5190. this.height = height;
  5191. this.depth = depth;
  5192. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  5193. this.textures[ i ].image.width = width;
  5194. this.textures[ i ].image.height = height;
  5195. this.textures[ i ].image.depth = depth;
  5196. }
  5197. this.dispose();
  5198. }
  5199. this.viewport.set( 0, 0, width, height );
  5200. this.scissor.set( 0, 0, width, height );
  5201. }
  5202. /**
  5203. * Returns a new render target with copied values from this instance.
  5204. *
  5205. * @return {RenderTarget} A clone of this instance.
  5206. */
  5207. clone() {
  5208. return new this.constructor().copy( this );
  5209. }
  5210. /**
  5211. * Copies the settings of the given render target. This is a structural copy so
  5212. * no resources are shared between render targets after the copy. That includes
  5213. * all MRT textures and the depth texture.
  5214. *
  5215. * @param {RenderTarget} source - The render target to copy.
  5216. * @return {RenderTarget} A reference to this instance.
  5217. */
  5218. copy( source ) {
  5219. this.width = source.width;
  5220. this.height = source.height;
  5221. this.depth = source.depth;
  5222. this.scissor.copy( source.scissor );
  5223. this.scissorTest = source.scissorTest;
  5224. this.viewport.copy( source.viewport );
  5225. this.textures.length = 0;
  5226. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  5227. this.textures[ i ] = source.textures[ i ].clone();
  5228. this.textures[ i ].isRenderTargetTexture = true;
  5229. this.textures[ i ].renderTarget = this;
  5230. // ensure image object is not shared, see #20328
  5231. const image = Object.assign( {}, source.textures[ i ].image );
  5232. this.textures[ i ].source = new Source( image );
  5233. }
  5234. this.depthBuffer = source.depthBuffer;
  5235. this.stencilBuffer = source.stencilBuffer;
  5236. this.resolveDepthBuffer = source.resolveDepthBuffer;
  5237. this.resolveStencilBuffer = source.resolveStencilBuffer;
  5238. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  5239. this.samples = source.samples;
  5240. return this;
  5241. }
  5242. /**
  5243. * Frees the GPU-related resources allocated by this instance. Call this
  5244. * method whenever this instance is no longer used in your app.
  5245. *
  5246. * @fires RenderTarget#dispose
  5247. */
  5248. dispose() {
  5249. this.dispatchEvent( { type: 'dispose' } );
  5250. }
  5251. }
  5252. /**
  5253. * A render target used in context of {@link WebGLRenderer}.
  5254. *
  5255. * @augments RenderTarget
  5256. */
  5257. class WebGLRenderTarget extends RenderTarget {
  5258. /**
  5259. * Constructs a new 3D render target.
  5260. *
  5261. * @param {number} [width=1] - The width of the render target.
  5262. * @param {number} [height=1] - The height of the render target.
  5263. * @param {RenderTarget~Options} [options] - The configuration object.
  5264. */
  5265. constructor( width = 1, height = 1, options = {} ) {
  5266. super( width, height, options );
  5267. /**
  5268. * This flag can be used for type testing.
  5269. *
  5270. * @type {boolean}
  5271. * @readonly
  5272. * @default true
  5273. */
  5274. this.isWebGLRenderTarget = true;
  5275. }
  5276. }
  5277. /**
  5278. * Creates an array of textures directly from raw buffer data.
  5279. *
  5280. * @augments Texture
  5281. */
  5282. class DataArrayTexture extends Texture {
  5283. /**
  5284. * Constructs a new data array texture.
  5285. *
  5286. * @param {?TypedArray} [data=null] - The buffer data.
  5287. * @param {number} [width=1] - The width of the texture.
  5288. * @param {number} [height=1] - The height of the texture.
  5289. * @param {number} [depth=1] - The depth of the texture.
  5290. */
  5291. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  5292. super( null );
  5293. /**
  5294. * This flag can be used for type testing.
  5295. *
  5296. * @type {boolean}
  5297. * @readonly
  5298. * @default true
  5299. */
  5300. this.isDataArrayTexture = true;
  5301. /**
  5302. * The image definition of a data texture.
  5303. *
  5304. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  5305. */
  5306. this.image = { data, width, height, depth };
  5307. /**
  5308. * How the texture is sampled when a texel covers more than one pixel.
  5309. *
  5310. * Overwritten and set to `NearestFilter` by default.
  5311. *
  5312. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5313. * @default NearestFilter
  5314. */
  5315. this.magFilter = NearestFilter;
  5316. /**
  5317. * How the texture is sampled when a texel covers less than one pixel.
  5318. *
  5319. * Overwritten and set to `NearestFilter` by default.
  5320. *
  5321. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5322. * @default NearestFilter
  5323. */
  5324. this.minFilter = NearestFilter;
  5325. /**
  5326. * This defines how the texture is wrapped in the depth and corresponds to
  5327. * *W* in UVW mapping.
  5328. *
  5329. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5330. * @default ClampToEdgeWrapping
  5331. */
  5332. this.wrapR = ClampToEdgeWrapping;
  5333. /**
  5334. * Whether to generate mipmaps (if possible) for a texture.
  5335. *
  5336. * Overwritten and set to `false` by default.
  5337. *
  5338. * @type {boolean}
  5339. * @default false
  5340. */
  5341. this.generateMipmaps = false;
  5342. /**
  5343. * If set to `true`, the texture is flipped along the vertical axis when
  5344. * uploaded to the GPU.
  5345. *
  5346. * Overwritten and set to `false` by default.
  5347. *
  5348. * @type {boolean}
  5349. * @default false
  5350. */
  5351. this.flipY = false;
  5352. /**
  5353. * Specifies the alignment requirements for the start of each pixel row in memory.
  5354. *
  5355. * Overwritten and set to `1` by default.
  5356. *
  5357. * @type {boolean}
  5358. * @default 1
  5359. */
  5360. this.unpackAlignment = 1;
  5361. /**
  5362. * A set of all layers which need to be updated in the texture.
  5363. *
  5364. * @type {Set<number>}
  5365. */
  5366. this.layerUpdates = new Set();
  5367. }
  5368. /**
  5369. * Describes that a specific layer of the texture needs to be updated.
  5370. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  5371. * entire data texture array is sent to the GPU. Marking specific
  5372. * layers will only transmit subsets of all mipmaps associated with a
  5373. * specific depth in the array which is often much more performant.
  5374. *
  5375. * @param {number} layerIndex - The layer index that should be updated.
  5376. */
  5377. addLayerUpdate( layerIndex ) {
  5378. this.layerUpdates.add( layerIndex );
  5379. }
  5380. /**
  5381. * Resets the layer updates registry.
  5382. */
  5383. clearLayerUpdates() {
  5384. this.layerUpdates.clear();
  5385. }
  5386. }
  5387. /**
  5388. * An array render target used in context of {@link WebGLRenderer}.
  5389. *
  5390. * @augments WebGLRenderTarget
  5391. */
  5392. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  5393. /**
  5394. * Constructs a new array render target.
  5395. *
  5396. * @param {number} [width=1] - The width of the render target.
  5397. * @param {number} [height=1] - The height of the render target.
  5398. * @param {number} [depth=1] - The height of the render target.
  5399. * @param {RenderTarget~Options} [options] - The configuration object.
  5400. */
  5401. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  5402. super( width, height, options );
  5403. /**
  5404. * This flag can be used for type testing.
  5405. *
  5406. * @type {boolean}
  5407. * @readonly
  5408. * @default true
  5409. */
  5410. this.isWebGLArrayRenderTarget = true;
  5411. this.depth = depth;
  5412. /**
  5413. * Overwritten with a different texture type.
  5414. *
  5415. * @type {DataArrayTexture}
  5416. */
  5417. this.texture = new DataArrayTexture( null, width, height, depth );
  5418. this.texture.isRenderTargetTexture = true;
  5419. }
  5420. }
  5421. /**
  5422. * Creates a three-dimensional texture from raw data, with parameters to
  5423. * divide it into width, height, and depth.
  5424. *
  5425. * @augments Texture
  5426. */
  5427. class Data3DTexture extends Texture {
  5428. /**
  5429. * Constructs a new data array texture.
  5430. *
  5431. * @param {?TypedArray} [data=null] - The buffer data.
  5432. * @param {number} [width=1] - The width of the texture.
  5433. * @param {number} [height=1] - The height of the texture.
  5434. * @param {number} [depth=1] - The depth of the texture.
  5435. */
  5436. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  5437. // We're going to add .setXXX() methods for setting properties later.
  5438. // Users can still set in Data3DTexture directly.
  5439. //
  5440. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  5441. // texture.anisotropy = 16;
  5442. //
  5443. // See #14839
  5444. super( null );
  5445. /**
  5446. * This flag can be used for type testing.
  5447. *
  5448. * @type {boolean}
  5449. * @readonly
  5450. * @default true
  5451. */
  5452. this.isData3DTexture = true;
  5453. /**
  5454. * The image definition of a data texture.
  5455. *
  5456. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  5457. */
  5458. this.image = { data, width, height, depth };
  5459. /**
  5460. * How the texture is sampled when a texel covers more than one pixel.
  5461. *
  5462. * Overwritten and set to `NearestFilter` by default.
  5463. *
  5464. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5465. * @default NearestFilter
  5466. */
  5467. this.magFilter = NearestFilter;
  5468. /**
  5469. * How the texture is sampled when a texel covers less than one pixel.
  5470. *
  5471. * Overwritten and set to `NearestFilter` by default.
  5472. *
  5473. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5474. * @default NearestFilter
  5475. */
  5476. this.minFilter = NearestFilter;
  5477. /**
  5478. * This defines how the texture is wrapped in the depth and corresponds to
  5479. * *W* in UVW mapping.
  5480. *
  5481. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5482. * @default ClampToEdgeWrapping
  5483. */
  5484. this.wrapR = ClampToEdgeWrapping;
  5485. /**
  5486. * Whether to generate mipmaps (if possible) for a texture.
  5487. *
  5488. * Overwritten and set to `false` by default.
  5489. *
  5490. * @type {boolean}
  5491. * @default false
  5492. */
  5493. this.generateMipmaps = false;
  5494. /**
  5495. * If set to `true`, the texture is flipped along the vertical axis when
  5496. * uploaded to the GPU.
  5497. *
  5498. * Overwritten and set to `false` by default.
  5499. *
  5500. * @type {boolean}
  5501. * @default false
  5502. */
  5503. this.flipY = false;
  5504. /**
  5505. * Specifies the alignment requirements for the start of each pixel row in memory.
  5506. *
  5507. * Overwritten and set to `1` by default.
  5508. *
  5509. * @type {boolean}
  5510. * @default 1
  5511. */
  5512. this.unpackAlignment = 1;
  5513. }
  5514. }
  5515. /**
  5516. * A 3D render target used in context of {@link WebGLRenderer}.
  5517. *
  5518. * @augments WebGLRenderTarget
  5519. */
  5520. class WebGL3DRenderTarget extends WebGLRenderTarget {
  5521. /**
  5522. * Constructs a new 3D render target.
  5523. *
  5524. * @param {number} [width=1] - The width of the render target.
  5525. * @param {number} [height=1] - The height of the render target.
  5526. * @param {number} [depth=1] - The height of the render target.
  5527. * @param {RenderTarget~Options} [options] - The configuration object.
  5528. */
  5529. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  5530. super( width, height, options );
  5531. /**
  5532. * This flag can be used for type testing.
  5533. *
  5534. * @type {boolean}
  5535. * @readonly
  5536. * @default true
  5537. */
  5538. this.isWebGL3DRenderTarget = true;
  5539. this.depth = depth;
  5540. /**
  5541. * Overwritten with a different texture type.
  5542. *
  5543. * @type {Data3DTexture}
  5544. */
  5545. this.texture = new Data3DTexture( null, width, height, depth );
  5546. this.texture.isRenderTargetTexture = true;
  5547. }
  5548. }
  5549. /**
  5550. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  5551. *
  5552. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  5553. * the corresponding order.
  5554. *
  5555. * Note that three.js expects Quaternions to be normalized.
  5556. * ```js
  5557. * const quaternion = new THREE.Quaternion();
  5558. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  5559. *
  5560. * const vector = new THREE.Vector3( 1, 0, 0 );
  5561. * vector.applyQuaternion( quaternion );
  5562. * ```
  5563. */
  5564. class Quaternion {
  5565. /**
  5566. * Constructs a new quaternion.
  5567. *
  5568. * @param {number} [x=0] - The x value of this quaternion.
  5569. * @param {number} [y=0] - The y value of this quaternion.
  5570. * @param {number} [z=0] - The z value of this quaternion.
  5571. * @param {number} [w=1] - The w value of this quaternion.
  5572. */
  5573. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  5574. /**
  5575. * This flag can be used for type testing.
  5576. *
  5577. * @type {boolean}
  5578. * @readonly
  5579. * @default true
  5580. */
  5581. this.isQuaternion = true;
  5582. this._x = x;
  5583. this._y = y;
  5584. this._z = z;
  5585. this._w = w;
  5586. }
  5587. /**
  5588. * Interpolates between two quaternions via SLERP. This implementation assumes the
  5589. * quaternion data are managed in flat arrays.
  5590. *
  5591. * @param {Array<number>} dst - The destination array.
  5592. * @param {number} dstOffset - An offset into the destination array.
  5593. * @param {Array<number>} src0 - The source array of the first quaternion.
  5594. * @param {number} srcOffset0 - An offset into the first source array.
  5595. * @param {Array<number>} src1 - The source array of the second quaternion.
  5596. * @param {number} srcOffset1 - An offset into the second source array.
  5597. * @param {number} t - The interpolation factor in the range `[0,1]`.
  5598. * @see {@link Quaternion#slerp}
  5599. */
  5600. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  5601. // fuzz-free, array-based Quaternion SLERP operation
  5602. let x0 = src0[ srcOffset0 + 0 ],
  5603. y0 = src0[ srcOffset0 + 1 ],
  5604. z0 = src0[ srcOffset0 + 2 ],
  5605. w0 = src0[ srcOffset0 + 3 ];
  5606. const x1 = src1[ srcOffset1 + 0 ],
  5607. y1 = src1[ srcOffset1 + 1 ],
  5608. z1 = src1[ srcOffset1 + 2 ],
  5609. w1 = src1[ srcOffset1 + 3 ];
  5610. if ( t === 0 ) {
  5611. dst[ dstOffset + 0 ] = x0;
  5612. dst[ dstOffset + 1 ] = y0;
  5613. dst[ dstOffset + 2 ] = z0;
  5614. dst[ dstOffset + 3 ] = w0;
  5615. return;
  5616. }
  5617. if ( t === 1 ) {
  5618. dst[ dstOffset + 0 ] = x1;
  5619. dst[ dstOffset + 1 ] = y1;
  5620. dst[ dstOffset + 2 ] = z1;
  5621. dst[ dstOffset + 3 ] = w1;
  5622. return;
  5623. }
  5624. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  5625. let s = 1 - t;
  5626. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  5627. dir = ( cos >= 0 ? 1 : -1 ),
  5628. sqrSin = 1 - cos * cos;
  5629. // Skip the Slerp for tiny steps to avoid numeric problems:
  5630. if ( sqrSin > Number.EPSILON ) {
  5631. const sin = Math.sqrt( sqrSin ),
  5632. len = Math.atan2( sin, cos * dir );
  5633. s = Math.sin( s * len ) / sin;
  5634. t = Math.sin( t * len ) / sin;
  5635. }
  5636. const tDir = t * dir;
  5637. x0 = x0 * s + x1 * tDir;
  5638. y0 = y0 * s + y1 * tDir;
  5639. z0 = z0 * s + z1 * tDir;
  5640. w0 = w0 * s + w1 * tDir;
  5641. // Normalize in case we just did a lerp:
  5642. if ( s === 1 - t ) {
  5643. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  5644. x0 *= f;
  5645. y0 *= f;
  5646. z0 *= f;
  5647. w0 *= f;
  5648. }
  5649. }
  5650. dst[ dstOffset ] = x0;
  5651. dst[ dstOffset + 1 ] = y0;
  5652. dst[ dstOffset + 2 ] = z0;
  5653. dst[ dstOffset + 3 ] = w0;
  5654. }
  5655. /**
  5656. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  5657. * in flat arrays.
  5658. *
  5659. * @param {Array<number>} dst - The destination array.
  5660. * @param {number} dstOffset - An offset into the destination array.
  5661. * @param {Array<number>} src0 - The source array of the first quaternion.
  5662. * @param {number} srcOffset0 - An offset into the first source array.
  5663. * @param {Array<number>} src1 - The source array of the second quaternion.
  5664. * @param {number} srcOffset1 - An offset into the second source array.
  5665. * @return {Array<number>} The destination array.
  5666. * @see {@link Quaternion#multiplyQuaternions}.
  5667. */
  5668. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  5669. const x0 = src0[ srcOffset0 ];
  5670. const y0 = src0[ srcOffset0 + 1 ];
  5671. const z0 = src0[ srcOffset0 + 2 ];
  5672. const w0 = src0[ srcOffset0 + 3 ];
  5673. const x1 = src1[ srcOffset1 ];
  5674. const y1 = src1[ srcOffset1 + 1 ];
  5675. const z1 = src1[ srcOffset1 + 2 ];
  5676. const w1 = src1[ srcOffset1 + 3 ];
  5677. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  5678. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  5679. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  5680. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  5681. return dst;
  5682. }
  5683. /**
  5684. * The x value of this quaternion.
  5685. *
  5686. * @type {number}
  5687. * @default 0
  5688. */
  5689. get x() {
  5690. return this._x;
  5691. }
  5692. set x( value ) {
  5693. this._x = value;
  5694. this._onChangeCallback();
  5695. }
  5696. /**
  5697. * The y value of this quaternion.
  5698. *
  5699. * @type {number}
  5700. * @default 0
  5701. */
  5702. get y() {
  5703. return this._y;
  5704. }
  5705. set y( value ) {
  5706. this._y = value;
  5707. this._onChangeCallback();
  5708. }
  5709. /**
  5710. * The z value of this quaternion.
  5711. *
  5712. * @type {number}
  5713. * @default 0
  5714. */
  5715. get z() {
  5716. return this._z;
  5717. }
  5718. set z( value ) {
  5719. this._z = value;
  5720. this._onChangeCallback();
  5721. }
  5722. /**
  5723. * The w value of this quaternion.
  5724. *
  5725. * @type {number}
  5726. * @default 1
  5727. */
  5728. get w() {
  5729. return this._w;
  5730. }
  5731. set w( value ) {
  5732. this._w = value;
  5733. this._onChangeCallback();
  5734. }
  5735. /**
  5736. * Sets the quaternion components.
  5737. *
  5738. * @param {number} x - The x value of this quaternion.
  5739. * @param {number} y - The y value of this quaternion.
  5740. * @param {number} z - The z value of this quaternion.
  5741. * @param {number} w - The w value of this quaternion.
  5742. * @return {Quaternion} A reference to this quaternion.
  5743. */
  5744. set( x, y, z, w ) {
  5745. this._x = x;
  5746. this._y = y;
  5747. this._z = z;
  5748. this._w = w;
  5749. this._onChangeCallback();
  5750. return this;
  5751. }
  5752. /**
  5753. * Returns a new quaternion with copied values from this instance.
  5754. *
  5755. * @return {Quaternion} A clone of this instance.
  5756. */
  5757. clone() {
  5758. return new this.constructor( this._x, this._y, this._z, this._w );
  5759. }
  5760. /**
  5761. * Copies the values of the given quaternion to this instance.
  5762. *
  5763. * @param {Quaternion} quaternion - The quaternion to copy.
  5764. * @return {Quaternion} A reference to this quaternion.
  5765. */
  5766. copy( quaternion ) {
  5767. this._x = quaternion.x;
  5768. this._y = quaternion.y;
  5769. this._z = quaternion.z;
  5770. this._w = quaternion.w;
  5771. this._onChangeCallback();
  5772. return this;
  5773. }
  5774. /**
  5775. * Sets this quaternion from the rotation specified by the given
  5776. * Euler angles.
  5777. *
  5778. * @param {Euler} euler - The Euler angles.
  5779. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  5780. * @return {Quaternion} A reference to this quaternion.
  5781. */
  5782. setFromEuler( euler, update = true ) {
  5783. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  5784. // http://www.mathworks.com/matlabcentral/fileexchange/
  5785. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  5786. // content/SpinCalc.m
  5787. const cos = Math.cos;
  5788. const sin = Math.sin;
  5789. const c1 = cos( x / 2 );
  5790. const c2 = cos( y / 2 );
  5791. const c3 = cos( z / 2 );
  5792. const s1 = sin( x / 2 );
  5793. const s2 = sin( y / 2 );
  5794. const s3 = sin( z / 2 );
  5795. switch ( order ) {
  5796. case 'XYZ':
  5797. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5798. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5799. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5800. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5801. break;
  5802. case 'YXZ':
  5803. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5804. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5805. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5806. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5807. break;
  5808. case 'ZXY':
  5809. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5810. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5811. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5812. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5813. break;
  5814. case 'ZYX':
  5815. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5816. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5817. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5818. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5819. break;
  5820. case 'YZX':
  5821. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5822. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5823. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5824. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5825. break;
  5826. case 'XZY':
  5827. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5828. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5829. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5830. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5831. break;
  5832. default:
  5833. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  5834. }
  5835. if ( update === true ) this._onChangeCallback();
  5836. return this;
  5837. }
  5838. /**
  5839. * Sets this quaternion from the given axis and angle.
  5840. *
  5841. * @param {Vector3} axis - The normalized axis.
  5842. * @param {number} angle - The angle in radians.
  5843. * @return {Quaternion} A reference to this quaternion.
  5844. */
  5845. setFromAxisAngle( axis, angle ) {
  5846. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  5847. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  5848. this._x = axis.x * s;
  5849. this._y = axis.y * s;
  5850. this._z = axis.z * s;
  5851. this._w = Math.cos( halfAngle );
  5852. this._onChangeCallback();
  5853. return this;
  5854. }
  5855. /**
  5856. * Sets this quaternion from the given rotation matrix.
  5857. *
  5858. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  5859. * @return {Quaternion} A reference to this quaternion.
  5860. */
  5861. setFromRotationMatrix( m ) {
  5862. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  5863. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5864. const te = m.elements,
  5865. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  5866. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  5867. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  5868. trace = m11 + m22 + m33;
  5869. if ( trace > 0 ) {
  5870. const s = 0.5 / Math.sqrt( trace + 1.0 );
  5871. this._w = 0.25 / s;
  5872. this._x = ( m32 - m23 ) * s;
  5873. this._y = ( m13 - m31 ) * s;
  5874. this._z = ( m21 - m12 ) * s;
  5875. } else if ( m11 > m22 && m11 > m33 ) {
  5876. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  5877. this._w = ( m32 - m23 ) / s;
  5878. this._x = 0.25 * s;
  5879. this._y = ( m12 + m21 ) / s;
  5880. this._z = ( m13 + m31 ) / s;
  5881. } else if ( m22 > m33 ) {
  5882. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  5883. this._w = ( m13 - m31 ) / s;
  5884. this._x = ( m12 + m21 ) / s;
  5885. this._y = 0.25 * s;
  5886. this._z = ( m23 + m32 ) / s;
  5887. } else {
  5888. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  5889. this._w = ( m21 - m12 ) / s;
  5890. this._x = ( m13 + m31 ) / s;
  5891. this._y = ( m23 + m32 ) / s;
  5892. this._z = 0.25 * s;
  5893. }
  5894. this._onChangeCallback();
  5895. return this;
  5896. }
  5897. /**
  5898. * Sets this quaternion to the rotation required to rotate the direction vector
  5899. * `vFrom` to the direction vector `vTo`.
  5900. *
  5901. * @param {Vector3} vFrom - The first (normalized) direction vector.
  5902. * @param {Vector3} vTo - The second (normalized) direction vector.
  5903. * @return {Quaternion} A reference to this quaternion.
  5904. */
  5905. setFromUnitVectors( vFrom, vTo ) {
  5906. // assumes direction vectors vFrom and vTo are normalized
  5907. let r = vFrom.dot( vTo ) + 1;
  5908. if ( r < Number.EPSILON ) {
  5909. // vFrom and vTo point in opposite directions
  5910. r = 0;
  5911. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  5912. this._x = - vFrom.y;
  5913. this._y = vFrom.x;
  5914. this._z = 0;
  5915. this._w = r;
  5916. } else {
  5917. this._x = 0;
  5918. this._y = - vFrom.z;
  5919. this._z = vFrom.y;
  5920. this._w = r;
  5921. }
  5922. } else {
  5923. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  5924. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  5925. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  5926. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  5927. this._w = r;
  5928. }
  5929. return this.normalize();
  5930. }
  5931. /**
  5932. * Returns the angle between this quaternion and the given one in radians.
  5933. *
  5934. * @param {Quaternion} q - The quaternion to compute the angle with.
  5935. * @return {number} The angle in radians.
  5936. */
  5937. angleTo( q ) {
  5938. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  5939. }
  5940. /**
  5941. * Rotates this quaternion by a given angular step to the given quaternion.
  5942. * The method ensures that the final quaternion will not overshoot `q`.
  5943. *
  5944. * @param {Quaternion} q - The target quaternion.
  5945. * @param {number} step - The angular step in radians.
  5946. * @return {Quaternion} A reference to this quaternion.
  5947. */
  5948. rotateTowards( q, step ) {
  5949. const angle = this.angleTo( q );
  5950. if ( angle === 0 ) return this;
  5951. const t = Math.min( 1, step / angle );
  5952. this.slerp( q, t );
  5953. return this;
  5954. }
  5955. /**
  5956. * Sets this quaternion to the identity quaternion; that is, to the
  5957. * quaternion that represents "no rotation".
  5958. *
  5959. * @return {Quaternion} A reference to this quaternion.
  5960. */
  5961. identity() {
  5962. return this.set( 0, 0, 0, 1 );
  5963. }
  5964. /**
  5965. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  5966. * quaternion is assumed to have unit length.
  5967. *
  5968. * @return {Quaternion} A reference to this quaternion.
  5969. */
  5970. invert() {
  5971. return this.conjugate();
  5972. }
  5973. /**
  5974. * Returns the rotational conjugate of this quaternion. The conjugate of a
  5975. * quaternion represents the same rotation in the opposite direction about
  5976. * the rotational axis.
  5977. *
  5978. * @return {Quaternion} A reference to this quaternion.
  5979. */
  5980. conjugate() {
  5981. this._x *= -1;
  5982. this._y *= -1;
  5983. this._z *= -1;
  5984. this._onChangeCallback();
  5985. return this;
  5986. }
  5987. /**
  5988. * Calculates the dot product of this quaternion and the given one.
  5989. *
  5990. * @param {Quaternion} v - The quaternion to compute the dot product with.
  5991. * @return {number} The result of the dot product.
  5992. */
  5993. dot( v ) {
  5994. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  5995. }
  5996. /**
  5997. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  5998. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  5999. * lengths of two quaternions, as this is a slightly more efficient calculation than
  6000. * {@link Quaternion#length}.
  6001. *
  6002. * @return {number} The squared Euclidean length.
  6003. */
  6004. lengthSq() {
  6005. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  6006. }
  6007. /**
  6008. * Computes the Euclidean length (straight-line length) of this quaternion,
  6009. * considered as a 4 dimensional vector.
  6010. *
  6011. * @return {number} The Euclidean length.
  6012. */
  6013. length() {
  6014. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  6015. }
  6016. /**
  6017. * Normalizes this quaternion - that is, calculated the quaternion that performs
  6018. * the same rotation as this one, but has a length equal to `1`.
  6019. *
  6020. * @return {Quaternion} A reference to this quaternion.
  6021. */
  6022. normalize() {
  6023. let l = this.length();
  6024. if ( l === 0 ) {
  6025. this._x = 0;
  6026. this._y = 0;
  6027. this._z = 0;
  6028. this._w = 1;
  6029. } else {
  6030. l = 1 / l;
  6031. this._x = this._x * l;
  6032. this._y = this._y * l;
  6033. this._z = this._z * l;
  6034. this._w = this._w * l;
  6035. }
  6036. this._onChangeCallback();
  6037. return this;
  6038. }
  6039. /**
  6040. * Multiplies this quaternion by the given one.
  6041. *
  6042. * @param {Quaternion} q - The quaternion.
  6043. * @return {Quaternion} A reference to this quaternion.
  6044. */
  6045. multiply( q ) {
  6046. return this.multiplyQuaternions( this, q );
  6047. }
  6048. /**
  6049. * Pre-multiplies this quaternion by the given one.
  6050. *
  6051. * @param {Quaternion} q - The quaternion.
  6052. * @return {Quaternion} A reference to this quaternion.
  6053. */
  6054. premultiply( q ) {
  6055. return this.multiplyQuaternions( q, this );
  6056. }
  6057. /**
  6058. * Multiplies the given quaternions and stores the result in this instance.
  6059. *
  6060. * @param {Quaternion} a - The first quaternion.
  6061. * @param {Quaternion} b - The second quaternion.
  6062. * @return {Quaternion} A reference to this quaternion.
  6063. */
  6064. multiplyQuaternions( a, b ) {
  6065. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  6066. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  6067. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  6068. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  6069. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  6070. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  6071. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  6072. this._onChangeCallback();
  6073. return this;
  6074. }
  6075. /**
  6076. * Performs a spherical linear interpolation between quaternions.
  6077. *
  6078. * @param {Quaternion} qb - The target quaternion.
  6079. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  6080. * @return {Quaternion} A reference to this quaternion.
  6081. */
  6082. slerp( qb, t ) {
  6083. if ( t === 0 ) return this;
  6084. if ( t === 1 ) return this.copy( qb );
  6085. const x = this._x, y = this._y, z = this._z, w = this._w;
  6086. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  6087. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  6088. if ( cosHalfTheta < 0 ) {
  6089. this._w = - qb._w;
  6090. this._x = - qb._x;
  6091. this._y = - qb._y;
  6092. this._z = - qb._z;
  6093. cosHalfTheta = - cosHalfTheta;
  6094. } else {
  6095. this.copy( qb );
  6096. }
  6097. if ( cosHalfTheta >= 1.0 ) {
  6098. this._w = w;
  6099. this._x = x;
  6100. this._y = y;
  6101. this._z = z;
  6102. return this;
  6103. }
  6104. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  6105. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  6106. const s = 1 - t;
  6107. this._w = s * w + t * this._w;
  6108. this._x = s * x + t * this._x;
  6109. this._y = s * y + t * this._y;
  6110. this._z = s * z + t * this._z;
  6111. this.normalize(); // normalize calls _onChangeCallback()
  6112. return this;
  6113. }
  6114. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  6115. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  6116. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  6117. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  6118. this._w = ( w * ratioA + this._w * ratioB );
  6119. this._x = ( x * ratioA + this._x * ratioB );
  6120. this._y = ( y * ratioA + this._y * ratioB );
  6121. this._z = ( z * ratioA + this._z * ratioB );
  6122. this._onChangeCallback();
  6123. return this;
  6124. }
  6125. /**
  6126. * Performs a spherical linear interpolation between the given quaternions
  6127. * and stores the result in this quaternion.
  6128. *
  6129. * @param {Quaternion} qa - The source quaternion.
  6130. * @param {Quaternion} qb - The target quaternion.
  6131. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  6132. * @return {Quaternion} A reference to this quaternion.
  6133. */
  6134. slerpQuaternions( qa, qb, t ) {
  6135. return this.copy( qa ).slerp( qb, t );
  6136. }
  6137. /**
  6138. * Sets this quaternion to a uniformly random, normalized quaternion.
  6139. *
  6140. * @return {Quaternion} A reference to this quaternion.
  6141. */
  6142. random() {
  6143. // Ken Shoemake
  6144. // Uniform random rotations
  6145. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  6146. const theta1 = 2 * Math.PI * Math.random();
  6147. const theta2 = 2 * Math.PI * Math.random();
  6148. const x0 = Math.random();
  6149. const r1 = Math.sqrt( 1 - x0 );
  6150. const r2 = Math.sqrt( x0 );
  6151. return this.set(
  6152. r1 * Math.sin( theta1 ),
  6153. r1 * Math.cos( theta1 ),
  6154. r2 * Math.sin( theta2 ),
  6155. r2 * Math.cos( theta2 ),
  6156. );
  6157. }
  6158. /**
  6159. * Returns `true` if this quaternion is equal with the given one.
  6160. *
  6161. * @param {Quaternion} quaternion - The quaternion to test for equality.
  6162. * @return {boolean} Whether this quaternion is equal with the given one.
  6163. */
  6164. equals( quaternion ) {
  6165. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  6166. }
  6167. /**
  6168. * Sets this quaternion's components from the given array.
  6169. *
  6170. * @param {Array<number>} array - An array holding the quaternion component values.
  6171. * @param {number} [offset=0] - The offset into the array.
  6172. * @return {Quaternion} A reference to this quaternion.
  6173. */
  6174. fromArray( array, offset = 0 ) {
  6175. this._x = array[ offset ];
  6176. this._y = array[ offset + 1 ];
  6177. this._z = array[ offset + 2 ];
  6178. this._w = array[ offset + 3 ];
  6179. this._onChangeCallback();
  6180. return this;
  6181. }
  6182. /**
  6183. * Writes the components of this quaternion to the given array. If no array is provided,
  6184. * the method returns a new instance.
  6185. *
  6186. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  6187. * @param {number} [offset=0] - Index of the first element in the array.
  6188. * @return {Array<number>} The quaternion components.
  6189. */
  6190. toArray( array = [], offset = 0 ) {
  6191. array[ offset ] = this._x;
  6192. array[ offset + 1 ] = this._y;
  6193. array[ offset + 2 ] = this._z;
  6194. array[ offset + 3 ] = this._w;
  6195. return array;
  6196. }
  6197. /**
  6198. * Sets the components of this quaternion from the given buffer attribute.
  6199. *
  6200. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  6201. * @param {number} index - The index into the attribute.
  6202. * @return {Quaternion} A reference to this quaternion.
  6203. */
  6204. fromBufferAttribute( attribute, index ) {
  6205. this._x = attribute.getX( index );
  6206. this._y = attribute.getY( index );
  6207. this._z = attribute.getZ( index );
  6208. this._w = attribute.getW( index );
  6209. this._onChangeCallback();
  6210. return this;
  6211. }
  6212. /**
  6213. * This methods defines the serialization result of this class. Returns the
  6214. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  6215. *
  6216. * @return {Array<number>} The serialized quaternion.
  6217. */
  6218. toJSON() {
  6219. return this.toArray();
  6220. }
  6221. _onChange( callback ) {
  6222. this._onChangeCallback = callback;
  6223. return this;
  6224. }
  6225. _onChangeCallback() {}
  6226. *[ Symbol.iterator ]() {
  6227. yield this._x;
  6228. yield this._y;
  6229. yield this._z;
  6230. yield this._w;
  6231. }
  6232. }
  6233. /**
  6234. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  6235. * (labeled x, y and z), which can be used to represent a number of things, such as:
  6236. *
  6237. * - A point in 3D space.
  6238. * - A direction and length in 3D space. In three.js the length will
  6239. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  6240. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  6241. * - Any arbitrary ordered triplet of numbers.
  6242. *
  6243. * There are other things a 3D vector can be used to represent, such as
  6244. * momentum vectors and so on, however these are the most
  6245. * common uses in three.js.
  6246. *
  6247. * Iterating through a vector instance will yield its components `(x, y, z)` in
  6248. * the corresponding order.
  6249. * ```js
  6250. * const a = new THREE.Vector3( 0, 1, 0 );
  6251. *
  6252. * //no arguments; will be initialised to (0, 0, 0)
  6253. * const b = new THREE.Vector3( );
  6254. *
  6255. * const d = a.distanceTo( b );
  6256. * ```
  6257. */
  6258. class Vector3 {
  6259. /**
  6260. * Constructs a new 3D vector.
  6261. *
  6262. * @param {number} [x=0] - The x value of this vector.
  6263. * @param {number} [y=0] - The y value of this vector.
  6264. * @param {number} [z=0] - The z value of this vector.
  6265. */
  6266. constructor( x = 0, y = 0, z = 0 ) {
  6267. /**
  6268. * This flag can be used for type testing.
  6269. *
  6270. * @type {boolean}
  6271. * @readonly
  6272. * @default true
  6273. */
  6274. Vector3.prototype.isVector3 = true;
  6275. /**
  6276. * The x value of this vector.
  6277. *
  6278. * @type {number}
  6279. */
  6280. this.x = x;
  6281. /**
  6282. * The y value of this vector.
  6283. *
  6284. * @type {number}
  6285. */
  6286. this.y = y;
  6287. /**
  6288. * The z value of this vector.
  6289. *
  6290. * @type {number}
  6291. */
  6292. this.z = z;
  6293. }
  6294. /**
  6295. * Sets the vector components.
  6296. *
  6297. * @param {number} x - The value of the x component.
  6298. * @param {number} y - The value of the y component.
  6299. * @param {number} z - The value of the z component.
  6300. * @return {Vector3} A reference to this vector.
  6301. */
  6302. set( x, y, z ) {
  6303. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  6304. this.x = x;
  6305. this.y = y;
  6306. this.z = z;
  6307. return this;
  6308. }
  6309. /**
  6310. * Sets the vector components to the same value.
  6311. *
  6312. * @param {number} scalar - The value to set for all vector components.
  6313. * @return {Vector3} A reference to this vector.
  6314. */
  6315. setScalar( scalar ) {
  6316. this.x = scalar;
  6317. this.y = scalar;
  6318. this.z = scalar;
  6319. return this;
  6320. }
  6321. /**
  6322. * Sets the vector's x component to the given value
  6323. *
  6324. * @param {number} x - The value to set.
  6325. * @return {Vector3} A reference to this vector.
  6326. */
  6327. setX( x ) {
  6328. this.x = x;
  6329. return this;
  6330. }
  6331. /**
  6332. * Sets the vector's y component to the given value
  6333. *
  6334. * @param {number} y - The value to set.
  6335. * @return {Vector3} A reference to this vector.
  6336. */
  6337. setY( y ) {
  6338. this.y = y;
  6339. return this;
  6340. }
  6341. /**
  6342. * Sets the vector's z component to the given value
  6343. *
  6344. * @param {number} z - The value to set.
  6345. * @return {Vector3} A reference to this vector.
  6346. */
  6347. setZ( z ) {
  6348. this.z = z;
  6349. return this;
  6350. }
  6351. /**
  6352. * Allows to set a vector component with an index.
  6353. *
  6354. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  6355. * @param {number} value - The value to set.
  6356. * @return {Vector3} A reference to this vector.
  6357. */
  6358. setComponent( index, value ) {
  6359. switch ( index ) {
  6360. case 0: this.x = value; break;
  6361. case 1: this.y = value; break;
  6362. case 2: this.z = value; break;
  6363. default: throw new Error( 'index is out of range: ' + index );
  6364. }
  6365. return this;
  6366. }
  6367. /**
  6368. * Returns the value of the vector component which matches the given index.
  6369. *
  6370. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  6371. * @return {number} A vector component value.
  6372. */
  6373. getComponent( index ) {
  6374. switch ( index ) {
  6375. case 0: return this.x;
  6376. case 1: return this.y;
  6377. case 2: return this.z;
  6378. default: throw new Error( 'index is out of range: ' + index );
  6379. }
  6380. }
  6381. /**
  6382. * Returns a new vector with copied values from this instance.
  6383. *
  6384. * @return {Vector3} A clone of this instance.
  6385. */
  6386. clone() {
  6387. return new this.constructor( this.x, this.y, this.z );
  6388. }
  6389. /**
  6390. * Copies the values of the given vector to this instance.
  6391. *
  6392. * @param {Vector3} v - The vector to copy.
  6393. * @return {Vector3} A reference to this vector.
  6394. */
  6395. copy( v ) {
  6396. this.x = v.x;
  6397. this.y = v.y;
  6398. this.z = v.z;
  6399. return this;
  6400. }
  6401. /**
  6402. * Adds the given vector to this instance.
  6403. *
  6404. * @param {Vector3} v - The vector to add.
  6405. * @return {Vector3} A reference to this vector.
  6406. */
  6407. add( v ) {
  6408. this.x += v.x;
  6409. this.y += v.y;
  6410. this.z += v.z;
  6411. return this;
  6412. }
  6413. /**
  6414. * Adds the given scalar value to all components of this instance.
  6415. *
  6416. * @param {number} s - The scalar to add.
  6417. * @return {Vector3} A reference to this vector.
  6418. */
  6419. addScalar( s ) {
  6420. this.x += s;
  6421. this.y += s;
  6422. this.z += s;
  6423. return this;
  6424. }
  6425. /**
  6426. * Adds the given vectors and stores the result in this instance.
  6427. *
  6428. * @param {Vector3} a - The first vector.
  6429. * @param {Vector3} b - The second vector.
  6430. * @return {Vector3} A reference to this vector.
  6431. */
  6432. addVectors( a, b ) {
  6433. this.x = a.x + b.x;
  6434. this.y = a.y + b.y;
  6435. this.z = a.z + b.z;
  6436. return this;
  6437. }
  6438. /**
  6439. * Adds the given vector scaled by the given factor to this instance.
  6440. *
  6441. * @param {Vector3|Vector4} v - The vector.
  6442. * @param {number} s - The factor that scales `v`.
  6443. * @return {Vector3} A reference to this vector.
  6444. */
  6445. addScaledVector( v, s ) {
  6446. this.x += v.x * s;
  6447. this.y += v.y * s;
  6448. this.z += v.z * s;
  6449. return this;
  6450. }
  6451. /**
  6452. * Subtracts the given vector from this instance.
  6453. *
  6454. * @param {Vector3} v - The vector to subtract.
  6455. * @return {Vector3} A reference to this vector.
  6456. */
  6457. sub( v ) {
  6458. this.x -= v.x;
  6459. this.y -= v.y;
  6460. this.z -= v.z;
  6461. return this;
  6462. }
  6463. /**
  6464. * Subtracts the given scalar value from all components of this instance.
  6465. *
  6466. * @param {number} s - The scalar to subtract.
  6467. * @return {Vector3} A reference to this vector.
  6468. */
  6469. subScalar( s ) {
  6470. this.x -= s;
  6471. this.y -= s;
  6472. this.z -= s;
  6473. return this;
  6474. }
  6475. /**
  6476. * Subtracts the given vectors and stores the result in this instance.
  6477. *
  6478. * @param {Vector3} a - The first vector.
  6479. * @param {Vector3} b - The second vector.
  6480. * @return {Vector3} A reference to this vector.
  6481. */
  6482. subVectors( a, b ) {
  6483. this.x = a.x - b.x;
  6484. this.y = a.y - b.y;
  6485. this.z = a.z - b.z;
  6486. return this;
  6487. }
  6488. /**
  6489. * Multiplies the given vector with this instance.
  6490. *
  6491. * @param {Vector3} v - The vector to multiply.
  6492. * @return {Vector3} A reference to this vector.
  6493. */
  6494. multiply( v ) {
  6495. this.x *= v.x;
  6496. this.y *= v.y;
  6497. this.z *= v.z;
  6498. return this;
  6499. }
  6500. /**
  6501. * Multiplies the given scalar value with all components of this instance.
  6502. *
  6503. * @param {number} scalar - The scalar to multiply.
  6504. * @return {Vector3} A reference to this vector.
  6505. */
  6506. multiplyScalar( scalar ) {
  6507. this.x *= scalar;
  6508. this.y *= scalar;
  6509. this.z *= scalar;
  6510. return this;
  6511. }
  6512. /**
  6513. * Multiplies the given vectors and stores the result in this instance.
  6514. *
  6515. * @param {Vector3} a - The first vector.
  6516. * @param {Vector3} b - The second vector.
  6517. * @return {Vector3} A reference to this vector.
  6518. */
  6519. multiplyVectors( a, b ) {
  6520. this.x = a.x * b.x;
  6521. this.y = a.y * b.y;
  6522. this.z = a.z * b.z;
  6523. return this;
  6524. }
  6525. /**
  6526. * Applies the given Euler rotation to this vector.
  6527. *
  6528. * @param {Euler} euler - The Euler angles.
  6529. * @return {Vector3} A reference to this vector.
  6530. */
  6531. applyEuler( euler ) {
  6532. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  6533. }
  6534. /**
  6535. * Applies a rotation specified by an axis and an angle to this vector.
  6536. *
  6537. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  6538. * @param {number} angle - The angle in radians.
  6539. * @return {Vector3} A reference to this vector.
  6540. */
  6541. applyAxisAngle( axis, angle ) {
  6542. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  6543. }
  6544. /**
  6545. * Multiplies this vector with the given 3x3 matrix.
  6546. *
  6547. * @param {Matrix3} m - The 3x3 matrix.
  6548. * @return {Vector3} A reference to this vector.
  6549. */
  6550. applyMatrix3( m ) {
  6551. const x = this.x, y = this.y, z = this.z;
  6552. const e = m.elements;
  6553. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  6554. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  6555. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  6556. return this;
  6557. }
  6558. /**
  6559. * Multiplies this vector by the given normal matrix and normalizes
  6560. * the result.
  6561. *
  6562. * @param {Matrix3} m - The normal matrix.
  6563. * @return {Vector3} A reference to this vector.
  6564. */
  6565. applyNormalMatrix( m ) {
  6566. return this.applyMatrix3( m ).normalize();
  6567. }
  6568. /**
  6569. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  6570. * divides by perspective.
  6571. *
  6572. * @param {Matrix4} m - The matrix to apply.
  6573. * @return {Vector3} A reference to this vector.
  6574. */
  6575. applyMatrix4( m ) {
  6576. const x = this.x, y = this.y, z = this.z;
  6577. const e = m.elements;
  6578. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  6579. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  6580. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  6581. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  6582. return this;
  6583. }
  6584. /**
  6585. * Applies the given Quaternion to this vector.
  6586. *
  6587. * @param {Quaternion} q - The Quaternion.
  6588. * @return {Vector3} A reference to this vector.
  6589. */
  6590. applyQuaternion( q ) {
  6591. // quaternion q is assumed to have unit length
  6592. const vx = this.x, vy = this.y, vz = this.z;
  6593. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  6594. // t = 2 * cross( q.xyz, v );
  6595. const tx = 2 * ( qy * vz - qz * vy );
  6596. const ty = 2 * ( qz * vx - qx * vz );
  6597. const tz = 2 * ( qx * vy - qy * vx );
  6598. // v + q.w * t + cross( q.xyz, t );
  6599. this.x = vx + qw * tx + qy * tz - qz * ty;
  6600. this.y = vy + qw * ty + qz * tx - qx * tz;
  6601. this.z = vz + qw * tz + qx * ty - qy * tx;
  6602. return this;
  6603. }
  6604. /**
  6605. * Projects this vector from world space into the camera's normalized
  6606. * device coordinate (NDC) space.
  6607. *
  6608. * @param {Camera} camera - The camera.
  6609. * @return {Vector3} A reference to this vector.
  6610. */
  6611. project( camera ) {
  6612. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  6613. }
  6614. /**
  6615. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  6616. * space into world space.
  6617. *
  6618. * @param {Camera} camera - The camera.
  6619. * @return {Vector3} A reference to this vector.
  6620. */
  6621. unproject( camera ) {
  6622. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  6623. }
  6624. /**
  6625. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  6626. * subset of the given 4x4 matrix and then normalizes the result.
  6627. *
  6628. * @param {Matrix4} m - The matrix.
  6629. * @return {Vector3} A reference to this vector.
  6630. */
  6631. transformDirection( m ) {
  6632. // input: THREE.Matrix4 affine matrix
  6633. // vector interpreted as a direction
  6634. const x = this.x, y = this.y, z = this.z;
  6635. const e = m.elements;
  6636. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  6637. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  6638. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  6639. return this.normalize();
  6640. }
  6641. /**
  6642. * Divides this instance by the given vector.
  6643. *
  6644. * @param {Vector3} v - The vector to divide.
  6645. * @return {Vector3} A reference to this vector.
  6646. */
  6647. divide( v ) {
  6648. this.x /= v.x;
  6649. this.y /= v.y;
  6650. this.z /= v.z;
  6651. return this;
  6652. }
  6653. /**
  6654. * Divides this vector by the given scalar.
  6655. *
  6656. * @param {number} scalar - The scalar to divide.
  6657. * @return {Vector3} A reference to this vector.
  6658. */
  6659. divideScalar( scalar ) {
  6660. return this.multiplyScalar( 1 / scalar );
  6661. }
  6662. /**
  6663. * If this vector's x, y or z value is greater than the given vector's x, y or z
  6664. * value, replace that value with the corresponding min value.
  6665. *
  6666. * @param {Vector3} v - The vector.
  6667. * @return {Vector3} A reference to this vector.
  6668. */
  6669. min( v ) {
  6670. this.x = Math.min( this.x, v.x );
  6671. this.y = Math.min( this.y, v.y );
  6672. this.z = Math.min( this.z, v.z );
  6673. return this;
  6674. }
  6675. /**
  6676. * If this vector's x, y or z value is less than the given vector's x, y or z
  6677. * value, replace that value with the corresponding max value.
  6678. *
  6679. * @param {Vector3} v - The vector.
  6680. * @return {Vector3} A reference to this vector.
  6681. */
  6682. max( v ) {
  6683. this.x = Math.max( this.x, v.x );
  6684. this.y = Math.max( this.y, v.y );
  6685. this.z = Math.max( this.z, v.z );
  6686. return this;
  6687. }
  6688. /**
  6689. * If this vector's x, y or z value is greater than the max vector's x, y or z
  6690. * value, it is replaced by the corresponding value.
  6691. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  6692. * it is replaced by the corresponding value.
  6693. *
  6694. * @param {Vector3} min - The minimum x, y and z values.
  6695. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  6696. * @return {Vector3} A reference to this vector.
  6697. */
  6698. clamp( min, max ) {
  6699. // assumes min < max, componentwise
  6700. this.x = clamp( this.x, min.x, max.x );
  6701. this.y = clamp( this.y, min.y, max.y );
  6702. this.z = clamp( this.z, min.z, max.z );
  6703. return this;
  6704. }
  6705. /**
  6706. * If this vector's x, y or z values are greater than the max value, they are
  6707. * replaced by the max value.
  6708. * If this vector's x, y or z values are less than the min value, they are
  6709. * replaced by the min value.
  6710. *
  6711. * @param {number} minVal - The minimum value the components will be clamped to.
  6712. * @param {number} maxVal - The maximum value the components will be clamped to.
  6713. * @return {Vector3} A reference to this vector.
  6714. */
  6715. clampScalar( minVal, maxVal ) {
  6716. this.x = clamp( this.x, minVal, maxVal );
  6717. this.y = clamp( this.y, minVal, maxVal );
  6718. this.z = clamp( this.z, minVal, maxVal );
  6719. return this;
  6720. }
  6721. /**
  6722. * If this vector's length is greater than the max value, it is replaced by
  6723. * the max value.
  6724. * If this vector's length is less than the min value, it is replaced by the
  6725. * min value.
  6726. *
  6727. * @param {number} min - The minimum value the vector length will be clamped to.
  6728. * @param {number} max - The maximum value the vector length will be clamped to.
  6729. * @return {Vector3} A reference to this vector.
  6730. */
  6731. clampLength( min, max ) {
  6732. const length = this.length();
  6733. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6734. }
  6735. /**
  6736. * The components of this vector are rounded down to the nearest integer value.
  6737. *
  6738. * @return {Vector3} A reference to this vector.
  6739. */
  6740. floor() {
  6741. this.x = Math.floor( this.x );
  6742. this.y = Math.floor( this.y );
  6743. this.z = Math.floor( this.z );
  6744. return this;
  6745. }
  6746. /**
  6747. * The components of this vector are rounded up to the nearest integer value.
  6748. *
  6749. * @return {Vector3} A reference to this vector.
  6750. */
  6751. ceil() {
  6752. this.x = Math.ceil( this.x );
  6753. this.y = Math.ceil( this.y );
  6754. this.z = Math.ceil( this.z );
  6755. return this;
  6756. }
  6757. /**
  6758. * The components of this vector are rounded to the nearest integer value
  6759. *
  6760. * @return {Vector3} A reference to this vector.
  6761. */
  6762. round() {
  6763. this.x = Math.round( this.x );
  6764. this.y = Math.round( this.y );
  6765. this.z = Math.round( this.z );
  6766. return this;
  6767. }
  6768. /**
  6769. * The components of this vector are rounded towards zero (up if negative,
  6770. * down if positive) to an integer value.
  6771. *
  6772. * @return {Vector3} A reference to this vector.
  6773. */
  6774. roundToZero() {
  6775. this.x = Math.trunc( this.x );
  6776. this.y = Math.trunc( this.y );
  6777. this.z = Math.trunc( this.z );
  6778. return this;
  6779. }
  6780. /**
  6781. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  6782. *
  6783. * @return {Vector3} A reference to this vector.
  6784. */
  6785. negate() {
  6786. this.x = - this.x;
  6787. this.y = - this.y;
  6788. this.z = - this.z;
  6789. return this;
  6790. }
  6791. /**
  6792. * Calculates the dot product of the given vector with this instance.
  6793. *
  6794. * @param {Vector3} v - The vector to compute the dot product with.
  6795. * @return {number} The result of the dot product.
  6796. */
  6797. dot( v ) {
  6798. return this.x * v.x + this.y * v.y + this.z * v.z;
  6799. }
  6800. // TODO lengthSquared?
  6801. /**
  6802. * Computes the square of the Euclidean length (straight-line length) from
  6803. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  6804. * compare the length squared instead as it is slightly more efficient to calculate.
  6805. *
  6806. * @return {number} The square length of this vector.
  6807. */
  6808. lengthSq() {
  6809. return this.x * this.x + this.y * this.y + this.z * this.z;
  6810. }
  6811. /**
  6812. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  6813. *
  6814. * @return {number} The length of this vector.
  6815. */
  6816. length() {
  6817. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  6818. }
  6819. /**
  6820. * Computes the Manhattan length of this vector.
  6821. *
  6822. * @return {number} The length of this vector.
  6823. */
  6824. manhattanLength() {
  6825. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  6826. }
  6827. /**
  6828. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6829. * with the same direction as this one, but with a vector length of `1`.
  6830. *
  6831. * @return {Vector3} A reference to this vector.
  6832. */
  6833. normalize() {
  6834. return this.divideScalar( this.length() || 1 );
  6835. }
  6836. /**
  6837. * Sets this vector to a vector with the same direction as this one, but
  6838. * with the specified length.
  6839. *
  6840. * @param {number} length - The new length of this vector.
  6841. * @return {Vector3} A reference to this vector.
  6842. */
  6843. setLength( length ) {
  6844. return this.normalize().multiplyScalar( length );
  6845. }
  6846. /**
  6847. * Linearly interpolates between the given vector and this instance, where
  6848. * alpha is the percent distance along the line - alpha = 0 will be this
  6849. * vector, and alpha = 1 will be the given one.
  6850. *
  6851. * @param {Vector3} v - The vector to interpolate towards.
  6852. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6853. * @return {Vector3} A reference to this vector.
  6854. */
  6855. lerp( v, alpha ) {
  6856. this.x += ( v.x - this.x ) * alpha;
  6857. this.y += ( v.y - this.y ) * alpha;
  6858. this.z += ( v.z - this.z ) * alpha;
  6859. return this;
  6860. }
  6861. /**
  6862. * Linearly interpolates between the given vectors, where alpha is the percent
  6863. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6864. * be the second one. The result is stored in this instance.
  6865. *
  6866. * @param {Vector3} v1 - The first vector.
  6867. * @param {Vector3} v2 - The second vector.
  6868. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6869. * @return {Vector3} A reference to this vector.
  6870. */
  6871. lerpVectors( v1, v2, alpha ) {
  6872. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6873. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6874. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6875. return this;
  6876. }
  6877. /**
  6878. * Calculates the cross product of the given vector with this instance.
  6879. *
  6880. * @param {Vector3} v - The vector to compute the cross product with.
  6881. * @return {Vector3} The result of the cross product.
  6882. */
  6883. cross( v ) {
  6884. return this.crossVectors( this, v );
  6885. }
  6886. /**
  6887. * Calculates the cross product of the given vectors and stores the result
  6888. * in this instance.
  6889. *
  6890. * @param {Vector3} a - The first vector.
  6891. * @param {Vector3} b - The second vector.
  6892. * @return {Vector3} A reference to this vector.
  6893. */
  6894. crossVectors( a, b ) {
  6895. const ax = a.x, ay = a.y, az = a.z;
  6896. const bx = b.x, by = b.y, bz = b.z;
  6897. this.x = ay * bz - az * by;
  6898. this.y = az * bx - ax * bz;
  6899. this.z = ax * by - ay * bx;
  6900. return this;
  6901. }
  6902. /**
  6903. * Projects this vector onto the given one.
  6904. *
  6905. * @param {Vector3} v - The vector to project to.
  6906. * @return {Vector3} A reference to this vector.
  6907. */
  6908. projectOnVector( v ) {
  6909. const denominator = v.lengthSq();
  6910. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  6911. const scalar = v.dot( this ) / denominator;
  6912. return this.copy( v ).multiplyScalar( scalar );
  6913. }
  6914. /**
  6915. * Projects this vector onto a plane by subtracting this
  6916. * vector projected onto the plane's normal from this vector.
  6917. *
  6918. * @param {Vector3} planeNormal - The plane normal.
  6919. * @return {Vector3} A reference to this vector.
  6920. */
  6921. projectOnPlane( planeNormal ) {
  6922. _vector$c.copy( this ).projectOnVector( planeNormal );
  6923. return this.sub( _vector$c );
  6924. }
  6925. /**
  6926. * Reflects this vector off a plane orthogonal to the given normal vector.
  6927. *
  6928. * @param {Vector3} normal - The (normalized) normal vector.
  6929. * @return {Vector3} A reference to this vector.
  6930. */
  6931. reflect( normal ) {
  6932. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  6933. }
  6934. /**
  6935. * Returns the angle between the given vector and this instance in radians.
  6936. *
  6937. * @param {Vector3} v - The vector to compute the angle with.
  6938. * @return {number} The angle in radians.
  6939. */
  6940. angleTo( v ) {
  6941. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  6942. if ( denominator === 0 ) return Math.PI / 2;
  6943. const theta = this.dot( v ) / denominator;
  6944. // clamp, to handle numerical problems
  6945. return Math.acos( clamp( theta, -1, 1 ) );
  6946. }
  6947. /**
  6948. * Computes the distance from the given vector to this instance.
  6949. *
  6950. * @param {Vector3} v - The vector to compute the distance to.
  6951. * @return {number} The distance.
  6952. */
  6953. distanceTo( v ) {
  6954. return Math.sqrt( this.distanceToSquared( v ) );
  6955. }
  6956. /**
  6957. * Computes the squared distance from the given vector to this instance.
  6958. * If you are just comparing the distance with another distance, you should compare
  6959. * the distance squared instead as it is slightly more efficient to calculate.
  6960. *
  6961. * @param {Vector3} v - The vector to compute the squared distance to.
  6962. * @return {number} The squared distance.
  6963. */
  6964. distanceToSquared( v ) {
  6965. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  6966. return dx * dx + dy * dy + dz * dz;
  6967. }
  6968. /**
  6969. * Computes the Manhattan distance from the given vector to this instance.
  6970. *
  6971. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  6972. * @return {number} The Manhattan distance.
  6973. */
  6974. manhattanDistanceTo( v ) {
  6975. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  6976. }
  6977. /**
  6978. * Sets the vector components from the given spherical coordinates.
  6979. *
  6980. * @param {Spherical} s - The spherical coordinates.
  6981. * @return {Vector3} A reference to this vector.
  6982. */
  6983. setFromSpherical( s ) {
  6984. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  6985. }
  6986. /**
  6987. * Sets the vector components from the given spherical coordinates.
  6988. *
  6989. * @param {number} radius - The radius.
  6990. * @param {number} phi - The phi angle in radians.
  6991. * @param {number} theta - The theta angle in radians.
  6992. * @return {Vector3} A reference to this vector.
  6993. */
  6994. setFromSphericalCoords( radius, phi, theta ) {
  6995. const sinPhiRadius = Math.sin( phi ) * radius;
  6996. this.x = sinPhiRadius * Math.sin( theta );
  6997. this.y = Math.cos( phi ) * radius;
  6998. this.z = sinPhiRadius * Math.cos( theta );
  6999. return this;
  7000. }
  7001. /**
  7002. * Sets the vector components from the given cylindrical coordinates.
  7003. *
  7004. * @param {Cylindrical} c - The cylindrical coordinates.
  7005. * @return {Vector3} A reference to this vector.
  7006. */
  7007. setFromCylindrical( c ) {
  7008. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  7009. }
  7010. /**
  7011. * Sets the vector components from the given cylindrical coordinates.
  7012. *
  7013. * @param {number} radius - The radius.
  7014. * @param {number} theta - The theta angle in radians.
  7015. * @param {number} y - The y value.
  7016. * @return {Vector3} A reference to this vector.
  7017. */
  7018. setFromCylindricalCoords( radius, theta, y ) {
  7019. this.x = radius * Math.sin( theta );
  7020. this.y = y;
  7021. this.z = radius * Math.cos( theta );
  7022. return this;
  7023. }
  7024. /**
  7025. * Sets the vector components to the position elements of the
  7026. * given transformation matrix.
  7027. *
  7028. * @param {Matrix4} m - The 4x4 matrix.
  7029. * @return {Vector3} A reference to this vector.
  7030. */
  7031. setFromMatrixPosition( m ) {
  7032. const e = m.elements;
  7033. this.x = e[ 12 ];
  7034. this.y = e[ 13 ];
  7035. this.z = e[ 14 ];
  7036. return this;
  7037. }
  7038. /**
  7039. * Sets the vector components to the scale elements of the
  7040. * given transformation matrix.
  7041. *
  7042. * @param {Matrix4} m - The 4x4 matrix.
  7043. * @return {Vector3} A reference to this vector.
  7044. */
  7045. setFromMatrixScale( m ) {
  7046. const sx = this.setFromMatrixColumn( m, 0 ).length();
  7047. const sy = this.setFromMatrixColumn( m, 1 ).length();
  7048. const sz = this.setFromMatrixColumn( m, 2 ).length();
  7049. this.x = sx;
  7050. this.y = sy;
  7051. this.z = sz;
  7052. return this;
  7053. }
  7054. /**
  7055. * Sets the vector components from the specified matrix column.
  7056. *
  7057. * @param {Matrix4} m - The 4x4 matrix.
  7058. * @param {number} index - The column index.
  7059. * @return {Vector3} A reference to this vector.
  7060. */
  7061. setFromMatrixColumn( m, index ) {
  7062. return this.fromArray( m.elements, index * 4 );
  7063. }
  7064. /**
  7065. * Sets the vector components from the specified matrix column.
  7066. *
  7067. * @param {Matrix3} m - The 3x3 matrix.
  7068. * @param {number} index - The column index.
  7069. * @return {Vector3} A reference to this vector.
  7070. */
  7071. setFromMatrix3Column( m, index ) {
  7072. return this.fromArray( m.elements, index * 3 );
  7073. }
  7074. /**
  7075. * Sets the vector components from the given Euler angles.
  7076. *
  7077. * @param {Euler} e - The Euler angles to set.
  7078. * @return {Vector3} A reference to this vector.
  7079. */
  7080. setFromEuler( e ) {
  7081. this.x = e._x;
  7082. this.y = e._y;
  7083. this.z = e._z;
  7084. return this;
  7085. }
  7086. /**
  7087. * Sets the vector components from the RGB components of the
  7088. * given color.
  7089. *
  7090. * @param {Color} c - The color to set.
  7091. * @return {Vector3} A reference to this vector.
  7092. */
  7093. setFromColor( c ) {
  7094. this.x = c.r;
  7095. this.y = c.g;
  7096. this.z = c.b;
  7097. return this;
  7098. }
  7099. /**
  7100. * Returns `true` if this vector is equal with the given one.
  7101. *
  7102. * @param {Vector3} v - The vector to test for equality.
  7103. * @return {boolean} Whether this vector is equal with the given one.
  7104. */
  7105. equals( v ) {
  7106. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  7107. }
  7108. /**
  7109. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  7110. * and z value to be `array[ offset + 2 ]`.
  7111. *
  7112. * @param {Array<number>} array - An array holding the vector component values.
  7113. * @param {number} [offset=0] - The offset into the array.
  7114. * @return {Vector3} A reference to this vector.
  7115. */
  7116. fromArray( array, offset = 0 ) {
  7117. this.x = array[ offset ];
  7118. this.y = array[ offset + 1 ];
  7119. this.z = array[ offset + 2 ];
  7120. return this;
  7121. }
  7122. /**
  7123. * Writes the components of this vector to the given array. If no array is provided,
  7124. * the method returns a new instance.
  7125. *
  7126. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  7127. * @param {number} [offset=0] - Index of the first element in the array.
  7128. * @return {Array<number>} The vector components.
  7129. */
  7130. toArray( array = [], offset = 0 ) {
  7131. array[ offset ] = this.x;
  7132. array[ offset + 1 ] = this.y;
  7133. array[ offset + 2 ] = this.z;
  7134. return array;
  7135. }
  7136. /**
  7137. * Sets the components of this vector from the given buffer attribute.
  7138. *
  7139. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  7140. * @param {number} index - The index into the attribute.
  7141. * @return {Vector3} A reference to this vector.
  7142. */
  7143. fromBufferAttribute( attribute, index ) {
  7144. this.x = attribute.getX( index );
  7145. this.y = attribute.getY( index );
  7146. this.z = attribute.getZ( index );
  7147. return this;
  7148. }
  7149. /**
  7150. * Sets each component of this vector to a pseudo-random value between `0` and
  7151. * `1`, excluding `1`.
  7152. *
  7153. * @return {Vector3} A reference to this vector.
  7154. */
  7155. random() {
  7156. this.x = Math.random();
  7157. this.y = Math.random();
  7158. this.z = Math.random();
  7159. return this;
  7160. }
  7161. /**
  7162. * Sets this vector to a uniformly random point on a unit sphere.
  7163. *
  7164. * @return {Vector3} A reference to this vector.
  7165. */
  7166. randomDirection() {
  7167. // https://mathworld.wolfram.com/SpherePointPicking.html
  7168. const theta = Math.random() * Math.PI * 2;
  7169. const u = Math.random() * 2 - 1;
  7170. const c = Math.sqrt( 1 - u * u );
  7171. this.x = c * Math.cos( theta );
  7172. this.y = u;
  7173. this.z = c * Math.sin( theta );
  7174. return this;
  7175. }
  7176. *[ Symbol.iterator ]() {
  7177. yield this.x;
  7178. yield this.y;
  7179. yield this.z;
  7180. }
  7181. }
  7182. const _vector$c = /*@__PURE__*/ new Vector3();
  7183. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  7184. /**
  7185. * Represents an axis-aligned bounding box (AABB) in 3D space.
  7186. */
  7187. class Box3 {
  7188. /**
  7189. * Constructs a new bounding box.
  7190. *
  7191. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  7192. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  7193. */
  7194. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  7195. /**
  7196. * This flag can be used for type testing.
  7197. *
  7198. * @type {boolean}
  7199. * @readonly
  7200. * @default true
  7201. */
  7202. this.isBox3 = true;
  7203. /**
  7204. * The lower boundary of the box.
  7205. *
  7206. * @type {Vector3}
  7207. */
  7208. this.min = min;
  7209. /**
  7210. * The upper boundary of the box.
  7211. *
  7212. * @type {Vector3}
  7213. */
  7214. this.max = max;
  7215. }
  7216. /**
  7217. * Sets the lower and upper boundaries of this box.
  7218. * Please note that this method only copies the values from the given objects.
  7219. *
  7220. * @param {Vector3} min - The lower boundary of the box.
  7221. * @param {Vector3} max - The upper boundary of the box.
  7222. * @return {Box3} A reference to this bounding box.
  7223. */
  7224. set( min, max ) {
  7225. this.min.copy( min );
  7226. this.max.copy( max );
  7227. return this;
  7228. }
  7229. /**
  7230. * Sets the upper and lower bounds of this box so it encloses the position data
  7231. * in the given array.
  7232. *
  7233. * @param {Array<number>} array - An array holding 3D position data.
  7234. * @return {Box3} A reference to this bounding box.
  7235. */
  7236. setFromArray( array ) {
  7237. this.makeEmpty();
  7238. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  7239. this.expandByPoint( _vector$b.fromArray( array, i ) );
  7240. }
  7241. return this;
  7242. }
  7243. /**
  7244. * Sets the upper and lower bounds of this box so it encloses the position data
  7245. * in the given buffer attribute.
  7246. *
  7247. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  7248. * @return {Box3} A reference to this bounding box.
  7249. */
  7250. setFromBufferAttribute( attribute ) {
  7251. this.makeEmpty();
  7252. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  7253. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  7254. }
  7255. return this;
  7256. }
  7257. /**
  7258. * Sets the upper and lower bounds of this box so it encloses the position data
  7259. * in the given array.
  7260. *
  7261. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  7262. * @return {Box3} A reference to this bounding box.
  7263. */
  7264. setFromPoints( points ) {
  7265. this.makeEmpty();
  7266. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7267. this.expandByPoint( points[ i ] );
  7268. }
  7269. return this;
  7270. }
  7271. /**
  7272. * Centers this box on the given center vector and sets this box's width, height and
  7273. * depth to the given size values.
  7274. *
  7275. * @param {Vector3} center - The center of the box.
  7276. * @param {Vector3} size - The x, y and z dimensions of the box.
  7277. * @return {Box3} A reference to this bounding box.
  7278. */
  7279. setFromCenterAndSize( center, size ) {
  7280. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  7281. this.min.copy( center ).sub( halfSize );
  7282. this.max.copy( center ).add( halfSize );
  7283. return this;
  7284. }
  7285. /**
  7286. * Computes the world-axis-aligned bounding box for the given 3D object
  7287. * (including its children), accounting for the object's, and children's,
  7288. * world transforms. The function may result in a larger box than strictly necessary.
  7289. *
  7290. * @param {Object3D} object - The 3D object to compute the bounding box for.
  7291. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  7292. * world-axis-aligned bounding box at the expense of more computation.
  7293. * @return {Box3} A reference to this bounding box.
  7294. */
  7295. setFromObject( object, precise = false ) {
  7296. this.makeEmpty();
  7297. return this.expandByObject( object, precise );
  7298. }
  7299. /**
  7300. * Returns a new box with copied values from this instance.
  7301. *
  7302. * @return {Box3} A clone of this instance.
  7303. */
  7304. clone() {
  7305. return new this.constructor().copy( this );
  7306. }
  7307. /**
  7308. * Copies the values of the given box to this instance.
  7309. *
  7310. * @param {Box3} box - The box to copy.
  7311. * @return {Box3} A reference to this bounding box.
  7312. */
  7313. copy( box ) {
  7314. this.min.copy( box.min );
  7315. this.max.copy( box.max );
  7316. return this;
  7317. }
  7318. /**
  7319. * Makes this box empty which means in encloses a zero space in 3D.
  7320. *
  7321. * @return {Box3} A reference to this bounding box.
  7322. */
  7323. makeEmpty() {
  7324. this.min.x = this.min.y = this.min.z = + Infinity;
  7325. this.max.x = this.max.y = this.max.z = - Infinity;
  7326. return this;
  7327. }
  7328. /**
  7329. * Returns true if this box includes zero points within its bounds.
  7330. * Note that a box with equal lower and upper bounds still includes one
  7331. * point, the one both bounds share.
  7332. *
  7333. * @return {boolean} Whether this box is empty or not.
  7334. */
  7335. isEmpty() {
  7336. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  7337. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  7338. }
  7339. /**
  7340. * Returns the center point of this box.
  7341. *
  7342. * @param {Vector3} target - The target vector that is used to store the method's result.
  7343. * @return {Vector3} The center point.
  7344. */
  7345. getCenter( target ) {
  7346. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  7347. }
  7348. /**
  7349. * Returns the dimensions of this box.
  7350. *
  7351. * @param {Vector3} target - The target vector that is used to store the method's result.
  7352. * @return {Vector3} The size.
  7353. */
  7354. getSize( target ) {
  7355. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  7356. }
  7357. /**
  7358. * Expands the boundaries of this box to include the given point.
  7359. *
  7360. * @param {Vector3} point - The point that should be included by the bounding box.
  7361. * @return {Box3} A reference to this bounding box.
  7362. */
  7363. expandByPoint( point ) {
  7364. this.min.min( point );
  7365. this.max.max( point );
  7366. return this;
  7367. }
  7368. /**
  7369. * Expands this box equilaterally by the given vector. The width of this
  7370. * box will be expanded by the x component of the vector in both
  7371. * directions. The height of this box will be expanded by the y component of
  7372. * the vector in both directions. The depth of this box will be
  7373. * expanded by the z component of the vector in both directions.
  7374. *
  7375. * @param {Vector3} vector - The vector that should expand the bounding box.
  7376. * @return {Box3} A reference to this bounding box.
  7377. */
  7378. expandByVector( vector ) {
  7379. this.min.sub( vector );
  7380. this.max.add( vector );
  7381. return this;
  7382. }
  7383. /**
  7384. * Expands each dimension of the box by the given scalar. If negative, the
  7385. * dimensions of the box will be contracted.
  7386. *
  7387. * @param {number} scalar - The scalar value that should expand the bounding box.
  7388. * @return {Box3} A reference to this bounding box.
  7389. */
  7390. expandByScalar( scalar ) {
  7391. this.min.addScalar( - scalar );
  7392. this.max.addScalar( scalar );
  7393. return this;
  7394. }
  7395. /**
  7396. * Expands the boundaries of this box to include the given 3D object and
  7397. * its children, accounting for the object's, and children's, world
  7398. * transforms. The function may result in a larger box than strictly
  7399. * necessary (unless the precise parameter is set to true).
  7400. *
  7401. * @param {Object3D} object - The 3D object that should expand the bounding box.
  7402. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  7403. * as little as necessary at the expense of more computation.
  7404. * @return {Box3} A reference to this bounding box.
  7405. */
  7406. expandByObject( object, precise = false ) {
  7407. // Computes the world-axis-aligned bounding box of an object (including its children),
  7408. // accounting for both the object's, and children's, world transforms
  7409. object.updateWorldMatrix( false, false );
  7410. const geometry = object.geometry;
  7411. if ( geometry !== undefined ) {
  7412. const positionAttribute = geometry.getAttribute( 'position' );
  7413. // precise AABB computation based on vertex data requires at least a position attribute.
  7414. // instancing isn't supported so far and uses the normal (conservative) code path.
  7415. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  7416. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  7417. if ( object.isMesh === true ) {
  7418. object.getVertexPosition( i, _vector$b );
  7419. } else {
  7420. _vector$b.fromBufferAttribute( positionAttribute, i );
  7421. }
  7422. _vector$b.applyMatrix4( object.matrixWorld );
  7423. this.expandByPoint( _vector$b );
  7424. }
  7425. } else {
  7426. if ( object.boundingBox !== undefined ) {
  7427. // object-level bounding box
  7428. if ( object.boundingBox === null ) {
  7429. object.computeBoundingBox();
  7430. }
  7431. _box$4.copy( object.boundingBox );
  7432. } else {
  7433. // geometry-level bounding box
  7434. if ( geometry.boundingBox === null ) {
  7435. geometry.computeBoundingBox();
  7436. }
  7437. _box$4.copy( geometry.boundingBox );
  7438. }
  7439. _box$4.applyMatrix4( object.matrixWorld );
  7440. this.union( _box$4 );
  7441. }
  7442. }
  7443. const children = object.children;
  7444. for ( let i = 0, l = children.length; i < l; i ++ ) {
  7445. this.expandByObject( children[ i ], precise );
  7446. }
  7447. return this;
  7448. }
  7449. /**
  7450. * Returns `true` if the given point lies within or on the boundaries of this box.
  7451. *
  7452. * @param {Vector3} point - The point to test.
  7453. * @return {boolean} Whether the bounding box contains the given point or not.
  7454. */
  7455. containsPoint( point ) {
  7456. return point.x >= this.min.x && point.x <= this.max.x &&
  7457. point.y >= this.min.y && point.y <= this.max.y &&
  7458. point.z >= this.min.z && point.z <= this.max.z;
  7459. }
  7460. /**
  7461. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  7462. * If this box and the given one are identical, this function also returns `true`.
  7463. *
  7464. * @param {Box3} box - The bounding box to test.
  7465. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  7466. */
  7467. containsBox( box ) {
  7468. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  7469. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  7470. this.min.z <= box.min.z && box.max.z <= this.max.z;
  7471. }
  7472. /**
  7473. * Returns a point as a proportion of this box's width, height and depth.
  7474. *
  7475. * @param {Vector3} point - A point in 3D space.
  7476. * @param {Vector3} target - The target vector that is used to store the method's result.
  7477. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  7478. */
  7479. getParameter( point, target ) {
  7480. // This can potentially have a divide by zero if the box
  7481. // has a size dimension of 0.
  7482. return target.set(
  7483. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7484. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  7485. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  7486. );
  7487. }
  7488. /**
  7489. * Returns `true` if the given bounding box intersects with this bounding box.
  7490. *
  7491. * @param {Box3} box - The bounding box to test.
  7492. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  7493. */
  7494. intersectsBox( box ) {
  7495. // using 6 splitting planes to rule out intersections.
  7496. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  7497. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  7498. box.max.z >= this.min.z && box.min.z <= this.max.z;
  7499. }
  7500. /**
  7501. * Returns `true` if the given bounding sphere intersects with this bounding box.
  7502. *
  7503. * @param {Sphere} sphere - The bounding sphere to test.
  7504. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  7505. */
  7506. intersectsSphere( sphere ) {
  7507. // Find the point on the AABB closest to the sphere center.
  7508. this.clampPoint( sphere.center, _vector$b );
  7509. // If that point is inside the sphere, the AABB and sphere intersect.
  7510. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  7511. }
  7512. /**
  7513. * Returns `true` if the given plane intersects with this bounding box.
  7514. *
  7515. * @param {Plane} plane - The plane to test.
  7516. * @return {boolean} Whether the given plane intersects with this bounding box.
  7517. */
  7518. intersectsPlane( plane ) {
  7519. // We compute the minimum and maximum dot product values. If those values
  7520. // are on the same side (back or front) of the plane, then there is no intersection.
  7521. let min, max;
  7522. if ( plane.normal.x > 0 ) {
  7523. min = plane.normal.x * this.min.x;
  7524. max = plane.normal.x * this.max.x;
  7525. } else {
  7526. min = plane.normal.x * this.max.x;
  7527. max = plane.normal.x * this.min.x;
  7528. }
  7529. if ( plane.normal.y > 0 ) {
  7530. min += plane.normal.y * this.min.y;
  7531. max += plane.normal.y * this.max.y;
  7532. } else {
  7533. min += plane.normal.y * this.max.y;
  7534. max += plane.normal.y * this.min.y;
  7535. }
  7536. if ( plane.normal.z > 0 ) {
  7537. min += plane.normal.z * this.min.z;
  7538. max += plane.normal.z * this.max.z;
  7539. } else {
  7540. min += plane.normal.z * this.max.z;
  7541. max += plane.normal.z * this.min.z;
  7542. }
  7543. return ( min <= - plane.constant && max >= - plane.constant );
  7544. }
  7545. /**
  7546. * Returns `true` if the given triangle intersects with this bounding box.
  7547. *
  7548. * @param {Triangle} triangle - The triangle to test.
  7549. * @return {boolean} Whether the given triangle intersects with this bounding box.
  7550. */
  7551. intersectsTriangle( triangle ) {
  7552. if ( this.isEmpty() ) {
  7553. return false;
  7554. }
  7555. // compute box center and extents
  7556. this.getCenter( _center );
  7557. _extents.subVectors( this.max, _center );
  7558. // translate triangle to aabb origin
  7559. _v0$3.subVectors( triangle.a, _center );
  7560. _v1$7.subVectors( triangle.b, _center );
  7561. _v2$4.subVectors( triangle.c, _center );
  7562. // compute edge vectors for triangle
  7563. _f0.subVectors( _v1$7, _v0$3 );
  7564. _f1.subVectors( _v2$4, _v1$7 );
  7565. _f2.subVectors( _v0$3, _v2$4 );
  7566. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7567. // 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
  7568. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7569. let axes = [
  7570. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  7571. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  7572. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  7573. ];
  7574. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  7575. return false;
  7576. }
  7577. // test 3 face normals from the aabb
  7578. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7579. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  7580. return false;
  7581. }
  7582. // finally testing the face normal of the triangle
  7583. // use already existing triangle edge vectors here
  7584. _triangleNormal.crossVectors( _f0, _f1 );
  7585. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  7586. return satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents );
  7587. }
  7588. /**
  7589. * Clamps the given point within the bounds of this box.
  7590. *
  7591. * @param {Vector3} point - The point to clamp.
  7592. * @param {Vector3} target - The target vector that is used to store the method's result.
  7593. * @return {Vector3} The clamped point.
  7594. */
  7595. clampPoint( point, target ) {
  7596. return target.copy( point ).clamp( this.min, this.max );
  7597. }
  7598. /**
  7599. * Returns the euclidean distance from any edge of this box to the specified point. If
  7600. * the given point lies inside of this box, the distance will be `0`.
  7601. *
  7602. * @param {Vector3} point - The point to compute the distance to.
  7603. * @return {number} The euclidean distance.
  7604. */
  7605. distanceToPoint( point ) {
  7606. return this.clampPoint( point, _vector$b ).distanceTo( point );
  7607. }
  7608. /**
  7609. * Returns a bounding sphere that encloses this bounding box.
  7610. *
  7611. * @param {Sphere} target - The target sphere that is used to store the method's result.
  7612. * @return {Sphere} The bounding sphere that encloses this bounding box.
  7613. */
  7614. getBoundingSphere( target ) {
  7615. if ( this.isEmpty() ) {
  7616. target.makeEmpty();
  7617. } else {
  7618. this.getCenter( target.center );
  7619. target.radius = this.getSize( _vector$b ).length() * 0.5;
  7620. }
  7621. return target;
  7622. }
  7623. /**
  7624. * Computes the intersection of this bounding box and the given one, setting the upper
  7625. * bound of this box to the lesser of the two boxes' upper bounds and the
  7626. * lower bound of this box to the greater of the two boxes' lower bounds. If
  7627. * there's no overlap, makes this box empty.
  7628. *
  7629. * @param {Box3} box - The bounding box to intersect with.
  7630. * @return {Box3} A reference to this bounding box.
  7631. */
  7632. intersect( box ) {
  7633. this.min.max( box.min );
  7634. this.max.min( box.max );
  7635. // 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.
  7636. if ( this.isEmpty() ) this.makeEmpty();
  7637. return this;
  7638. }
  7639. /**
  7640. * Computes the union of this box and another and the given one, setting the upper
  7641. * bound of this box to the greater of the two boxes' upper bounds and the
  7642. * lower bound of this box to the lesser of the two boxes' lower bounds.
  7643. *
  7644. * @param {Box3} box - The bounding box that will be unioned with this instance.
  7645. * @return {Box3} A reference to this bounding box.
  7646. */
  7647. union( box ) {
  7648. this.min.min( box.min );
  7649. this.max.max( box.max );
  7650. return this;
  7651. }
  7652. /**
  7653. * Transforms this bounding box by the given 4x4 transformation matrix.
  7654. *
  7655. * @param {Matrix4} matrix - The transformation matrix.
  7656. * @return {Box3} A reference to this bounding box.
  7657. */
  7658. applyMatrix4( matrix ) {
  7659. // transform of empty box is an empty box.
  7660. if ( this.isEmpty() ) return this;
  7661. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  7662. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  7663. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  7664. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  7665. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  7666. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  7667. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  7668. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  7669. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  7670. this.setFromPoints( _points );
  7671. return this;
  7672. }
  7673. /**
  7674. * Adds the given offset to both the upper and lower bounds of this bounding box,
  7675. * effectively moving it in 3D space.
  7676. *
  7677. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  7678. * @return {Box3} A reference to this bounding box.
  7679. */
  7680. translate( offset ) {
  7681. this.min.add( offset );
  7682. this.max.add( offset );
  7683. return this;
  7684. }
  7685. /**
  7686. * Returns `true` if this bounding box is equal with the given one.
  7687. *
  7688. * @param {Box3} box - The box to test for equality.
  7689. * @return {boolean} Whether this bounding box is equal with the given one.
  7690. */
  7691. equals( box ) {
  7692. return box.min.equals( this.min ) && box.max.equals( this.max );
  7693. }
  7694. }
  7695. const _points = [
  7696. /*@__PURE__*/ new Vector3(),
  7697. /*@__PURE__*/ new Vector3(),
  7698. /*@__PURE__*/ new Vector3(),
  7699. /*@__PURE__*/ new Vector3(),
  7700. /*@__PURE__*/ new Vector3(),
  7701. /*@__PURE__*/ new Vector3(),
  7702. /*@__PURE__*/ new Vector3(),
  7703. /*@__PURE__*/ new Vector3()
  7704. ];
  7705. const _vector$b = /*@__PURE__*/ new Vector3();
  7706. const _box$4 = /*@__PURE__*/ new Box3();
  7707. // triangle centered vertices
  7708. const _v0$3 = /*@__PURE__*/ new Vector3();
  7709. const _v1$7 = /*@__PURE__*/ new Vector3();
  7710. const _v2$4 = /*@__PURE__*/ new Vector3();
  7711. // triangle edge vectors
  7712. const _f0 = /*@__PURE__*/ new Vector3();
  7713. const _f1 = /*@__PURE__*/ new Vector3();
  7714. const _f2 = /*@__PURE__*/ new Vector3();
  7715. const _center = /*@__PURE__*/ new Vector3();
  7716. const _extents = /*@__PURE__*/ new Vector3();
  7717. const _triangleNormal = /*@__PURE__*/ new Vector3();
  7718. const _testAxis = /*@__PURE__*/ new Vector3();
  7719. function satForAxes( axes, v0, v1, v2, extents ) {
  7720. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  7721. _testAxis.fromArray( axes, i );
  7722. // project the aabb onto the separating axis
  7723. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  7724. // project all 3 vertices of the triangle onto the separating axis
  7725. const p0 = v0.dot( _testAxis );
  7726. const p1 = v1.dot( _testAxis );
  7727. const p2 = v2.dot( _testAxis );
  7728. // actual test, basically see if either of the most extreme of the triangle points intersects r
  7729. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  7730. // points of the projected triangle are outside the projected half-length of the aabb
  7731. // the axis is separating and we can exit
  7732. return false;
  7733. }
  7734. }
  7735. return true;
  7736. }
  7737. const _box$3 = /*@__PURE__*/ new Box3();
  7738. const _v1$6 = /*@__PURE__*/ new Vector3();
  7739. const _v2$3 = /*@__PURE__*/ new Vector3();
  7740. /**
  7741. * An analytical 3D sphere defined by a center and radius. This class is mainly
  7742. * used as a Bounding Sphere for 3D objects.
  7743. */
  7744. class Sphere {
  7745. /**
  7746. * Constructs a new sphere.
  7747. *
  7748. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  7749. * @param {number} [radius=-1] - The radius of the sphere.
  7750. */
  7751. constructor( center = new Vector3(), radius = -1 ) {
  7752. /**
  7753. * This flag can be used for type testing.
  7754. *
  7755. * @type {boolean}
  7756. * @readonly
  7757. * @default true
  7758. */
  7759. this.isSphere = true;
  7760. /**
  7761. * The center of the sphere
  7762. *
  7763. * @type {Vector3}
  7764. */
  7765. this.center = center;
  7766. /**
  7767. * The radius of the sphere.
  7768. *
  7769. * @type {number}
  7770. */
  7771. this.radius = radius;
  7772. }
  7773. /**
  7774. * Sets the sphere's components by copying the given values.
  7775. *
  7776. * @param {Vector3} center - The center.
  7777. * @param {number} radius - The radius.
  7778. * @return {Sphere} A reference to this sphere.
  7779. */
  7780. set( center, radius ) {
  7781. this.center.copy( center );
  7782. this.radius = radius;
  7783. return this;
  7784. }
  7785. /**
  7786. * Computes the minimum bounding sphere for list of points.
  7787. * If the optional center point is given, it is used as the sphere's
  7788. * center. Otherwise, the center of the axis-aligned bounding box
  7789. * encompassing the points is calculated.
  7790. *
  7791. * @param {Array<Vector3>} points - A list of points in 3D space.
  7792. * @param {Vector3} [optionalCenter] - The center of the sphere.
  7793. * @return {Sphere} A reference to this sphere.
  7794. */
  7795. setFromPoints( points, optionalCenter ) {
  7796. const center = this.center;
  7797. if ( optionalCenter !== undefined ) {
  7798. center.copy( optionalCenter );
  7799. } else {
  7800. _box$3.setFromPoints( points ).getCenter( center );
  7801. }
  7802. let maxRadiusSq = 0;
  7803. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7804. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  7805. }
  7806. this.radius = Math.sqrt( maxRadiusSq );
  7807. return this;
  7808. }
  7809. /**
  7810. * Copies the values of the given sphere to this instance.
  7811. *
  7812. * @param {Sphere} sphere - The sphere to copy.
  7813. * @return {Sphere} A reference to this sphere.
  7814. */
  7815. copy( sphere ) {
  7816. this.center.copy( sphere.center );
  7817. this.radius = sphere.radius;
  7818. return this;
  7819. }
  7820. /**
  7821. * Returns `true` if the sphere is empty (the radius set to a negative number).
  7822. *
  7823. * Spheres with a radius of `0` contain only their center point and are not
  7824. * considered to be empty.
  7825. *
  7826. * @return {boolean} Whether this sphere is empty or not.
  7827. */
  7828. isEmpty() {
  7829. return ( this.radius < 0 );
  7830. }
  7831. /**
  7832. * Makes this sphere empty which means in encloses a zero space in 3D.
  7833. *
  7834. * @return {Sphere} A reference to this sphere.
  7835. */
  7836. makeEmpty() {
  7837. this.center.set( 0, 0, 0 );
  7838. this.radius = -1;
  7839. return this;
  7840. }
  7841. /**
  7842. * Returns `true` if this sphere contains the given point inclusive of
  7843. * the surface of the sphere.
  7844. *
  7845. * @param {Vector3} point - The point to check.
  7846. * @return {boolean} Whether this sphere contains the given point or not.
  7847. */
  7848. containsPoint( point ) {
  7849. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  7850. }
  7851. /**
  7852. * Returns the closest distance from the boundary of the sphere to the
  7853. * given point. If the sphere contains the point, the distance will
  7854. * be negative.
  7855. *
  7856. * @param {Vector3} point - The point to compute the distance to.
  7857. * @return {number} The distance to the point.
  7858. */
  7859. distanceToPoint( point ) {
  7860. return ( point.distanceTo( this.center ) - this.radius );
  7861. }
  7862. /**
  7863. * Returns `true` if this sphere intersects with the given one.
  7864. *
  7865. * @param {Sphere} sphere - The sphere to test.
  7866. * @return {boolean} Whether this sphere intersects with the given one or not.
  7867. */
  7868. intersectsSphere( sphere ) {
  7869. const radiusSum = this.radius + sphere.radius;
  7870. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  7871. }
  7872. /**
  7873. * Returns `true` if this sphere intersects with the given box.
  7874. *
  7875. * @param {Box3} box - The box to test.
  7876. * @return {boolean} Whether this sphere intersects with the given box or not.
  7877. */
  7878. intersectsBox( box ) {
  7879. return box.intersectsSphere( this );
  7880. }
  7881. /**
  7882. * Returns `true` if this sphere intersects with the given plane.
  7883. *
  7884. * @param {Plane} plane - The plane to test.
  7885. * @return {boolean} Whether this sphere intersects with the given plane or not.
  7886. */
  7887. intersectsPlane( plane ) {
  7888. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  7889. }
  7890. /**
  7891. * Clamps a point within the sphere. If the point is outside the sphere, it
  7892. * will clamp it to the closest point on the edge of the sphere. Points
  7893. * already inside the sphere will not be affected.
  7894. *
  7895. * @param {Vector3} point - The plane to clamp.
  7896. * @param {Vector3} target - The target vector that is used to store the method's result.
  7897. * @return {Vector3} The clamped point.
  7898. */
  7899. clampPoint( point, target ) {
  7900. const deltaLengthSq = this.center.distanceToSquared( point );
  7901. target.copy( point );
  7902. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  7903. target.sub( this.center ).normalize();
  7904. target.multiplyScalar( this.radius ).add( this.center );
  7905. }
  7906. return target;
  7907. }
  7908. /**
  7909. * Returns a bounding box that encloses this sphere.
  7910. *
  7911. * @param {Box3} target - The target box that is used to store the method's result.
  7912. * @return {Box3} The bounding box that encloses this sphere.
  7913. */
  7914. getBoundingBox( target ) {
  7915. if ( this.isEmpty() ) {
  7916. // Empty sphere produces empty bounding box
  7917. target.makeEmpty();
  7918. return target;
  7919. }
  7920. target.set( this.center, this.center );
  7921. target.expandByScalar( this.radius );
  7922. return target;
  7923. }
  7924. /**
  7925. * Transforms this sphere with the given 4x4 transformation matrix.
  7926. *
  7927. * @param {Matrix4} matrix - The transformation matrix.
  7928. * @return {Sphere} A reference to this sphere.
  7929. */
  7930. applyMatrix4( matrix ) {
  7931. this.center.applyMatrix4( matrix );
  7932. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  7933. return this;
  7934. }
  7935. /**
  7936. * Translates the sphere's center by the given offset.
  7937. *
  7938. * @param {Vector3} offset - The offset.
  7939. * @return {Sphere} A reference to this sphere.
  7940. */
  7941. translate( offset ) {
  7942. this.center.add( offset );
  7943. return this;
  7944. }
  7945. /**
  7946. * Expands the boundaries of this sphere to include the given point.
  7947. *
  7948. * @param {Vector3} point - The point to include.
  7949. * @return {Sphere} A reference to this sphere.
  7950. */
  7951. expandByPoint( point ) {
  7952. if ( this.isEmpty() ) {
  7953. this.center.copy( point );
  7954. this.radius = 0;
  7955. return this;
  7956. }
  7957. _v1$6.subVectors( point, this.center );
  7958. const lengthSq = _v1$6.lengthSq();
  7959. if ( lengthSq > ( this.radius * this.radius ) ) {
  7960. // calculate the minimal sphere
  7961. const length = Math.sqrt( lengthSq );
  7962. const delta = ( length - this.radius ) * 0.5;
  7963. this.center.addScaledVector( _v1$6, delta / length );
  7964. this.radius += delta;
  7965. }
  7966. return this;
  7967. }
  7968. /**
  7969. * Expands this sphere to enclose both the original sphere and the given sphere.
  7970. *
  7971. * @param {Sphere} sphere - The sphere to include.
  7972. * @return {Sphere} A reference to this sphere.
  7973. */
  7974. union( sphere ) {
  7975. if ( sphere.isEmpty() ) {
  7976. return this;
  7977. }
  7978. if ( this.isEmpty() ) {
  7979. this.copy( sphere );
  7980. return this;
  7981. }
  7982. if ( this.center.equals( sphere.center ) === true ) {
  7983. this.radius = Math.max( this.radius, sphere.radius );
  7984. } else {
  7985. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  7986. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  7987. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  7988. }
  7989. return this;
  7990. }
  7991. /**
  7992. * Returns `true` if this sphere is equal with the given one.
  7993. *
  7994. * @param {Sphere} sphere - The sphere to test for equality.
  7995. * @return {boolean} Whether this bounding sphere is equal with the given one.
  7996. */
  7997. equals( sphere ) {
  7998. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  7999. }
  8000. /**
  8001. * Returns a new sphere with copied values from this instance.
  8002. *
  8003. * @return {Sphere} A clone of this instance.
  8004. */
  8005. clone() {
  8006. return new this.constructor().copy( this );
  8007. }
  8008. }
  8009. const _vector$a = /*@__PURE__*/ new Vector3();
  8010. const _segCenter = /*@__PURE__*/ new Vector3();
  8011. const _segDir = /*@__PURE__*/ new Vector3();
  8012. const _diff = /*@__PURE__*/ new Vector3();
  8013. const _edge1 = /*@__PURE__*/ new Vector3();
  8014. const _edge2 = /*@__PURE__*/ new Vector3();
  8015. const _normal$1 = /*@__PURE__*/ new Vector3();
  8016. /**
  8017. * A ray that emits from an origin in a certain direction. The class is used by
  8018. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  8019. * mouse picking (working out what objects in the 3D space the mouse is over)
  8020. * amongst other things.
  8021. */
  8022. class Ray {
  8023. /**
  8024. * Constructs a new ray.
  8025. *
  8026. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  8027. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  8028. */
  8029. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  8030. /**
  8031. * The origin of the ray.
  8032. *
  8033. * @type {Vector3}
  8034. */
  8035. this.origin = origin;
  8036. /**
  8037. * The (normalized) direction of the ray.
  8038. *
  8039. * @type {Vector3}
  8040. */
  8041. this.direction = direction;
  8042. }
  8043. /**
  8044. * Sets the ray's components by copying the given values.
  8045. *
  8046. * @param {Vector3} origin - The origin.
  8047. * @param {Vector3} direction - The direction.
  8048. * @return {Ray} A reference to this ray.
  8049. */
  8050. set( origin, direction ) {
  8051. this.origin.copy( origin );
  8052. this.direction.copy( direction );
  8053. return this;
  8054. }
  8055. /**
  8056. * Copies the values of the given ray to this instance.
  8057. *
  8058. * @param {Ray} ray - The ray to copy.
  8059. * @return {Ray} A reference to this ray.
  8060. */
  8061. copy( ray ) {
  8062. this.origin.copy( ray.origin );
  8063. this.direction.copy( ray.direction );
  8064. return this;
  8065. }
  8066. /**
  8067. * Returns a vector that is located at a given distance along this ray.
  8068. *
  8069. * @param {number} t - The distance along the ray to retrieve a position for.
  8070. * @param {Vector3} target - The target vector that is used to store the method's result.
  8071. * @return {Vector3} A position on the ray.
  8072. */
  8073. at( t, target ) {
  8074. return target.copy( this.origin ).addScaledVector( this.direction, t );
  8075. }
  8076. /**
  8077. * Adjusts the direction of the ray to point at the given vector in world space.
  8078. *
  8079. * @param {Vector3} v - The target position.
  8080. * @return {Ray} A reference to this ray.
  8081. */
  8082. lookAt( v ) {
  8083. this.direction.copy( v ).sub( this.origin ).normalize();
  8084. return this;
  8085. }
  8086. /**
  8087. * Shift the origin of this ray along its direction by the given distance.
  8088. *
  8089. * @param {number} t - The distance along the ray to interpolate.
  8090. * @return {Ray} A reference to this ray.
  8091. */
  8092. recast( t ) {
  8093. this.origin.copy( this.at( t, _vector$a ) );
  8094. return this;
  8095. }
  8096. /**
  8097. * Returns the point along this ray that is closest to the given point.
  8098. *
  8099. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  8100. * @param {Vector3} target - The target vector that is used to store the method's result.
  8101. * @return {Vector3} The closest point on this ray.
  8102. */
  8103. closestPointToPoint( point, target ) {
  8104. target.subVectors( point, this.origin );
  8105. const directionDistance = target.dot( this.direction );
  8106. if ( directionDistance < 0 ) {
  8107. return target.copy( this.origin );
  8108. }
  8109. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8110. }
  8111. /**
  8112. * Returns the distance of the closest approach between this ray and the given point.
  8113. *
  8114. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8115. * @return {number} The distance.
  8116. */
  8117. distanceToPoint( point ) {
  8118. return Math.sqrt( this.distanceSqToPoint( point ) );
  8119. }
  8120. /**
  8121. * Returns the squared distance of the closest approach between this ray and the given point.
  8122. *
  8123. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8124. * @return {number} The squared distance.
  8125. */
  8126. distanceSqToPoint( point ) {
  8127. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  8128. // point behind the ray
  8129. if ( directionDistance < 0 ) {
  8130. return this.origin.distanceToSquared( point );
  8131. }
  8132. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8133. return _vector$a.distanceToSquared( point );
  8134. }
  8135. /**
  8136. * Returns the squared distance between this ray and the given line segment.
  8137. *
  8138. * @param {Vector3} v0 - The start point of the line segment.
  8139. * @param {Vector3} v1 - The end point of the line segment.
  8140. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  8141. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  8142. * @return {number} The squared distance.
  8143. */
  8144. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  8145. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8146. // It returns the min distance between the ray and the segment
  8147. // defined by v0 and v1
  8148. // It can also set two optional targets :
  8149. // - The closest point on the ray
  8150. // - The closest point on the segment
  8151. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  8152. _segDir.copy( v1 ).sub( v0 ).normalize();
  8153. _diff.copy( this.origin ).sub( _segCenter );
  8154. const segExtent = v0.distanceTo( v1 ) * 0.5;
  8155. const a01 = - this.direction.dot( _segDir );
  8156. const b0 = _diff.dot( this.direction );
  8157. const b1 = - _diff.dot( _segDir );
  8158. const c = _diff.lengthSq();
  8159. const det = Math.abs( 1 - a01 * a01 );
  8160. let s0, s1, sqrDist, extDet;
  8161. if ( det > 0 ) {
  8162. // The ray and segment are not parallel.
  8163. s0 = a01 * b1 - b0;
  8164. s1 = a01 * b0 - b1;
  8165. extDet = segExtent * det;
  8166. if ( s0 >= 0 ) {
  8167. if ( s1 >= - extDet ) {
  8168. if ( s1 <= extDet ) {
  8169. // region 0
  8170. // Minimum at interior points of ray and segment.
  8171. const invDet = 1 / det;
  8172. s0 *= invDet;
  8173. s1 *= invDet;
  8174. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  8175. } else {
  8176. // region 1
  8177. s1 = segExtent;
  8178. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8179. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8180. }
  8181. } else {
  8182. // region 5
  8183. s1 = - segExtent;
  8184. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8185. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8186. }
  8187. } else {
  8188. if ( s1 <= - extDet ) {
  8189. // region 4
  8190. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  8191. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8192. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8193. } else if ( s1 <= extDet ) {
  8194. // region 3
  8195. s0 = 0;
  8196. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8197. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  8198. } else {
  8199. // region 2
  8200. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  8201. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8202. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8203. }
  8204. }
  8205. } else {
  8206. // Ray and segment are parallel.
  8207. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  8208. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8209. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8210. }
  8211. if ( optionalPointOnRay ) {
  8212. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  8213. }
  8214. if ( optionalPointOnSegment ) {
  8215. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  8216. }
  8217. return sqrDist;
  8218. }
  8219. /**
  8220. * Intersects this ray with the given sphere, returning the intersection
  8221. * point or `null` if there is no intersection.
  8222. *
  8223. * @param {Sphere} sphere - The sphere to intersect.
  8224. * @param {Vector3} target - The target vector that is used to store the method's result.
  8225. * @return {?Vector3} The intersection point.
  8226. */
  8227. intersectSphere( sphere, target ) {
  8228. _vector$a.subVectors( sphere.center, this.origin );
  8229. const tca = _vector$a.dot( this.direction );
  8230. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  8231. const radius2 = sphere.radius * sphere.radius;
  8232. if ( d2 > radius2 ) return null;
  8233. const thc = Math.sqrt( radius2 - d2 );
  8234. // t0 = first intersect point - entrance on front of sphere
  8235. const t0 = tca - thc;
  8236. // t1 = second intersect point - exit point on back of sphere
  8237. const t1 = tca + thc;
  8238. // test to see if t1 is behind the ray - if so, return null
  8239. if ( t1 < 0 ) return null;
  8240. // test to see if t0 is behind the ray:
  8241. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  8242. // in order to always return an intersect point that is in front of the ray.
  8243. if ( t0 < 0 ) return this.at( t1, target );
  8244. // else t0 is in front of the ray, so return the first collision point scaled by t0
  8245. return this.at( t0, target );
  8246. }
  8247. /**
  8248. * Returns `true` if this ray intersects with the given sphere.
  8249. *
  8250. * @param {Sphere} sphere - The sphere to intersect.
  8251. * @return {boolean} Whether this ray intersects with the given sphere or not.
  8252. */
  8253. intersectsSphere( sphere ) {
  8254. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  8255. }
  8256. /**
  8257. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  8258. * does not intersect with the plane.
  8259. *
  8260. * @param {Plane} plane - The plane to compute the distance to.
  8261. * @return {?number} Whether this ray intersects with the given sphere or not.
  8262. */
  8263. distanceToPlane( plane ) {
  8264. const denominator = plane.normal.dot( this.direction );
  8265. if ( denominator === 0 ) {
  8266. // line is coplanar, return origin
  8267. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  8268. return 0;
  8269. }
  8270. // Null is preferable to undefined since undefined means.... it is undefined
  8271. return null;
  8272. }
  8273. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  8274. // Return if the ray never intersects the plane
  8275. return t >= 0 ? t : null;
  8276. }
  8277. /**
  8278. * Intersects this ray with the given plane, returning the intersection
  8279. * point or `null` if there is no intersection.
  8280. *
  8281. * @param {Plane} plane - The plane to intersect.
  8282. * @param {Vector3} target - The target vector that is used to store the method's result.
  8283. * @return {?Vector3} The intersection point.
  8284. */
  8285. intersectPlane( plane, target ) {
  8286. const t = this.distanceToPlane( plane );
  8287. if ( t === null ) {
  8288. return null;
  8289. }
  8290. return this.at( t, target );
  8291. }
  8292. /**
  8293. * Returns `true` if this ray intersects with the given plane.
  8294. *
  8295. * @param {Plane} plane - The plane to intersect.
  8296. * @return {boolean} Whether this ray intersects with the given plane or not.
  8297. */
  8298. intersectsPlane( plane ) {
  8299. // check if the ray lies on the plane first
  8300. const distToPoint = plane.distanceToPoint( this.origin );
  8301. if ( distToPoint === 0 ) {
  8302. return true;
  8303. }
  8304. const denominator = plane.normal.dot( this.direction );
  8305. if ( denominator * distToPoint < 0 ) {
  8306. return true;
  8307. }
  8308. // ray origin is behind the plane (and is pointing behind it)
  8309. return false;
  8310. }
  8311. /**
  8312. * Intersects this ray with the given bounding box, returning the intersection
  8313. * point or `null` if there is no intersection.
  8314. *
  8315. * @param {Box3} box - The box to intersect.
  8316. * @param {Vector3} target - The target vector that is used to store the method's result.
  8317. * @return {?Vector3} The intersection point.
  8318. */
  8319. intersectBox( box, target ) {
  8320. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  8321. const invdirx = 1 / this.direction.x,
  8322. invdiry = 1 / this.direction.y,
  8323. invdirz = 1 / this.direction.z;
  8324. const origin = this.origin;
  8325. if ( invdirx >= 0 ) {
  8326. tmin = ( box.min.x - origin.x ) * invdirx;
  8327. tmax = ( box.max.x - origin.x ) * invdirx;
  8328. } else {
  8329. tmin = ( box.max.x - origin.x ) * invdirx;
  8330. tmax = ( box.min.x - origin.x ) * invdirx;
  8331. }
  8332. if ( invdiry >= 0 ) {
  8333. tymin = ( box.min.y - origin.y ) * invdiry;
  8334. tymax = ( box.max.y - origin.y ) * invdiry;
  8335. } else {
  8336. tymin = ( box.max.y - origin.y ) * invdiry;
  8337. tymax = ( box.min.y - origin.y ) * invdiry;
  8338. }
  8339. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  8340. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  8341. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  8342. if ( invdirz >= 0 ) {
  8343. tzmin = ( box.min.z - origin.z ) * invdirz;
  8344. tzmax = ( box.max.z - origin.z ) * invdirz;
  8345. } else {
  8346. tzmin = ( box.max.z - origin.z ) * invdirz;
  8347. tzmax = ( box.min.z - origin.z ) * invdirz;
  8348. }
  8349. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  8350. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  8351. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  8352. //return point closest to the ray (positive side)
  8353. if ( tmax < 0 ) return null;
  8354. return this.at( tmin >= 0 ? tmin : tmax, target );
  8355. }
  8356. /**
  8357. * Returns `true` if this ray intersects with the given box.
  8358. *
  8359. * @param {Box3} box - The box to intersect.
  8360. * @return {boolean} Whether this ray intersects with the given box or not.
  8361. */
  8362. intersectsBox( box ) {
  8363. return this.intersectBox( box, _vector$a ) !== null;
  8364. }
  8365. /**
  8366. * Intersects this ray with the given triangle, returning the intersection
  8367. * point or `null` if there is no intersection.
  8368. *
  8369. * @param {Vector3} a - The first vertex of the triangle.
  8370. * @param {Vector3} b - The second vertex of the triangle.
  8371. * @param {Vector3} c - The third vertex of the triangle.
  8372. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  8373. * @param {Vector3} target - The target vector that is used to store the method's result.
  8374. * @return {?Vector3} The intersection point.
  8375. */
  8376. intersectTriangle( a, b, c, backfaceCulling, target ) {
  8377. // Compute the offset origin, edges, and normal.
  8378. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  8379. _edge1.subVectors( b, a );
  8380. _edge2.subVectors( c, a );
  8381. _normal$1.crossVectors( _edge1, _edge2 );
  8382. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  8383. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  8384. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  8385. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  8386. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  8387. let DdN = this.direction.dot( _normal$1 );
  8388. let sign;
  8389. if ( DdN > 0 ) {
  8390. if ( backfaceCulling ) return null;
  8391. sign = 1;
  8392. } else if ( DdN < 0 ) {
  8393. sign = -1;
  8394. DdN = - DdN;
  8395. } else {
  8396. return null;
  8397. }
  8398. _diff.subVectors( this.origin, a );
  8399. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  8400. // b1 < 0, no intersection
  8401. if ( DdQxE2 < 0 ) {
  8402. return null;
  8403. }
  8404. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  8405. // b2 < 0, no intersection
  8406. if ( DdE1xQ < 0 ) {
  8407. return null;
  8408. }
  8409. // b1+b2 > 1, no intersection
  8410. if ( DdQxE2 + DdE1xQ > DdN ) {
  8411. return null;
  8412. }
  8413. // Line intersects triangle, check if ray does.
  8414. const QdN = - sign * _diff.dot( _normal$1 );
  8415. // t < 0, no intersection
  8416. if ( QdN < 0 ) {
  8417. return null;
  8418. }
  8419. // Ray intersects triangle.
  8420. return this.at( QdN / DdN, target );
  8421. }
  8422. /**
  8423. * Transforms this ray with the given 4x4 transformation matrix.
  8424. *
  8425. * @param {Matrix4} matrix4 - The transformation matrix.
  8426. * @return {Ray} A reference to this ray.
  8427. */
  8428. applyMatrix4( matrix4 ) {
  8429. this.origin.applyMatrix4( matrix4 );
  8430. this.direction.transformDirection( matrix4 );
  8431. return this;
  8432. }
  8433. /**
  8434. * Returns `true` if this ray is equal with the given one.
  8435. *
  8436. * @param {Ray} ray - The ray to test for equality.
  8437. * @return {boolean} Whether this ray is equal with the given one.
  8438. */
  8439. equals( ray ) {
  8440. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  8441. }
  8442. /**
  8443. * Returns a new ray with copied values from this instance.
  8444. *
  8445. * @return {Ray} A clone of this instance.
  8446. */
  8447. clone() {
  8448. return new this.constructor().copy( this );
  8449. }
  8450. }
  8451. /**
  8452. * Represents a 4x4 matrix.
  8453. *
  8454. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  8455. * 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}
  8456. *
  8457. * This allows a 3D vector representing a point in 3D space to undergo
  8458. * transformations such as translation, rotation, shear, scale, reflection,
  8459. * orthogonal or perspective projection and so on, by being multiplied by the
  8460. * matrix. This is known as `applying` the matrix to the vector.
  8461. *
  8462. * A Note on Row-Major and Column-Major Ordering:
  8463. *
  8464. * The constructor and {@link Matrix3#set} method take arguments in
  8465. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  8466. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  8467. * This means that calling:
  8468. * ```js
  8469. * const m = new THREE.Matrix4();
  8470. * m.set( 11, 12, 13, 14,
  8471. * 21, 22, 23, 24,
  8472. * 31, 32, 33, 34,
  8473. * 41, 42, 43, 44 );
  8474. * ```
  8475. * will result in the elements array containing:
  8476. * ```js
  8477. * m.elements = [ 11, 21, 31, 41,
  8478. * 12, 22, 32, 42,
  8479. * 13, 23, 33, 43,
  8480. * 14, 24, 34, 44 ];
  8481. * ```
  8482. * and internally all calculations are performed using column-major ordering.
  8483. * However, as the actual ordering makes no difference mathematically and
  8484. * most people are used to thinking about matrices in row-major order, the
  8485. * three.js documentation shows matrices in row-major order. Just bear in
  8486. * mind that if you are reading the source code, you'll have to take the
  8487. * transpose of any matrices outlined here to make sense of the calculations.
  8488. */
  8489. class Matrix4 {
  8490. /**
  8491. * Constructs a new 4x4 matrix. The arguments are supposed to be
  8492. * in row-major order. If no arguments are provided, the constructor
  8493. * initializes the matrix as an identity matrix.
  8494. *
  8495. * @param {number} [n11] - 1-1 matrix element.
  8496. * @param {number} [n12] - 1-2 matrix element.
  8497. * @param {number} [n13] - 1-3 matrix element.
  8498. * @param {number} [n14] - 1-4 matrix element.
  8499. * @param {number} [n21] - 2-1 matrix element.
  8500. * @param {number} [n22] - 2-2 matrix element.
  8501. * @param {number} [n23] - 2-3 matrix element.
  8502. * @param {number} [n24] - 2-4 matrix element.
  8503. * @param {number} [n31] - 3-1 matrix element.
  8504. * @param {number} [n32] - 3-2 matrix element.
  8505. * @param {number} [n33] - 3-3 matrix element.
  8506. * @param {number} [n34] - 3-4 matrix element.
  8507. * @param {number} [n41] - 4-1 matrix element.
  8508. * @param {number} [n42] - 4-2 matrix element.
  8509. * @param {number} [n43] - 4-3 matrix element.
  8510. * @param {number} [n44] - 4-4 matrix element.
  8511. */
  8512. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8513. /**
  8514. * This flag can be used for type testing.
  8515. *
  8516. * @type {boolean}
  8517. * @readonly
  8518. * @default true
  8519. */
  8520. Matrix4.prototype.isMatrix4 = true;
  8521. /**
  8522. * A column-major list of matrix values.
  8523. *
  8524. * @type {Array<number>}
  8525. */
  8526. this.elements = [
  8527. 1, 0, 0, 0,
  8528. 0, 1, 0, 0,
  8529. 0, 0, 1, 0,
  8530. 0, 0, 0, 1
  8531. ];
  8532. if ( n11 !== undefined ) {
  8533. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  8534. }
  8535. }
  8536. /**
  8537. * Sets the elements of the matrix.The arguments are supposed to be
  8538. * in row-major order.
  8539. *
  8540. * @param {number} [n11] - 1-1 matrix element.
  8541. * @param {number} [n12] - 1-2 matrix element.
  8542. * @param {number} [n13] - 1-3 matrix element.
  8543. * @param {number} [n14] - 1-4 matrix element.
  8544. * @param {number} [n21] - 2-1 matrix element.
  8545. * @param {number} [n22] - 2-2 matrix element.
  8546. * @param {number} [n23] - 2-3 matrix element.
  8547. * @param {number} [n24] - 2-4 matrix element.
  8548. * @param {number} [n31] - 3-1 matrix element.
  8549. * @param {number} [n32] - 3-2 matrix element.
  8550. * @param {number} [n33] - 3-3 matrix element.
  8551. * @param {number} [n34] - 3-4 matrix element.
  8552. * @param {number} [n41] - 4-1 matrix element.
  8553. * @param {number} [n42] - 4-2 matrix element.
  8554. * @param {number} [n43] - 4-3 matrix element.
  8555. * @param {number} [n44] - 4-4 matrix element.
  8556. * @return {Matrix4} A reference to this matrix.
  8557. */
  8558. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8559. const te = this.elements;
  8560. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  8561. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  8562. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  8563. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  8564. return this;
  8565. }
  8566. /**
  8567. * Sets this matrix to the 4x4 identity matrix.
  8568. *
  8569. * @return {Matrix4} A reference to this matrix.
  8570. */
  8571. identity() {
  8572. this.set(
  8573. 1, 0, 0, 0,
  8574. 0, 1, 0, 0,
  8575. 0, 0, 1, 0,
  8576. 0, 0, 0, 1
  8577. );
  8578. return this;
  8579. }
  8580. /**
  8581. * Returns a matrix with copied values from this instance.
  8582. *
  8583. * @return {Matrix4} A clone of this instance.
  8584. */
  8585. clone() {
  8586. return new Matrix4().fromArray( this.elements );
  8587. }
  8588. /**
  8589. * Copies the values of the given matrix to this instance.
  8590. *
  8591. * @param {Matrix4} m - The matrix to copy.
  8592. * @return {Matrix4} A reference to this matrix.
  8593. */
  8594. copy( m ) {
  8595. const te = this.elements;
  8596. const me = m.elements;
  8597. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  8598. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  8599. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  8600. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  8601. return this;
  8602. }
  8603. /**
  8604. * Copies the translation component of the given matrix
  8605. * into this matrix's translation component.
  8606. *
  8607. * @param {Matrix4} m - The matrix to copy the translation component.
  8608. * @return {Matrix4} A reference to this matrix.
  8609. */
  8610. copyPosition( m ) {
  8611. const te = this.elements, me = m.elements;
  8612. te[ 12 ] = me[ 12 ];
  8613. te[ 13 ] = me[ 13 ];
  8614. te[ 14 ] = me[ 14 ];
  8615. return this;
  8616. }
  8617. /**
  8618. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  8619. *
  8620. * @param {Matrix3} m - The 3x3 matrix.
  8621. * @return {Matrix4} A reference to this matrix.
  8622. */
  8623. setFromMatrix3( m ) {
  8624. const me = m.elements;
  8625. this.set(
  8626. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  8627. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  8628. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  8629. 0, 0, 0, 1
  8630. );
  8631. return this;
  8632. }
  8633. /**
  8634. * Extracts the basis of this matrix into the three axis vectors provided.
  8635. *
  8636. * @param {Vector3} xAxis - The basis's x axis.
  8637. * @param {Vector3} yAxis - The basis's y axis.
  8638. * @param {Vector3} zAxis - The basis's z axis.
  8639. * @return {Matrix4} A reference to this matrix.
  8640. */
  8641. extractBasis( xAxis, yAxis, zAxis ) {
  8642. xAxis.setFromMatrixColumn( this, 0 );
  8643. yAxis.setFromMatrixColumn( this, 1 );
  8644. zAxis.setFromMatrixColumn( this, 2 );
  8645. return this;
  8646. }
  8647. /**
  8648. * Sets the given basis vectors to this matrix.
  8649. *
  8650. * @param {Vector3} xAxis - The basis's x axis.
  8651. * @param {Vector3} yAxis - The basis's y axis.
  8652. * @param {Vector3} zAxis - The basis's z axis.
  8653. * @return {Matrix4} A reference to this matrix.
  8654. */
  8655. makeBasis( xAxis, yAxis, zAxis ) {
  8656. this.set(
  8657. xAxis.x, yAxis.x, zAxis.x, 0,
  8658. xAxis.y, yAxis.y, zAxis.y, 0,
  8659. xAxis.z, yAxis.z, zAxis.z, 0,
  8660. 0, 0, 0, 1
  8661. );
  8662. return this;
  8663. }
  8664. /**
  8665. * Extracts the rotation component of the given matrix
  8666. * into this matrix's rotation component.
  8667. *
  8668. * Note: This method does not support reflection matrices.
  8669. *
  8670. * @param {Matrix4} m - The matrix.
  8671. * @return {Matrix4} A reference to this matrix.
  8672. */
  8673. extractRotation( m ) {
  8674. const te = this.elements;
  8675. const me = m.elements;
  8676. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  8677. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  8678. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  8679. te[ 0 ] = me[ 0 ] * scaleX;
  8680. te[ 1 ] = me[ 1 ] * scaleX;
  8681. te[ 2 ] = me[ 2 ] * scaleX;
  8682. te[ 3 ] = 0;
  8683. te[ 4 ] = me[ 4 ] * scaleY;
  8684. te[ 5 ] = me[ 5 ] * scaleY;
  8685. te[ 6 ] = me[ 6 ] * scaleY;
  8686. te[ 7 ] = 0;
  8687. te[ 8 ] = me[ 8 ] * scaleZ;
  8688. te[ 9 ] = me[ 9 ] * scaleZ;
  8689. te[ 10 ] = me[ 10 ] * scaleZ;
  8690. te[ 11 ] = 0;
  8691. te[ 12 ] = 0;
  8692. te[ 13 ] = 0;
  8693. te[ 14 ] = 0;
  8694. te[ 15 ] = 1;
  8695. return this;
  8696. }
  8697. /**
  8698. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  8699. * the rotation specified by the given Euler angles. The rest of
  8700. * the matrix is set to the identity. Depending on the {@link Euler#order},
  8701. * there are six possible outcomes. See [this page]{@link https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix}
  8702. * for a complete list.
  8703. *
  8704. * @param {Euler} euler - The Euler angles.
  8705. * @return {Matrix4} A reference to this matrix.
  8706. */
  8707. makeRotationFromEuler( euler ) {
  8708. const te = this.elements;
  8709. const x = euler.x, y = euler.y, z = euler.z;
  8710. const a = Math.cos( x ), b = Math.sin( x );
  8711. const c = Math.cos( y ), d = Math.sin( y );
  8712. const e = Math.cos( z ), f = Math.sin( z );
  8713. if ( euler.order === 'XYZ' ) {
  8714. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8715. te[ 0 ] = c * e;
  8716. te[ 4 ] = - c * f;
  8717. te[ 8 ] = d;
  8718. te[ 1 ] = af + be * d;
  8719. te[ 5 ] = ae - bf * d;
  8720. te[ 9 ] = - b * c;
  8721. te[ 2 ] = bf - ae * d;
  8722. te[ 6 ] = be + af * d;
  8723. te[ 10 ] = a * c;
  8724. } else if ( euler.order === 'YXZ' ) {
  8725. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8726. te[ 0 ] = ce + df * b;
  8727. te[ 4 ] = de * b - cf;
  8728. te[ 8 ] = a * d;
  8729. te[ 1 ] = a * f;
  8730. te[ 5 ] = a * e;
  8731. te[ 9 ] = - b;
  8732. te[ 2 ] = cf * b - de;
  8733. te[ 6 ] = df + ce * b;
  8734. te[ 10 ] = a * c;
  8735. } else if ( euler.order === 'ZXY' ) {
  8736. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8737. te[ 0 ] = ce - df * b;
  8738. te[ 4 ] = - a * f;
  8739. te[ 8 ] = de + cf * b;
  8740. te[ 1 ] = cf + de * b;
  8741. te[ 5 ] = a * e;
  8742. te[ 9 ] = df - ce * b;
  8743. te[ 2 ] = - a * d;
  8744. te[ 6 ] = b;
  8745. te[ 10 ] = a * c;
  8746. } else if ( euler.order === 'ZYX' ) {
  8747. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8748. te[ 0 ] = c * e;
  8749. te[ 4 ] = be * d - af;
  8750. te[ 8 ] = ae * d + bf;
  8751. te[ 1 ] = c * f;
  8752. te[ 5 ] = bf * d + ae;
  8753. te[ 9 ] = af * d - be;
  8754. te[ 2 ] = - d;
  8755. te[ 6 ] = b * c;
  8756. te[ 10 ] = a * c;
  8757. } else if ( euler.order === 'YZX' ) {
  8758. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8759. te[ 0 ] = c * e;
  8760. te[ 4 ] = bd - ac * f;
  8761. te[ 8 ] = bc * f + ad;
  8762. te[ 1 ] = f;
  8763. te[ 5 ] = a * e;
  8764. te[ 9 ] = - b * e;
  8765. te[ 2 ] = - d * e;
  8766. te[ 6 ] = ad * f + bc;
  8767. te[ 10 ] = ac - bd * f;
  8768. } else if ( euler.order === 'XZY' ) {
  8769. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8770. te[ 0 ] = c * e;
  8771. te[ 4 ] = - f;
  8772. te[ 8 ] = d * e;
  8773. te[ 1 ] = ac * f + bd;
  8774. te[ 5 ] = a * e;
  8775. te[ 9 ] = ad * f - bc;
  8776. te[ 2 ] = bc * f - ad;
  8777. te[ 6 ] = b * e;
  8778. te[ 10 ] = bd * f + ac;
  8779. }
  8780. // bottom row
  8781. te[ 3 ] = 0;
  8782. te[ 7 ] = 0;
  8783. te[ 11 ] = 0;
  8784. // last column
  8785. te[ 12 ] = 0;
  8786. te[ 13 ] = 0;
  8787. te[ 14 ] = 0;
  8788. te[ 15 ] = 1;
  8789. return this;
  8790. }
  8791. /**
  8792. * Sets the rotation component of this matrix to the rotation specified by
  8793. * the given Quaternion as outlined [here]{@link https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion}
  8794. * The rest of the matrix is set to the identity.
  8795. *
  8796. * @param {Quaternion} q - The Quaternion.
  8797. * @return {Matrix4} A reference to this matrix.
  8798. */
  8799. makeRotationFromQuaternion( q ) {
  8800. return this.compose( _zero, q, _one );
  8801. }
  8802. /**
  8803. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  8804. * `target`, and oriented by the up-direction.
  8805. *
  8806. * @param {Vector3} eye - The eye vector.
  8807. * @param {Vector3} target - The target vector.
  8808. * @param {Vector3} up - The up vector.
  8809. * @return {Matrix4} A reference to this matrix.
  8810. */
  8811. lookAt( eye, target, up ) {
  8812. const te = this.elements;
  8813. _z.subVectors( eye, target );
  8814. if ( _z.lengthSq() === 0 ) {
  8815. // eye and target are in the same position
  8816. _z.z = 1;
  8817. }
  8818. _z.normalize();
  8819. _x.crossVectors( up, _z );
  8820. if ( _x.lengthSq() === 0 ) {
  8821. // up and z are parallel
  8822. if ( Math.abs( up.z ) === 1 ) {
  8823. _z.x += 0.0001;
  8824. } else {
  8825. _z.z += 0.0001;
  8826. }
  8827. _z.normalize();
  8828. _x.crossVectors( up, _z );
  8829. }
  8830. _x.normalize();
  8831. _y.crossVectors( _z, _x );
  8832. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  8833. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  8834. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  8835. return this;
  8836. }
  8837. /**
  8838. * Post-multiplies this matrix by the given 4x4 matrix.
  8839. *
  8840. * @param {Matrix4} m - The matrix to multiply with.
  8841. * @return {Matrix4} A reference to this matrix.
  8842. */
  8843. multiply( m ) {
  8844. return this.multiplyMatrices( this, m );
  8845. }
  8846. /**
  8847. * Pre-multiplies this matrix by the given 4x4 matrix.
  8848. *
  8849. * @param {Matrix4} m - The matrix to multiply with.
  8850. * @return {Matrix4} A reference to this matrix.
  8851. */
  8852. premultiply( m ) {
  8853. return this.multiplyMatrices( m, this );
  8854. }
  8855. /**
  8856. * Multiples the given 4x4 matrices and stores the result
  8857. * in this matrix.
  8858. *
  8859. * @param {Matrix4} a - The first matrix.
  8860. * @param {Matrix4} b - The second matrix.
  8861. * @return {Matrix4} A reference to this matrix.
  8862. */
  8863. multiplyMatrices( a, b ) {
  8864. const ae = a.elements;
  8865. const be = b.elements;
  8866. const te = this.elements;
  8867. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  8868. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  8869. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  8870. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  8871. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  8872. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  8873. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  8874. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  8875. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  8876. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  8877. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  8878. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  8879. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  8880. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  8881. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  8882. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  8883. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  8884. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  8885. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  8886. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  8887. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  8888. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  8889. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  8890. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  8891. return this;
  8892. }
  8893. /**
  8894. * Multiplies every component of the matrix by the given scalar.
  8895. *
  8896. * @param {number} s - The scalar.
  8897. * @return {Matrix4} A reference to this matrix.
  8898. */
  8899. multiplyScalar( s ) {
  8900. const te = this.elements;
  8901. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  8902. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  8903. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  8904. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  8905. return this;
  8906. }
  8907. /**
  8908. * Computes and returns the determinant of this matrix.
  8909. *
  8910. * Based on the method outlined [here]{@link http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html}.
  8911. *
  8912. * @return {number} The determinant.
  8913. */
  8914. determinant() {
  8915. const te = this.elements;
  8916. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  8917. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  8918. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  8919. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  8920. //TODO: make this more efficient
  8921. return (
  8922. n41 * (
  8923. + n14 * n23 * n32
  8924. - n13 * n24 * n32
  8925. - n14 * n22 * n33
  8926. + n12 * n24 * n33
  8927. + n13 * n22 * n34
  8928. - n12 * n23 * n34
  8929. ) +
  8930. n42 * (
  8931. + n11 * n23 * n34
  8932. - n11 * n24 * n33
  8933. + n14 * n21 * n33
  8934. - n13 * n21 * n34
  8935. + n13 * n24 * n31
  8936. - n14 * n23 * n31
  8937. ) +
  8938. n43 * (
  8939. + n11 * n24 * n32
  8940. - n11 * n22 * n34
  8941. - n14 * n21 * n32
  8942. + n12 * n21 * n34
  8943. + n14 * n22 * n31
  8944. - n12 * n24 * n31
  8945. ) +
  8946. n44 * (
  8947. - n13 * n22 * n31
  8948. - n11 * n23 * n32
  8949. + n11 * n22 * n33
  8950. + n13 * n21 * n32
  8951. - n12 * n21 * n33
  8952. + n12 * n23 * n31
  8953. )
  8954. );
  8955. }
  8956. /**
  8957. * Transposes this matrix in place.
  8958. *
  8959. * @return {Matrix4} A reference to this matrix.
  8960. */
  8961. transpose() {
  8962. const te = this.elements;
  8963. let tmp;
  8964. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  8965. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  8966. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  8967. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  8968. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  8969. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  8970. return this;
  8971. }
  8972. /**
  8973. * Sets the position component for this matrix from the given vector,
  8974. * without affecting the rest of the matrix.
  8975. *
  8976. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  8977. * @param {number} y - The y component of the vector.
  8978. * @param {number} z - The z component of the vector.
  8979. * @return {Matrix4} A reference to this matrix.
  8980. */
  8981. setPosition( x, y, z ) {
  8982. const te = this.elements;
  8983. if ( x.isVector3 ) {
  8984. te[ 12 ] = x.x;
  8985. te[ 13 ] = x.y;
  8986. te[ 14 ] = x.z;
  8987. } else {
  8988. te[ 12 ] = x;
  8989. te[ 13 ] = y;
  8990. te[ 14 ] = z;
  8991. }
  8992. return this;
  8993. }
  8994. /**
  8995. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  8996. * You can not invert with a determinant of zero. If you attempt this, the method produces
  8997. * a zero matrix instead.
  8998. *
  8999. * @return {Matrix4} A reference to this matrix.
  9000. */
  9001. invert() {
  9002. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  9003. const te = this.elements,
  9004. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  9005. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  9006. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  9007. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  9008. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  9009. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  9010. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  9011. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  9012. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  9013. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  9014. const detInv = 1 / det;
  9015. te[ 0 ] = t11 * detInv;
  9016. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  9017. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  9018. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  9019. te[ 4 ] = t12 * detInv;
  9020. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  9021. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  9022. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  9023. te[ 8 ] = t13 * detInv;
  9024. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  9025. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  9026. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  9027. te[ 12 ] = t14 * detInv;
  9028. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  9029. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  9030. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  9031. return this;
  9032. }
  9033. /**
  9034. * Multiplies the columns of this matrix by the given vector.
  9035. *
  9036. * @param {Vector3} v - The scale vector.
  9037. * @return {Matrix4} A reference to this matrix.
  9038. */
  9039. scale( v ) {
  9040. const te = this.elements;
  9041. const x = v.x, y = v.y, z = v.z;
  9042. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  9043. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  9044. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  9045. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  9046. return this;
  9047. }
  9048. /**
  9049. * Gets the maximum scale value of the three axes.
  9050. *
  9051. * @return {number} The maximum scale.
  9052. */
  9053. getMaxScaleOnAxis() {
  9054. const te = this.elements;
  9055. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  9056. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  9057. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  9058. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  9059. }
  9060. /**
  9061. * Sets this matrix as a translation transform from the given vector.
  9062. *
  9063. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  9064. * @param {number} y - The amount to translate in the Y axis.
  9065. * @param {number} z - The amount to translate in the z axis.
  9066. * @return {Matrix4} A reference to this matrix.
  9067. */
  9068. makeTranslation( x, y, z ) {
  9069. if ( x.isVector3 ) {
  9070. this.set(
  9071. 1, 0, 0, x.x,
  9072. 0, 1, 0, x.y,
  9073. 0, 0, 1, x.z,
  9074. 0, 0, 0, 1
  9075. );
  9076. } else {
  9077. this.set(
  9078. 1, 0, 0, x,
  9079. 0, 1, 0, y,
  9080. 0, 0, 1, z,
  9081. 0, 0, 0, 1
  9082. );
  9083. }
  9084. return this;
  9085. }
  9086. /**
  9087. * Sets this matrix as a rotational transformation around the X axis by
  9088. * the given angle.
  9089. *
  9090. * @param {number} theta - The rotation in radians.
  9091. * @return {Matrix4} A reference to this matrix.
  9092. */
  9093. makeRotationX( theta ) {
  9094. const c = Math.cos( theta ), s = Math.sin( theta );
  9095. this.set(
  9096. 1, 0, 0, 0,
  9097. 0, c, - s, 0,
  9098. 0, s, c, 0,
  9099. 0, 0, 0, 1
  9100. );
  9101. return this;
  9102. }
  9103. /**
  9104. * Sets this matrix as a rotational transformation around the Y axis by
  9105. * the given angle.
  9106. *
  9107. * @param {number} theta - The rotation in radians.
  9108. * @return {Matrix4} A reference to this matrix.
  9109. */
  9110. makeRotationY( theta ) {
  9111. const c = Math.cos( theta ), s = Math.sin( theta );
  9112. this.set(
  9113. c, 0, s, 0,
  9114. 0, 1, 0, 0,
  9115. - s, 0, c, 0,
  9116. 0, 0, 0, 1
  9117. );
  9118. return this;
  9119. }
  9120. /**
  9121. * Sets this matrix as a rotational transformation around the Z axis by
  9122. * the given angle.
  9123. *
  9124. * @param {number} theta - The rotation in radians.
  9125. * @return {Matrix4} A reference to this matrix.
  9126. */
  9127. makeRotationZ( theta ) {
  9128. const c = Math.cos( theta ), s = Math.sin( theta );
  9129. this.set(
  9130. c, - s, 0, 0,
  9131. s, c, 0, 0,
  9132. 0, 0, 1, 0,
  9133. 0, 0, 0, 1
  9134. );
  9135. return this;
  9136. }
  9137. /**
  9138. * Sets this matrix as a rotational transformation around the given axis by
  9139. * the given angle.
  9140. *
  9141. * This is a somewhat controversial but mathematically sound alternative to
  9142. * rotating via Quaternions. See the discussion [here]{@link https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199}.
  9143. *
  9144. * @param {Vector3} axis - The normalized rotation axis.
  9145. * @param {number} angle - The rotation in radians.
  9146. * @return {Matrix4} A reference to this matrix.
  9147. */
  9148. makeRotationAxis( axis, angle ) {
  9149. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  9150. const c = Math.cos( angle );
  9151. const s = Math.sin( angle );
  9152. const t = 1 - c;
  9153. const x = axis.x, y = axis.y, z = axis.z;
  9154. const tx = t * x, ty = t * y;
  9155. this.set(
  9156. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  9157. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  9158. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  9159. 0, 0, 0, 1
  9160. );
  9161. return this;
  9162. }
  9163. /**
  9164. * Sets this matrix as a scale transformation.
  9165. *
  9166. * @param {number} x - The amount to scale in the X axis.
  9167. * @param {number} y - The amount to scale in the Y axis.
  9168. * @param {number} z - The amount to scale in the Z axis.
  9169. * @return {Matrix4} A reference to this matrix.
  9170. */
  9171. makeScale( x, y, z ) {
  9172. this.set(
  9173. x, 0, 0, 0,
  9174. 0, y, 0, 0,
  9175. 0, 0, z, 0,
  9176. 0, 0, 0, 1
  9177. );
  9178. return this;
  9179. }
  9180. /**
  9181. * Sets this matrix as a shear transformation.
  9182. *
  9183. * @param {number} xy - The amount to shear X by Y.
  9184. * @param {number} xz - The amount to shear X by Z.
  9185. * @param {number} yx - The amount to shear Y by X.
  9186. * @param {number} yz - The amount to shear Y by Z.
  9187. * @param {number} zx - The amount to shear Z by X.
  9188. * @param {number} zy - The amount to shear Z by Y.
  9189. * @return {Matrix4} A reference to this matrix.
  9190. */
  9191. makeShear( xy, xz, yx, yz, zx, zy ) {
  9192. this.set(
  9193. 1, yx, zx, 0,
  9194. xy, 1, zy, 0,
  9195. xz, yz, 1, 0,
  9196. 0, 0, 0, 1
  9197. );
  9198. return this;
  9199. }
  9200. /**
  9201. * Sets this matrix to the transformation composed of the given position,
  9202. * rotation (Quaternion) and scale.
  9203. *
  9204. * @param {Vector3} position - The position vector.
  9205. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9206. * @param {Vector3} scale - The scale vector.
  9207. * @return {Matrix4} A reference to this matrix.
  9208. */
  9209. compose( position, quaternion, scale ) {
  9210. const te = this.elements;
  9211. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  9212. const x2 = x + x, y2 = y + y, z2 = z + z;
  9213. const xx = x * x2, xy = x * y2, xz = x * z2;
  9214. const yy = y * y2, yz = y * z2, zz = z * z2;
  9215. const wx = w * x2, wy = w * y2, wz = w * z2;
  9216. const sx = scale.x, sy = scale.y, sz = scale.z;
  9217. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  9218. te[ 1 ] = ( xy + wz ) * sx;
  9219. te[ 2 ] = ( xz - wy ) * sx;
  9220. te[ 3 ] = 0;
  9221. te[ 4 ] = ( xy - wz ) * sy;
  9222. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  9223. te[ 6 ] = ( yz + wx ) * sy;
  9224. te[ 7 ] = 0;
  9225. te[ 8 ] = ( xz + wy ) * sz;
  9226. te[ 9 ] = ( yz - wx ) * sz;
  9227. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  9228. te[ 11 ] = 0;
  9229. te[ 12 ] = position.x;
  9230. te[ 13 ] = position.y;
  9231. te[ 14 ] = position.z;
  9232. te[ 15 ] = 1;
  9233. return this;
  9234. }
  9235. /**
  9236. * Decomposes this matrix into its position, rotation and scale components
  9237. * and provides the result in the given objects.
  9238. *
  9239. * Note: Not all matrices are decomposable in this way. For example, if an
  9240. * object has a non-uniformly scaled parent, then the object's world matrix
  9241. * may not be decomposable, and this method may not be appropriate.
  9242. *
  9243. * @param {Vector3} position - The position vector.
  9244. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9245. * @param {Vector3} scale - The scale vector.
  9246. * @return {Matrix4} A reference to this matrix.
  9247. */
  9248. decompose( position, quaternion, scale ) {
  9249. const te = this.elements;
  9250. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  9251. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  9252. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  9253. // if determine is negative, we need to invert one scale
  9254. const det = this.determinant();
  9255. if ( det < 0 ) sx = - sx;
  9256. position.x = te[ 12 ];
  9257. position.y = te[ 13 ];
  9258. position.z = te[ 14 ];
  9259. // scale the rotation part
  9260. _m1$4.copy( this );
  9261. const invSX = 1 / sx;
  9262. const invSY = 1 / sy;
  9263. const invSZ = 1 / sz;
  9264. _m1$4.elements[ 0 ] *= invSX;
  9265. _m1$4.elements[ 1 ] *= invSX;
  9266. _m1$4.elements[ 2 ] *= invSX;
  9267. _m1$4.elements[ 4 ] *= invSY;
  9268. _m1$4.elements[ 5 ] *= invSY;
  9269. _m1$4.elements[ 6 ] *= invSY;
  9270. _m1$4.elements[ 8 ] *= invSZ;
  9271. _m1$4.elements[ 9 ] *= invSZ;
  9272. _m1$4.elements[ 10 ] *= invSZ;
  9273. quaternion.setFromRotationMatrix( _m1$4 );
  9274. scale.x = sx;
  9275. scale.y = sy;
  9276. scale.z = sz;
  9277. return this;
  9278. }
  9279. /**
  9280. * Creates a perspective projection matrix. This is used internally by
  9281. * {@link PerspectiveCamera#updateProjectionMatrix}.
  9282. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9283. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9284. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9285. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9286. * @param {number} near - The distance from the camera to the near plane.
  9287. * @param {number} far - The distance from the camera to the far plane.
  9288. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9289. * @return {Matrix4} A reference to this matrix.
  9290. */
  9291. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  9292. const te = this.elements;
  9293. const x = 2 * near / ( right - left );
  9294. const y = 2 * near / ( top - bottom );
  9295. const a = ( right + left ) / ( right - left );
  9296. const b = ( top + bottom ) / ( top - bottom );
  9297. let c, d;
  9298. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9299. c = - ( far + near ) / ( far - near );
  9300. d = ( -2 * far * near ) / ( far - near );
  9301. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9302. c = - far / ( far - near );
  9303. d = ( - far * near ) / ( far - near );
  9304. } else {
  9305. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  9306. }
  9307. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  9308. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  9309. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9310. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  9311. return this;
  9312. }
  9313. /**
  9314. * Creates a orthographic projection matrix. This is used internally by
  9315. * {@link OrthographicCamera#updateProjectionMatrix}.
  9316. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9317. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9318. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9319. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9320. * @param {number} near - The distance from the camera to the near plane.
  9321. * @param {number} far - The distance from the camera to the far plane.
  9322. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9323. * @return {Matrix4} A reference to this matrix.
  9324. */
  9325. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  9326. const te = this.elements;
  9327. const w = 1.0 / ( right - left );
  9328. const h = 1.0 / ( top - bottom );
  9329. const p = 1.0 / ( far - near );
  9330. const x = ( right + left ) * w;
  9331. const y = ( top + bottom ) * h;
  9332. let z, zInv;
  9333. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9334. z = ( far + near ) * p;
  9335. zInv = -2 * p;
  9336. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9337. z = near * p;
  9338. zInv = -1 * p;
  9339. } else {
  9340. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  9341. }
  9342. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  9343. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  9344. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  9345. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  9346. return this;
  9347. }
  9348. /**
  9349. * Returns `true` if this matrix is equal with the given one.
  9350. *
  9351. * @param {Matrix4} matrix - The matrix to test for equality.
  9352. * @return {boolean} Whether this matrix is equal with the given one.
  9353. */
  9354. equals( matrix ) {
  9355. const te = this.elements;
  9356. const me = matrix.elements;
  9357. for ( let i = 0; i < 16; i ++ ) {
  9358. if ( te[ i ] !== me[ i ] ) return false;
  9359. }
  9360. return true;
  9361. }
  9362. /**
  9363. * Sets the elements of the matrix from the given array.
  9364. *
  9365. * @param {Array<number>} array - The matrix elements in column-major order.
  9366. * @param {number} [offset=0] - Index of the first element in the array.
  9367. * @return {Matrix4} A reference to this matrix.
  9368. */
  9369. fromArray( array, offset = 0 ) {
  9370. for ( let i = 0; i < 16; i ++ ) {
  9371. this.elements[ i ] = array[ i + offset ];
  9372. }
  9373. return this;
  9374. }
  9375. /**
  9376. * Writes the elements of this matrix to the given array. If no array is provided,
  9377. * the method returns a new instance.
  9378. *
  9379. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  9380. * @param {number} [offset=0] - Index of the first element in the array.
  9381. * @return {Array<number>} The matrix elements in column-major order.
  9382. */
  9383. toArray( array = [], offset = 0 ) {
  9384. const te = this.elements;
  9385. array[ offset ] = te[ 0 ];
  9386. array[ offset + 1 ] = te[ 1 ];
  9387. array[ offset + 2 ] = te[ 2 ];
  9388. array[ offset + 3 ] = te[ 3 ];
  9389. array[ offset + 4 ] = te[ 4 ];
  9390. array[ offset + 5 ] = te[ 5 ];
  9391. array[ offset + 6 ] = te[ 6 ];
  9392. array[ offset + 7 ] = te[ 7 ];
  9393. array[ offset + 8 ] = te[ 8 ];
  9394. array[ offset + 9 ] = te[ 9 ];
  9395. array[ offset + 10 ] = te[ 10 ];
  9396. array[ offset + 11 ] = te[ 11 ];
  9397. array[ offset + 12 ] = te[ 12 ];
  9398. array[ offset + 13 ] = te[ 13 ];
  9399. array[ offset + 14 ] = te[ 14 ];
  9400. array[ offset + 15 ] = te[ 15 ];
  9401. return array;
  9402. }
  9403. }
  9404. const _v1$5 = /*@__PURE__*/ new Vector3();
  9405. const _m1$4 = /*@__PURE__*/ new Matrix4();
  9406. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  9407. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  9408. const _x = /*@__PURE__*/ new Vector3();
  9409. const _y = /*@__PURE__*/ new Vector3();
  9410. const _z = /*@__PURE__*/ new Vector3();
  9411. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  9412. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  9413. /**
  9414. * A class representing Euler angles.
  9415. *
  9416. * Euler angles describe a rotational transformation by rotating an object on
  9417. * its various axes in specified amounts per axis, and a specified axis
  9418. * order.
  9419. *
  9420. * Iterating through an instance will yield its components (x, y, z,
  9421. * order) in the corresponding order.
  9422. *
  9423. * ```js
  9424. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  9425. * const b = new THREE.Vector3( 1, 0, 1 );
  9426. * b.applyEuler(a);
  9427. * ```
  9428. */
  9429. class Euler {
  9430. /**
  9431. * Constructs a new euler instance.
  9432. *
  9433. * @param {number} [x=0] - The angle of the x axis in radians.
  9434. * @param {number} [y=0] - The angle of the y axis in radians.
  9435. * @param {number} [z=0] - The angle of the z axis in radians.
  9436. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  9437. */
  9438. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  9439. /**
  9440. * This flag can be used for type testing.
  9441. *
  9442. * @type {boolean}
  9443. * @readonly
  9444. * @default true
  9445. */
  9446. this.isEuler = true;
  9447. this._x = x;
  9448. this._y = y;
  9449. this._z = z;
  9450. this._order = order;
  9451. }
  9452. /**
  9453. * The angle of the x axis in radians.
  9454. *
  9455. * @type {number}
  9456. * @default 0
  9457. */
  9458. get x() {
  9459. return this._x;
  9460. }
  9461. set x( value ) {
  9462. this._x = value;
  9463. this._onChangeCallback();
  9464. }
  9465. /**
  9466. * The angle of the y axis in radians.
  9467. *
  9468. * @type {number}
  9469. * @default 0
  9470. */
  9471. get y() {
  9472. return this._y;
  9473. }
  9474. set y( value ) {
  9475. this._y = value;
  9476. this._onChangeCallback();
  9477. }
  9478. /**
  9479. * The angle of the z axis in radians.
  9480. *
  9481. * @type {number}
  9482. * @default 0
  9483. */
  9484. get z() {
  9485. return this._z;
  9486. }
  9487. set z( value ) {
  9488. this._z = value;
  9489. this._onChangeCallback();
  9490. }
  9491. /**
  9492. * A string representing the order that the rotations are applied.
  9493. *
  9494. * @type {string}
  9495. * @default 'XYZ'
  9496. */
  9497. get order() {
  9498. return this._order;
  9499. }
  9500. set order( value ) {
  9501. this._order = value;
  9502. this._onChangeCallback();
  9503. }
  9504. /**
  9505. * Sets the Euler components.
  9506. *
  9507. * @param {number} x - The angle of the x axis in radians.
  9508. * @param {number} y - The angle of the y axis in radians.
  9509. * @param {number} z - The angle of the z axis in radians.
  9510. * @param {string} [order] - A string representing the order that the rotations are applied.
  9511. * @return {Euler} A reference to this Euler instance.
  9512. */
  9513. set( x, y, z, order = this._order ) {
  9514. this._x = x;
  9515. this._y = y;
  9516. this._z = z;
  9517. this._order = order;
  9518. this._onChangeCallback();
  9519. return this;
  9520. }
  9521. /**
  9522. * Returns a new Euler instance with copied values from this instance.
  9523. *
  9524. * @return {Euler} A clone of this instance.
  9525. */
  9526. clone() {
  9527. return new this.constructor( this._x, this._y, this._z, this._order );
  9528. }
  9529. /**
  9530. * Copies the values of the given Euler instance to this instance.
  9531. *
  9532. * @param {Euler} euler - The Euler instance to copy.
  9533. * @return {Euler} A reference to this Euler instance.
  9534. */
  9535. copy( euler ) {
  9536. this._x = euler._x;
  9537. this._y = euler._y;
  9538. this._z = euler._z;
  9539. this._order = euler._order;
  9540. this._onChangeCallback();
  9541. return this;
  9542. }
  9543. /**
  9544. * Sets the angles of this Euler instance from a pure rotation matrix.
  9545. *
  9546. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  9547. * @param {string} [order] - A string representing the order that the rotations are applied.
  9548. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9549. * @return {Euler} A reference to this Euler instance.
  9550. */
  9551. setFromRotationMatrix( m, order = this._order, update = true ) {
  9552. const te = m.elements;
  9553. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  9554. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  9555. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  9556. switch ( order ) {
  9557. case 'XYZ':
  9558. this._y = Math.asin( clamp( m13, -1, 1 ) );
  9559. if ( Math.abs( m13 ) < 0.9999999 ) {
  9560. this._x = Math.atan2( - m23, m33 );
  9561. this._z = Math.atan2( - m12, m11 );
  9562. } else {
  9563. this._x = Math.atan2( m32, m22 );
  9564. this._z = 0;
  9565. }
  9566. break;
  9567. case 'YXZ':
  9568. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  9569. if ( Math.abs( m23 ) < 0.9999999 ) {
  9570. this._y = Math.atan2( m13, m33 );
  9571. this._z = Math.atan2( m21, m22 );
  9572. } else {
  9573. this._y = Math.atan2( - m31, m11 );
  9574. this._z = 0;
  9575. }
  9576. break;
  9577. case 'ZXY':
  9578. this._x = Math.asin( clamp( m32, -1, 1 ) );
  9579. if ( Math.abs( m32 ) < 0.9999999 ) {
  9580. this._y = Math.atan2( - m31, m33 );
  9581. this._z = Math.atan2( - m12, m22 );
  9582. } else {
  9583. this._y = 0;
  9584. this._z = Math.atan2( m21, m11 );
  9585. }
  9586. break;
  9587. case 'ZYX':
  9588. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  9589. if ( Math.abs( m31 ) < 0.9999999 ) {
  9590. this._x = Math.atan2( m32, m33 );
  9591. this._z = Math.atan2( m21, m11 );
  9592. } else {
  9593. this._x = 0;
  9594. this._z = Math.atan2( - m12, m22 );
  9595. }
  9596. break;
  9597. case 'YZX':
  9598. this._z = Math.asin( clamp( m21, -1, 1 ) );
  9599. if ( Math.abs( m21 ) < 0.9999999 ) {
  9600. this._x = Math.atan2( - m23, m22 );
  9601. this._y = Math.atan2( - m31, m11 );
  9602. } else {
  9603. this._x = 0;
  9604. this._y = Math.atan2( m13, m33 );
  9605. }
  9606. break;
  9607. case 'XZY':
  9608. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  9609. if ( Math.abs( m12 ) < 0.9999999 ) {
  9610. this._x = Math.atan2( m32, m22 );
  9611. this._y = Math.atan2( m13, m11 );
  9612. } else {
  9613. this._x = Math.atan2( - m23, m33 );
  9614. this._y = 0;
  9615. }
  9616. break;
  9617. default:
  9618. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  9619. }
  9620. this._order = order;
  9621. if ( update === true ) this._onChangeCallback();
  9622. return this;
  9623. }
  9624. /**
  9625. * Sets the angles of this Euler instance from a normalized quaternion.
  9626. *
  9627. * @param {Quaternion} q - A normalized Quaternion.
  9628. * @param {string} [order] - A string representing the order that the rotations are applied.
  9629. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9630. * @return {Euler} A reference to this Euler instance.
  9631. */
  9632. setFromQuaternion( q, order, update ) {
  9633. _matrix$2.makeRotationFromQuaternion( q );
  9634. return this.setFromRotationMatrix( _matrix$2, order, update );
  9635. }
  9636. /**
  9637. * Sets the angles of this Euler instance from the given vector.
  9638. *
  9639. * @param {Vector3} v - The vector.
  9640. * @param {string} [order] - A string representing the order that the rotations are applied.
  9641. * @return {Euler} A reference to this Euler instance.
  9642. */
  9643. setFromVector3( v, order = this._order ) {
  9644. return this.set( v.x, v.y, v.z, order );
  9645. }
  9646. /**
  9647. * Resets the euler angle with a new order by creating a quaternion from this
  9648. * euler angle and then setting this euler angle with the quaternion and the
  9649. * new order.
  9650. *
  9651. * Warning: This discards revolution information.
  9652. *
  9653. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  9654. * @return {Euler} A reference to this Euler instance.
  9655. */
  9656. reorder( newOrder ) {
  9657. _quaternion$3.setFromEuler( this );
  9658. return this.setFromQuaternion( _quaternion$3, newOrder );
  9659. }
  9660. /**
  9661. * Returns `true` if this Euler instance is equal with the given one.
  9662. *
  9663. * @param {Euler} euler - The Euler instance to test for equality.
  9664. * @return {boolean} Whether this Euler instance is equal with the given one.
  9665. */
  9666. equals( euler ) {
  9667. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  9668. }
  9669. /**
  9670. * Sets this Euler instance's components to values from the given array. The first three
  9671. * entries of the array are assign to the x,y and z components. An optional fourth entry
  9672. * defines the Euler order.
  9673. *
  9674. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  9675. * @return {Euler} A reference to this Euler instance.
  9676. */
  9677. fromArray( array ) {
  9678. this._x = array[ 0 ];
  9679. this._y = array[ 1 ];
  9680. this._z = array[ 2 ];
  9681. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  9682. this._onChangeCallback();
  9683. return this;
  9684. }
  9685. /**
  9686. * Writes the components of this Euler instance to the given array. If no array is provided,
  9687. * the method returns a new instance.
  9688. *
  9689. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  9690. * @param {number} [offset=0] - Index of the first element in the array.
  9691. * @return {Array<number,number,number,string>} The Euler components.
  9692. */
  9693. toArray( array = [], offset = 0 ) {
  9694. array[ offset ] = this._x;
  9695. array[ offset + 1 ] = this._y;
  9696. array[ offset + 2 ] = this._z;
  9697. array[ offset + 3 ] = this._order;
  9698. return array;
  9699. }
  9700. _onChange( callback ) {
  9701. this._onChangeCallback = callback;
  9702. return this;
  9703. }
  9704. _onChangeCallback() {}
  9705. *[ Symbol.iterator ]() {
  9706. yield this._x;
  9707. yield this._y;
  9708. yield this._z;
  9709. yield this._order;
  9710. }
  9711. }
  9712. /**
  9713. * The default Euler angle order.
  9714. *
  9715. * @static
  9716. * @type {string}
  9717. * @default 'XYZ'
  9718. */
  9719. Euler.DEFAULT_ORDER = 'XYZ';
  9720. /**
  9721. * A layers object assigns an 3D object to 1 or more of 32
  9722. * layers numbered `0` to `31` - internally the layers are stored as a
  9723. * bit mask], and by default all 3D objects are a member of layer `0`.
  9724. *
  9725. * This can be used to control visibility - an object must share a layer with
  9726. * a camera to be visible when that camera's view is
  9727. * rendered.
  9728. *
  9729. * All classes that inherit from {@link Object3D} have an `layers` property which
  9730. * is an instance of this class.
  9731. */
  9732. class Layers {
  9733. /**
  9734. * Constructs a new layers instance, with membership
  9735. * initially set to layer `0`.
  9736. */
  9737. constructor() {
  9738. /**
  9739. * A bit mask storing which of the 32 layers this layers object is currently
  9740. * a member of.
  9741. *
  9742. * @type {number}
  9743. */
  9744. this.mask = 1 | 0;
  9745. }
  9746. /**
  9747. * Sets membership to the given layer, and remove membership all other layers.
  9748. *
  9749. * @param {number} layer - The layer to set.
  9750. */
  9751. set( layer ) {
  9752. this.mask = ( 1 << layer | 0 ) >>> 0;
  9753. }
  9754. /**
  9755. * Adds membership of the given layer.
  9756. *
  9757. * @param {number} layer - The layer to enable.
  9758. */
  9759. enable( layer ) {
  9760. this.mask |= 1 << layer | 0;
  9761. }
  9762. /**
  9763. * Adds membership to all layers.
  9764. */
  9765. enableAll() {
  9766. this.mask = 0xffffffff | 0;
  9767. }
  9768. /**
  9769. * Toggles the membership of the given layer.
  9770. *
  9771. * @param {number} layer - The layer to toggle.
  9772. */
  9773. toggle( layer ) {
  9774. this.mask ^= 1 << layer | 0;
  9775. }
  9776. /**
  9777. * Removes membership of the given layer.
  9778. *
  9779. * @param {number} layer - The layer to enable.
  9780. */
  9781. disable( layer ) {
  9782. this.mask &= ~ ( 1 << layer | 0 );
  9783. }
  9784. /**
  9785. * Removes the membership from all layers.
  9786. */
  9787. disableAll() {
  9788. this.mask = 0;
  9789. }
  9790. /**
  9791. * Returns `true` if this and the given layers object have at least one
  9792. * layer in common.
  9793. *
  9794. * @param {Layers} layers - The layers to test.
  9795. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  9796. */
  9797. test( layers ) {
  9798. return ( this.mask & layers.mask ) !== 0;
  9799. }
  9800. /**
  9801. * Returns `true` if the given layer is enabled.
  9802. *
  9803. * @param {number} layer - The layer to test.
  9804. * @return {boolean } Whether the given layer is enabled or not.
  9805. */
  9806. isEnabled( layer ) {
  9807. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  9808. }
  9809. }
  9810. let _object3DId = 0;
  9811. const _v1$4 = /*@__PURE__*/ new Vector3();
  9812. const _q1 = /*@__PURE__*/ new Quaternion();
  9813. const _m1$3 = /*@__PURE__*/ new Matrix4();
  9814. const _target = /*@__PURE__*/ new Vector3();
  9815. const _position$3 = /*@__PURE__*/ new Vector3();
  9816. const _scale$2 = /*@__PURE__*/ new Vector3();
  9817. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  9818. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  9819. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  9820. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  9821. /**
  9822. * Fires when the object has been added to its parent object.
  9823. *
  9824. * @event Object3D#added
  9825. * @type {Object}
  9826. */
  9827. const _addedEvent = { type: 'added' };
  9828. /**
  9829. * Fires when the object has been removed from its parent object.
  9830. *
  9831. * @event Object3D#removed
  9832. * @type {Object}
  9833. */
  9834. const _removedEvent = { type: 'removed' };
  9835. /**
  9836. * Fires when a new child object has been added.
  9837. *
  9838. * @event Object3D#childadded
  9839. * @type {Object}
  9840. */
  9841. const _childaddedEvent = { type: 'childadded', child: null };
  9842. /**
  9843. * Fires when a new child object has been added.
  9844. *
  9845. * @event Object3D#childremoved
  9846. * @type {Object}
  9847. */
  9848. const _childremovedEvent = { type: 'childremoved', child: null };
  9849. /**
  9850. * This is the base class for most objects in three.js and provides a set of
  9851. * properties and methods for manipulating objects in 3D space.
  9852. *
  9853. * @augments EventDispatcher
  9854. */
  9855. class Object3D extends EventDispatcher {
  9856. /**
  9857. * Constructs a new 3D object.
  9858. */
  9859. constructor() {
  9860. super();
  9861. /**
  9862. * This flag can be used for type testing.
  9863. *
  9864. * @type {boolean}
  9865. * @readonly
  9866. * @default true
  9867. */
  9868. this.isObject3D = true;
  9869. /**
  9870. * The ID of the 3D object.
  9871. *
  9872. * @name Object3D#id
  9873. * @type {number}
  9874. * @readonly
  9875. */
  9876. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  9877. /**
  9878. * The UUID of the 3D object.
  9879. *
  9880. * @type {string}
  9881. * @readonly
  9882. */
  9883. this.uuid = generateUUID();
  9884. /**
  9885. * The name of the 3D object.
  9886. *
  9887. * @type {string}
  9888. */
  9889. this.name = '';
  9890. /**
  9891. * The type property is used for detecting the object type
  9892. * in context of serialization/deserialization.
  9893. *
  9894. * @type {string}
  9895. * @readonly
  9896. */
  9897. this.type = 'Object3D';
  9898. /**
  9899. * A reference to the parent object.
  9900. *
  9901. * @type {?Object3D}
  9902. * @default null
  9903. */
  9904. this.parent = null;
  9905. /**
  9906. * An array holding the child 3D objects of this instance.
  9907. *
  9908. * @type {Array<Object3D>}
  9909. */
  9910. this.children = [];
  9911. /**
  9912. * Defines the `up` direction of the 3D object which influences
  9913. * the orientation via methods like {@link Object3D#lookAt}.
  9914. *
  9915. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  9916. *
  9917. * @type {Vector3}
  9918. */
  9919. this.up = Object3D.DEFAULT_UP.clone();
  9920. const position = new Vector3();
  9921. const rotation = new Euler();
  9922. const quaternion = new Quaternion();
  9923. const scale = new Vector3( 1, 1, 1 );
  9924. function onRotationChange() {
  9925. quaternion.setFromEuler( rotation, false );
  9926. }
  9927. function onQuaternionChange() {
  9928. rotation.setFromQuaternion( quaternion, undefined, false );
  9929. }
  9930. rotation._onChange( onRotationChange );
  9931. quaternion._onChange( onQuaternionChange );
  9932. Object.defineProperties( this, {
  9933. /**
  9934. * Represents the object's local position.
  9935. *
  9936. * @name Object3D#position
  9937. * @type {Vector3}
  9938. * @default (0,0,0)
  9939. */
  9940. position: {
  9941. configurable: true,
  9942. enumerable: true,
  9943. value: position
  9944. },
  9945. /**
  9946. * Represents the object's local rotation as Euler angles, in radians.
  9947. *
  9948. * @name Object3D#rotation
  9949. * @type {Euler}
  9950. * @default (0,0,0)
  9951. */
  9952. rotation: {
  9953. configurable: true,
  9954. enumerable: true,
  9955. value: rotation
  9956. },
  9957. /**
  9958. * Represents the object's local rotation as Quaternions.
  9959. *
  9960. * @name Object3D#quaternion
  9961. * @type {Quaternion}
  9962. */
  9963. quaternion: {
  9964. configurable: true,
  9965. enumerable: true,
  9966. value: quaternion
  9967. },
  9968. /**
  9969. * Represents the object's local scale.
  9970. *
  9971. * @name Object3D#scale
  9972. * @type {Vector3}
  9973. * @default (1,1,1)
  9974. */
  9975. scale: {
  9976. configurable: true,
  9977. enumerable: true,
  9978. value: scale
  9979. },
  9980. /**
  9981. * Represents the object's model-view matrix.
  9982. *
  9983. * @name Object3D#modelViewMatrix
  9984. * @type {Matrix4}
  9985. */
  9986. modelViewMatrix: {
  9987. value: new Matrix4()
  9988. },
  9989. /**
  9990. * Represents the object's normal matrix.
  9991. *
  9992. * @name Object3D#normalMatrix
  9993. * @type {Matrix3}
  9994. */
  9995. normalMatrix: {
  9996. value: new Matrix3()
  9997. }
  9998. } );
  9999. /**
  10000. * Represents the object's transformation matrix in local space.
  10001. *
  10002. * @type {Matrix4}
  10003. */
  10004. this.matrix = new Matrix4();
  10005. /**
  10006. * Represents the object's transformation matrix in world space.
  10007. * If the 3D object has no parent, then it's identical to the local transformation matrix
  10008. *
  10009. * @type {Matrix4}
  10010. */
  10011. this.matrixWorld = new Matrix4();
  10012. /**
  10013. * When set to `true`, the engine automatically computes the local matrix from position,
  10014. * rotation and scale every frame.
  10015. *
  10016. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  10017. *
  10018. * @type {boolean}
  10019. * @default true
  10020. */
  10021. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  10022. /**
  10023. * When set to `true`, the engine automatically computes the world matrix from the current local
  10024. * matrix and the object's transformation hierarchy.
  10025. *
  10026. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  10027. *
  10028. * @type {boolean}
  10029. * @default true
  10030. */
  10031. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  10032. /**
  10033. * When set to `true`, it calculates the world matrix in that frame and resets this property
  10034. * to `false`.
  10035. *
  10036. * @type {boolean}
  10037. * @default false
  10038. */
  10039. this.matrixWorldNeedsUpdate = false;
  10040. /**
  10041. * The layer membership of the 3D object. The 3D object is only visible if it has
  10042. * at least one layer in common with the camera in use. This property can also be
  10043. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  10044. *
  10045. * @type {Layers}
  10046. */
  10047. this.layers = new Layers();
  10048. /**
  10049. * When set to `true`, the 3D object gets rendered.
  10050. *
  10051. * @type {boolean}
  10052. * @default true
  10053. */
  10054. this.visible = true;
  10055. /**
  10056. * When set to `true`, the 3D object gets rendered into shadow maps.
  10057. *
  10058. * @type {boolean}
  10059. * @default false
  10060. */
  10061. this.castShadow = false;
  10062. /**
  10063. * When set to `true`, the 3D object is affected by shadows in the scene.
  10064. *
  10065. * @type {boolean}
  10066. * @default false
  10067. */
  10068. this.receiveShadow = false;
  10069. /**
  10070. * When set to `true`, the 3D object is honored by view frustum culling.
  10071. *
  10072. * @type {boolean}
  10073. * @default true
  10074. */
  10075. this.frustumCulled = true;
  10076. /**
  10077. * This value allows the default rendering order of scene graph objects to be
  10078. * overridden although opaque and transparent objects remain sorted independently.
  10079. * When this property is set for an instance of {@link Group},all descendants
  10080. * objects will be sorted and rendered together. Sorting is from lowest to highest
  10081. * render order.
  10082. *
  10083. * @type {number}
  10084. * @default 0
  10085. */
  10086. this.renderOrder = 0;
  10087. /**
  10088. * An array holding the animation clips of the 3D object.
  10089. *
  10090. * @type {Array<AnimationClip>}
  10091. */
  10092. this.animations = [];
  10093. /**
  10094. * Custom depth material to be used when rendering to the depth map. Can only be used
  10095. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  10096. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  10097. * material for proper shadows.
  10098. *
  10099. * Only relevant in context of {@link WebGLRenderer}.
  10100. *
  10101. * @type {(Material|undefined)}
  10102. * @default undefined
  10103. */
  10104. this.customDepthMaterial = undefined;
  10105. /**
  10106. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  10107. *
  10108. * Only relevant in context of {@link WebGLRenderer}.
  10109. *
  10110. * @type {(Material|undefined)}
  10111. * @default undefined
  10112. */
  10113. this.customDistanceMaterial = undefined;
  10114. /**
  10115. * An object that can be used to store custom data about the 3D object. It
  10116. * should not hold references to functions as these will not be cloned.
  10117. *
  10118. * @type {Object}
  10119. */
  10120. this.userData = {};
  10121. }
  10122. /**
  10123. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  10124. *
  10125. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10126. * @param {Object3D} object - The 3D object.
  10127. * @param {Camera} camera - The camera that is used to render the scene.
  10128. * @param {Camera} shadowCamera - The shadow camera.
  10129. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10130. * @param {Material} depthMaterial - The depth material.
  10131. * @param {Object} group - The geometry group data.
  10132. */
  10133. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10134. /**
  10135. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  10136. *
  10137. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10138. * @param {Object3D} object - The 3D object.
  10139. * @param {Camera} camera - The camera that is used to render the scene.
  10140. * @param {Camera} shadowCamera - The shadow camera.
  10141. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10142. * @param {Material} depthMaterial - The depth material.
  10143. * @param {Object} group - The geometry group data.
  10144. */
  10145. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10146. /**
  10147. * A callback that is executed immediately before a 3D object is rendered.
  10148. *
  10149. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10150. * @param {Object3D} object - The 3D object.
  10151. * @param {Camera} camera - The camera that is used to render the scene.
  10152. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10153. * @param {Material} material - The 3D object's material.
  10154. * @param {Object} group - The geometry group data.
  10155. */
  10156. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10157. /**
  10158. * A callback that is executed immediately after a 3D object is rendered.
  10159. *
  10160. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10161. * @param {Object3D} object - The 3D object.
  10162. * @param {Camera} camera - The camera that is used to render the scene.
  10163. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10164. * @param {Material} material - The 3D object's material.
  10165. * @param {Object} group - The geometry group data.
  10166. */
  10167. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10168. /**
  10169. * Applies the given transformation matrix to the object and updates the object's position,
  10170. * rotation and scale.
  10171. *
  10172. * @param {Matrix4} matrix - The transformation matrix.
  10173. */
  10174. applyMatrix4( matrix ) {
  10175. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10176. this.matrix.premultiply( matrix );
  10177. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10178. }
  10179. /**
  10180. * Applies a rotation represented by given the quaternion to the 3D object.
  10181. *
  10182. * @param {Quaternion} q - The quaternion.
  10183. * @return {Object3D} A reference to this instance.
  10184. */
  10185. applyQuaternion( q ) {
  10186. this.quaternion.premultiply( q );
  10187. return this;
  10188. }
  10189. /**
  10190. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  10191. *
  10192. * @param {Vector3} axis - The (normalized) axis vector.
  10193. * @param {number} angle - The angle in radians.
  10194. */
  10195. setRotationFromAxisAngle( axis, angle ) {
  10196. // assumes axis is normalized
  10197. this.quaternion.setFromAxisAngle( axis, angle );
  10198. }
  10199. /**
  10200. * Sets the given rotation represented as Euler angles to the 3D object.
  10201. *
  10202. * @param {Euler} euler - The Euler angles.
  10203. */
  10204. setRotationFromEuler( euler ) {
  10205. this.quaternion.setFromEuler( euler, true );
  10206. }
  10207. /**
  10208. * Sets the given rotation represented as rotation matrix to the 3D object.
  10209. *
  10210. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  10211. * a pure rotation matrix (i.e, unscaled).
  10212. */
  10213. setRotationFromMatrix( m ) {
  10214. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10215. this.quaternion.setFromRotationMatrix( m );
  10216. }
  10217. /**
  10218. * Sets the given rotation represented as a Quaternion to the 3D object.
  10219. *
  10220. * @param {Quaternion} q - The Quaternion
  10221. */
  10222. setRotationFromQuaternion( q ) {
  10223. // assumes q is normalized
  10224. this.quaternion.copy( q );
  10225. }
  10226. /**
  10227. * Rotates the 3D object along an axis in local space.
  10228. *
  10229. * @param {Vector3} axis - The (normalized) axis vector.
  10230. * @param {number} angle - The angle in radians.
  10231. * @return {Object3D} A reference to this instance.
  10232. */
  10233. rotateOnAxis( axis, angle ) {
  10234. // rotate object on axis in object space
  10235. // axis is assumed to be normalized
  10236. _q1.setFromAxisAngle( axis, angle );
  10237. this.quaternion.multiply( _q1 );
  10238. return this;
  10239. }
  10240. /**
  10241. * Rotates the 3D object along an axis in world space.
  10242. *
  10243. * @param {Vector3} axis - The (normalized) axis vector.
  10244. * @param {number} angle - The angle in radians.
  10245. * @return {Object3D} A reference to this instance.
  10246. */
  10247. rotateOnWorldAxis( axis, angle ) {
  10248. // rotate object on axis in world space
  10249. // axis is assumed to be normalized
  10250. // method assumes no rotated parent
  10251. _q1.setFromAxisAngle( axis, angle );
  10252. this.quaternion.premultiply( _q1 );
  10253. return this;
  10254. }
  10255. /**
  10256. * Rotates the 3D object around its X axis in local space.
  10257. *
  10258. * @param {number} angle - The angle in radians.
  10259. * @return {Object3D} A reference to this instance.
  10260. */
  10261. rotateX( angle ) {
  10262. return this.rotateOnAxis( _xAxis, angle );
  10263. }
  10264. /**
  10265. * Rotates the 3D object around its Y axis in local space.
  10266. *
  10267. * @param {number} angle - The angle in radians.
  10268. * @return {Object3D} A reference to this instance.
  10269. */
  10270. rotateY( angle ) {
  10271. return this.rotateOnAxis( _yAxis, angle );
  10272. }
  10273. /**
  10274. * Rotates the 3D object around its Z axis in local space.
  10275. *
  10276. * @param {number} angle - The angle in radians.
  10277. * @return {Object3D} A reference to this instance.
  10278. */
  10279. rotateZ( angle ) {
  10280. return this.rotateOnAxis( _zAxis, angle );
  10281. }
  10282. /**
  10283. * Translate the 3D object by a distance along the given axis in local space.
  10284. *
  10285. * @param {Vector3} axis - The (normalized) axis vector.
  10286. * @param {number} distance - The distance in world units.
  10287. * @return {Object3D} A reference to this instance.
  10288. */
  10289. translateOnAxis( axis, distance ) {
  10290. // translate object by distance along axis in object space
  10291. // axis is assumed to be normalized
  10292. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  10293. this.position.add( _v1$4.multiplyScalar( distance ) );
  10294. return this;
  10295. }
  10296. /**
  10297. * Translate the 3D object by a distance along its X-axis in local space.
  10298. *
  10299. * @param {number} distance - The distance in world units.
  10300. * @return {Object3D} A reference to this instance.
  10301. */
  10302. translateX( distance ) {
  10303. return this.translateOnAxis( _xAxis, distance );
  10304. }
  10305. /**
  10306. * Translate the 3D object by a distance along its Y-axis in local space.
  10307. *
  10308. * @param {number} distance - The distance in world units.
  10309. * @return {Object3D} A reference to this instance.
  10310. */
  10311. translateY( distance ) {
  10312. return this.translateOnAxis( _yAxis, distance );
  10313. }
  10314. /**
  10315. * Translate the 3D object by a distance along its Z-axis in local space.
  10316. *
  10317. * @param {number} distance - The distance in world units.
  10318. * @return {Object3D} A reference to this instance.
  10319. */
  10320. translateZ( distance ) {
  10321. return this.translateOnAxis( _zAxis, distance );
  10322. }
  10323. /**
  10324. * Converts the given vector from this 3D object's local space to world space.
  10325. *
  10326. * @param {Vector3} vector - The vector to convert.
  10327. * @return {Vector3} The converted vector.
  10328. */
  10329. localToWorld( vector ) {
  10330. this.updateWorldMatrix( true, false );
  10331. return vector.applyMatrix4( this.matrixWorld );
  10332. }
  10333. /**
  10334. * Converts the given vector from this 3D object's word space to local space.
  10335. *
  10336. * @param {Vector3} vector - The vector to convert.
  10337. * @return {Vector3} The converted vector.
  10338. */
  10339. worldToLocal( vector ) {
  10340. this.updateWorldMatrix( true, false );
  10341. return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() );
  10342. }
  10343. /**
  10344. * Rotates the object to face a point in world space.
  10345. *
  10346. * This method does not support objects having non-uniformly-scaled parent(s).
  10347. *
  10348. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  10349. * @param {number} [y] - The y coordinate in world space.
  10350. * @param {number} [z] - The z coordinate in world space.
  10351. */
  10352. lookAt( x, y, z ) {
  10353. // This method does not support objects having non-uniformly-scaled parent(s)
  10354. if ( x.isVector3 ) {
  10355. _target.copy( x );
  10356. } else {
  10357. _target.set( x, y, z );
  10358. }
  10359. const parent = this.parent;
  10360. this.updateWorldMatrix( true, false );
  10361. _position$3.setFromMatrixPosition( this.matrixWorld );
  10362. if ( this.isCamera || this.isLight ) {
  10363. _m1$3.lookAt( _position$3, _target, this.up );
  10364. } else {
  10365. _m1$3.lookAt( _target, _position$3, this.up );
  10366. }
  10367. this.quaternion.setFromRotationMatrix( _m1$3 );
  10368. if ( parent ) {
  10369. _m1$3.extractRotation( parent.matrixWorld );
  10370. _q1.setFromRotationMatrix( _m1$3 );
  10371. this.quaternion.premultiply( _q1.invert() );
  10372. }
  10373. }
  10374. /**
  10375. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  10376. * objects may be added. Any current parent on an object passed in here will be
  10377. * removed, since an object can have at most one parent.
  10378. *
  10379. * @fires Object3D#added
  10380. * @fires Object3D#childadded
  10381. * @param {Object3D} object - The 3D object to add.
  10382. * @return {Object3D} A reference to this instance.
  10383. */
  10384. add( object ) {
  10385. if ( arguments.length > 1 ) {
  10386. for ( let i = 0; i < arguments.length; i ++ ) {
  10387. this.add( arguments[ i ] );
  10388. }
  10389. return this;
  10390. }
  10391. if ( object === this ) {
  10392. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  10393. return this;
  10394. }
  10395. if ( object && object.isObject3D ) {
  10396. object.removeFromParent();
  10397. object.parent = this;
  10398. this.children.push( object );
  10399. object.dispatchEvent( _addedEvent );
  10400. _childaddedEvent.child = object;
  10401. this.dispatchEvent( _childaddedEvent );
  10402. _childaddedEvent.child = null;
  10403. } else {
  10404. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  10405. }
  10406. return this;
  10407. }
  10408. /**
  10409. * Removes the given 3D object as child from this 3D object.
  10410. * An arbitrary number of objects may be removed.
  10411. *
  10412. * @fires Object3D#removed
  10413. * @fires Object3D#childremoved
  10414. * @param {Object3D} object - The 3D object to remove.
  10415. * @return {Object3D} A reference to this instance.
  10416. */
  10417. remove( object ) {
  10418. if ( arguments.length > 1 ) {
  10419. for ( let i = 0; i < arguments.length; i ++ ) {
  10420. this.remove( arguments[ i ] );
  10421. }
  10422. return this;
  10423. }
  10424. const index = this.children.indexOf( object );
  10425. if ( index !== -1 ) {
  10426. object.parent = null;
  10427. this.children.splice( index, 1 );
  10428. object.dispatchEvent( _removedEvent );
  10429. _childremovedEvent.child = object;
  10430. this.dispatchEvent( _childremovedEvent );
  10431. _childremovedEvent.child = null;
  10432. }
  10433. return this;
  10434. }
  10435. /**
  10436. * Removes this 3D object from its current parent.
  10437. *
  10438. * @fires Object3D#removed
  10439. * @fires Object3D#childremoved
  10440. * @return {Object3D} A reference to this instance.
  10441. */
  10442. removeFromParent() {
  10443. const parent = this.parent;
  10444. if ( parent !== null ) {
  10445. parent.remove( this );
  10446. }
  10447. return this;
  10448. }
  10449. /**
  10450. * Removes all child objects.
  10451. *
  10452. * @fires Object3D#removed
  10453. * @fires Object3D#childremoved
  10454. * @return {Object3D} A reference to this instance.
  10455. */
  10456. clear() {
  10457. return this.remove( ... this.children );
  10458. }
  10459. /**
  10460. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  10461. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  10462. *
  10463. * @fires Object3D#added
  10464. * @fires Object3D#childadded
  10465. * @param {Object3D} object - The 3D object to attach.
  10466. * @return {Object3D} A reference to this instance.
  10467. */
  10468. attach( object ) {
  10469. // adds object as a child of this, while maintaining the object's world transform
  10470. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  10471. this.updateWorldMatrix( true, false );
  10472. _m1$3.copy( this.matrixWorld ).invert();
  10473. if ( object.parent !== null ) {
  10474. object.parent.updateWorldMatrix( true, false );
  10475. _m1$3.multiply( object.parent.matrixWorld );
  10476. }
  10477. object.applyMatrix4( _m1$3 );
  10478. object.removeFromParent();
  10479. object.parent = this;
  10480. this.children.push( object );
  10481. object.updateWorldMatrix( false, true );
  10482. object.dispatchEvent( _addedEvent );
  10483. _childaddedEvent.child = object;
  10484. this.dispatchEvent( _childaddedEvent );
  10485. _childaddedEvent.child = null;
  10486. return this;
  10487. }
  10488. /**
  10489. * Searches through the 3D object and its children, starting with the 3D object
  10490. * itself, and returns the first with a matching ID.
  10491. *
  10492. * @param {number} id - The id.
  10493. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10494. */
  10495. getObjectById( id ) {
  10496. return this.getObjectByProperty( 'id', id );
  10497. }
  10498. /**
  10499. * Searches through the 3D object and its children, starting with the 3D object
  10500. * itself, and returns the first with a matching name.
  10501. *
  10502. * @param {string} name - The name.
  10503. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10504. */
  10505. getObjectByName( name ) {
  10506. return this.getObjectByProperty( 'name', name );
  10507. }
  10508. /**
  10509. * Searches through the 3D object and its children, starting with the 3D object
  10510. * itself, and returns the first with a matching property value.
  10511. *
  10512. * @param {string} name - The name of the property.
  10513. * @param {any} value - The value.
  10514. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10515. */
  10516. getObjectByProperty( name, value ) {
  10517. if ( this[ name ] === value ) return this;
  10518. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  10519. const child = this.children[ i ];
  10520. const object = child.getObjectByProperty( name, value );
  10521. if ( object !== undefined ) {
  10522. return object;
  10523. }
  10524. }
  10525. return undefined;
  10526. }
  10527. /**
  10528. * Searches through the 3D object and its children, starting with the 3D object
  10529. * itself, and returns all 3D objects with a matching property value.
  10530. *
  10531. * @param {string} name - The name of the property.
  10532. * @param {any} value - The value.
  10533. * @param {Array<Object3D>} result - The method stores the result in this array.
  10534. * @return {Array<Object3D>} The found 3D objects.
  10535. */
  10536. getObjectsByProperty( name, value, result = [] ) {
  10537. if ( this[ name ] === value ) result.push( this );
  10538. const children = this.children;
  10539. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10540. children[ i ].getObjectsByProperty( name, value, result );
  10541. }
  10542. return result;
  10543. }
  10544. /**
  10545. * Returns a vector representing the position of the 3D object in world space.
  10546. *
  10547. * @param {Vector3} target - The target vector the result is stored to.
  10548. * @return {Vector3} The 3D object's position in world space.
  10549. */
  10550. getWorldPosition( target ) {
  10551. this.updateWorldMatrix( true, false );
  10552. return target.setFromMatrixPosition( this.matrixWorld );
  10553. }
  10554. /**
  10555. * Returns a Quaternion representing the position of the 3D object in world space.
  10556. *
  10557. * @param {Quaternion} target - The target Quaternion the result is stored to.
  10558. * @return {Quaternion} The 3D object's rotation in world space.
  10559. */
  10560. getWorldQuaternion( target ) {
  10561. this.updateWorldMatrix( true, false );
  10562. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  10563. return target;
  10564. }
  10565. /**
  10566. * Returns a vector representing the scale of the 3D object in world space.
  10567. *
  10568. * @param {Vector3} target - The target vector the result is stored to.
  10569. * @return {Vector3} The 3D object's scale in world space.
  10570. */
  10571. getWorldScale( target ) {
  10572. this.updateWorldMatrix( true, false );
  10573. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  10574. return target;
  10575. }
  10576. /**
  10577. * Returns a vector representing the ("look") direction of the 3D object in world space.
  10578. *
  10579. * @param {Vector3} target - The target vector the result is stored to.
  10580. * @return {Vector3} The 3D object's direction in world space.
  10581. */
  10582. getWorldDirection( target ) {
  10583. this.updateWorldMatrix( true, false );
  10584. const e = this.matrixWorld.elements;
  10585. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  10586. }
  10587. /**
  10588. * Abstract method to get intersections between a casted ray and this
  10589. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  10590. * implement this method in order to use raycasting.
  10591. *
  10592. * @abstract
  10593. * @param {Raycaster} raycaster - The raycaster.
  10594. * @param {Array<Object>} intersects - An array holding the result of the method.
  10595. */
  10596. raycast( /* raycaster, intersects */ ) {}
  10597. /**
  10598. * Executes the callback on this 3D object and all descendants.
  10599. *
  10600. * Note: Modifying the scene graph inside the callback is discouraged.
  10601. *
  10602. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10603. */
  10604. traverse( callback ) {
  10605. callback( this );
  10606. const children = this.children;
  10607. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10608. children[ i ].traverse( callback );
  10609. }
  10610. }
  10611. /**
  10612. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  10613. * Descendants of invisible 3D objects are not traversed.
  10614. *
  10615. * Note: Modifying the scene graph inside the callback is discouraged.
  10616. *
  10617. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10618. */
  10619. traverseVisible( callback ) {
  10620. if ( this.visible === false ) return;
  10621. callback( this );
  10622. const children = this.children;
  10623. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10624. children[ i ].traverseVisible( callback );
  10625. }
  10626. }
  10627. /**
  10628. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  10629. *
  10630. * Note: Modifying the scene graph inside the callback is discouraged.
  10631. *
  10632. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10633. */
  10634. traverseAncestors( callback ) {
  10635. const parent = this.parent;
  10636. if ( parent !== null ) {
  10637. callback( parent );
  10638. parent.traverseAncestors( callback );
  10639. }
  10640. }
  10641. /**
  10642. * Updates the transformation matrix in local space by computing it from the current
  10643. * position, rotation and scale values.
  10644. */
  10645. updateMatrix() {
  10646. this.matrix.compose( this.position, this.quaternion, this.scale );
  10647. this.matrixWorldNeedsUpdate = true;
  10648. }
  10649. /**
  10650. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  10651. *
  10652. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  10653. * local space. The computation of the local and world matrix can be controlled with the
  10654. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  10655. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  10656. *
  10657. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  10658. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  10659. */
  10660. updateMatrixWorld( force ) {
  10661. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10662. if ( this.matrixWorldNeedsUpdate || force ) {
  10663. if ( this.matrixWorldAutoUpdate === true ) {
  10664. if ( this.parent === null ) {
  10665. this.matrixWorld.copy( this.matrix );
  10666. } else {
  10667. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10668. }
  10669. }
  10670. this.matrixWorldNeedsUpdate = false;
  10671. force = true;
  10672. }
  10673. // make sure descendants are updated if required
  10674. const children = this.children;
  10675. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10676. const child = children[ i ];
  10677. child.updateMatrixWorld( force );
  10678. }
  10679. }
  10680. /**
  10681. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  10682. * update of ancestor and descendant nodes.
  10683. *
  10684. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  10685. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  10686. */
  10687. updateWorldMatrix( updateParents, updateChildren ) {
  10688. const parent = this.parent;
  10689. if ( updateParents === true && parent !== null ) {
  10690. parent.updateWorldMatrix( true, false );
  10691. }
  10692. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10693. if ( this.matrixWorldAutoUpdate === true ) {
  10694. if ( this.parent === null ) {
  10695. this.matrixWorld.copy( this.matrix );
  10696. } else {
  10697. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10698. }
  10699. }
  10700. // make sure descendants are updated
  10701. if ( updateChildren === true ) {
  10702. const children = this.children;
  10703. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10704. const child = children[ i ];
  10705. child.updateWorldMatrix( false, true );
  10706. }
  10707. }
  10708. }
  10709. /**
  10710. * Serializes the 3D object into JSON.
  10711. *
  10712. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  10713. * @return {Object} A JSON object representing the serialized 3D object.
  10714. * @see {@link ObjectLoader#parse}
  10715. */
  10716. toJSON( meta ) {
  10717. // meta is a string when called from JSON.stringify
  10718. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  10719. const output = {};
  10720. // meta is a hash used to collect geometries, materials.
  10721. // not providing it implies that this is the root object
  10722. // being serialized.
  10723. if ( isRootObject ) {
  10724. // initialize meta obj
  10725. meta = {
  10726. geometries: {},
  10727. materials: {},
  10728. textures: {},
  10729. images: {},
  10730. shapes: {},
  10731. skeletons: {},
  10732. animations: {},
  10733. nodes: {}
  10734. };
  10735. output.metadata = {
  10736. version: 4.6,
  10737. type: 'Object',
  10738. generator: 'Object3D.toJSON'
  10739. };
  10740. }
  10741. // standard Object3D serialization
  10742. const object = {};
  10743. object.uuid = this.uuid;
  10744. object.type = this.type;
  10745. if ( this.name !== '' ) object.name = this.name;
  10746. if ( this.castShadow === true ) object.castShadow = true;
  10747. if ( this.receiveShadow === true ) object.receiveShadow = true;
  10748. if ( this.visible === false ) object.visible = false;
  10749. if ( this.frustumCulled === false ) object.frustumCulled = false;
  10750. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  10751. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  10752. object.layers = this.layers.mask;
  10753. object.matrix = this.matrix.toArray();
  10754. object.up = this.up.toArray();
  10755. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  10756. // object specific properties
  10757. if ( this.isInstancedMesh ) {
  10758. object.type = 'InstancedMesh';
  10759. object.count = this.count;
  10760. object.instanceMatrix = this.instanceMatrix.toJSON();
  10761. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  10762. }
  10763. if ( this.isBatchedMesh ) {
  10764. object.type = 'BatchedMesh';
  10765. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  10766. object.sortObjects = this.sortObjects;
  10767. object.drawRanges = this._drawRanges;
  10768. object.reservedRanges = this._reservedRanges;
  10769. object.geometryInfo = this._geometryInfo.map( info => ( {
  10770. ...info,
  10771. boundingBox: info.boundingBox ? {
  10772. min: info.boundingBox.min.toArray(),
  10773. max: info.boundingBox.max.toArray()
  10774. } : undefined,
  10775. boundingSphere: info.boundingSphere ? {
  10776. radius: info.boundingSphere.radius,
  10777. center: info.boundingSphere.center.toArray()
  10778. } : undefined
  10779. } ) );
  10780. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  10781. object.availableInstanceIds = this._availableInstanceIds.slice();
  10782. object.availableGeometryIds = this._availableGeometryIds.slice();
  10783. object.nextIndexStart = this._nextIndexStart;
  10784. object.nextVertexStart = this._nextVertexStart;
  10785. object.geometryCount = this._geometryCount;
  10786. object.maxInstanceCount = this._maxInstanceCount;
  10787. object.maxVertexCount = this._maxVertexCount;
  10788. object.maxIndexCount = this._maxIndexCount;
  10789. object.geometryInitialized = this._geometryInitialized;
  10790. object.matricesTexture = this._matricesTexture.toJSON( meta );
  10791. object.indirectTexture = this._indirectTexture.toJSON( meta );
  10792. if ( this._colorsTexture !== null ) {
  10793. object.colorsTexture = this._colorsTexture.toJSON( meta );
  10794. }
  10795. if ( this.boundingSphere !== null ) {
  10796. object.boundingSphere = {
  10797. center: this.boundingSphere.center.toArray(),
  10798. radius: this.boundingSphere.radius
  10799. };
  10800. }
  10801. if ( this.boundingBox !== null ) {
  10802. object.boundingBox = {
  10803. min: this.boundingBox.min.toArray(),
  10804. max: this.boundingBox.max.toArray()
  10805. };
  10806. }
  10807. }
  10808. //
  10809. function serialize( library, element ) {
  10810. if ( library[ element.uuid ] === undefined ) {
  10811. library[ element.uuid ] = element.toJSON( meta );
  10812. }
  10813. return element.uuid;
  10814. }
  10815. if ( this.isScene ) {
  10816. if ( this.background ) {
  10817. if ( this.background.isColor ) {
  10818. object.background = this.background.toJSON();
  10819. } else if ( this.background.isTexture ) {
  10820. object.background = this.background.toJSON( meta ).uuid;
  10821. }
  10822. }
  10823. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  10824. object.environment = this.environment.toJSON( meta ).uuid;
  10825. }
  10826. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  10827. object.geometry = serialize( meta.geometries, this.geometry );
  10828. const parameters = this.geometry.parameters;
  10829. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  10830. const shapes = parameters.shapes;
  10831. if ( Array.isArray( shapes ) ) {
  10832. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  10833. const shape = shapes[ i ];
  10834. serialize( meta.shapes, shape );
  10835. }
  10836. } else {
  10837. serialize( meta.shapes, shapes );
  10838. }
  10839. }
  10840. }
  10841. if ( this.isSkinnedMesh ) {
  10842. object.bindMode = this.bindMode;
  10843. object.bindMatrix = this.bindMatrix.toArray();
  10844. if ( this.skeleton !== undefined ) {
  10845. serialize( meta.skeletons, this.skeleton );
  10846. object.skeleton = this.skeleton.uuid;
  10847. }
  10848. }
  10849. if ( this.material !== undefined ) {
  10850. if ( Array.isArray( this.material ) ) {
  10851. const uuids = [];
  10852. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  10853. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  10854. }
  10855. object.material = uuids;
  10856. } else {
  10857. object.material = serialize( meta.materials, this.material );
  10858. }
  10859. }
  10860. //
  10861. if ( this.children.length > 0 ) {
  10862. object.children = [];
  10863. for ( let i = 0; i < this.children.length; i ++ ) {
  10864. object.children.push( this.children[ i ].toJSON( meta ).object );
  10865. }
  10866. }
  10867. //
  10868. if ( this.animations.length > 0 ) {
  10869. object.animations = [];
  10870. for ( let i = 0; i < this.animations.length; i ++ ) {
  10871. const animation = this.animations[ i ];
  10872. object.animations.push( serialize( meta.animations, animation ) );
  10873. }
  10874. }
  10875. if ( isRootObject ) {
  10876. const geometries = extractFromCache( meta.geometries );
  10877. const materials = extractFromCache( meta.materials );
  10878. const textures = extractFromCache( meta.textures );
  10879. const images = extractFromCache( meta.images );
  10880. const shapes = extractFromCache( meta.shapes );
  10881. const skeletons = extractFromCache( meta.skeletons );
  10882. const animations = extractFromCache( meta.animations );
  10883. const nodes = extractFromCache( meta.nodes );
  10884. if ( geometries.length > 0 ) output.geometries = geometries;
  10885. if ( materials.length > 0 ) output.materials = materials;
  10886. if ( textures.length > 0 ) output.textures = textures;
  10887. if ( images.length > 0 ) output.images = images;
  10888. if ( shapes.length > 0 ) output.shapes = shapes;
  10889. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  10890. if ( animations.length > 0 ) output.animations = animations;
  10891. if ( nodes.length > 0 ) output.nodes = nodes;
  10892. }
  10893. output.object = object;
  10894. return output;
  10895. // extract data from the cache hash
  10896. // remove metadata on each item
  10897. // and return as array
  10898. function extractFromCache( cache ) {
  10899. const values = [];
  10900. for ( const key in cache ) {
  10901. const data = cache[ key ];
  10902. delete data.metadata;
  10903. values.push( data );
  10904. }
  10905. return values;
  10906. }
  10907. }
  10908. /**
  10909. * Returns a new 3D object with copied values from this instance.
  10910. *
  10911. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  10912. * @return {Object3D} A clone of this instance.
  10913. */
  10914. clone( recursive ) {
  10915. return new this.constructor().copy( this, recursive );
  10916. }
  10917. /**
  10918. * Copies the values of the given 3D object to this instance.
  10919. *
  10920. * @param {Object3D} source - The 3D object to copy.
  10921. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  10922. * @return {Object3D} A reference to this instance.
  10923. */
  10924. copy( source, recursive = true ) {
  10925. this.name = source.name;
  10926. this.up.copy( source.up );
  10927. this.position.copy( source.position );
  10928. this.rotation.order = source.rotation.order;
  10929. this.quaternion.copy( source.quaternion );
  10930. this.scale.copy( source.scale );
  10931. this.matrix.copy( source.matrix );
  10932. this.matrixWorld.copy( source.matrixWorld );
  10933. this.matrixAutoUpdate = source.matrixAutoUpdate;
  10934. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  10935. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  10936. this.layers.mask = source.layers.mask;
  10937. this.visible = source.visible;
  10938. this.castShadow = source.castShadow;
  10939. this.receiveShadow = source.receiveShadow;
  10940. this.frustumCulled = source.frustumCulled;
  10941. this.renderOrder = source.renderOrder;
  10942. this.animations = source.animations.slice();
  10943. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  10944. if ( recursive === true ) {
  10945. for ( let i = 0; i < source.children.length; i ++ ) {
  10946. const child = source.children[ i ];
  10947. this.add( child.clone() );
  10948. }
  10949. }
  10950. return this;
  10951. }
  10952. }
  10953. /**
  10954. * The default up direction for objects, also used as the default
  10955. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  10956. *
  10957. * @static
  10958. * @type {Vector3}
  10959. * @default (0,1,0)
  10960. */
  10961. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  10962. /**
  10963. * The default setting for {@link Object3D#matrixAutoUpdate} for
  10964. * newly created 3D objects.
  10965. *
  10966. * @static
  10967. * @type {boolean}
  10968. * @default true
  10969. */
  10970. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  10971. /**
  10972. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  10973. * newly created 3D objects.
  10974. *
  10975. * @static
  10976. * @type {boolean}
  10977. * @default true
  10978. */
  10979. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  10980. const _v0$2 = /*@__PURE__*/ new Vector3();
  10981. const _v1$3 = /*@__PURE__*/ new Vector3();
  10982. const _v2$2 = /*@__PURE__*/ new Vector3();
  10983. const _v3$2 = /*@__PURE__*/ new Vector3();
  10984. const _vab = /*@__PURE__*/ new Vector3();
  10985. const _vac = /*@__PURE__*/ new Vector3();
  10986. const _vbc = /*@__PURE__*/ new Vector3();
  10987. const _vap = /*@__PURE__*/ new Vector3();
  10988. const _vbp = /*@__PURE__*/ new Vector3();
  10989. const _vcp = /*@__PURE__*/ new Vector3();
  10990. const _v40 = /*@__PURE__*/ new Vector4();
  10991. const _v41 = /*@__PURE__*/ new Vector4();
  10992. const _v42 = /*@__PURE__*/ new Vector4();
  10993. /**
  10994. * A geometric triangle as defined by three vectors representing its three corners.
  10995. */
  10996. class Triangle {
  10997. /**
  10998. * Constructs a new triangle.
  10999. *
  11000. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11001. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11002. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11003. */
  11004. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11005. /**
  11006. * The first corner of the triangle.
  11007. *
  11008. * @type {Vector3}
  11009. */
  11010. this.a = a;
  11011. /**
  11012. * The second corner of the triangle.
  11013. *
  11014. * @type {Vector3}
  11015. */
  11016. this.b = b;
  11017. /**
  11018. * The third corner of the triangle.
  11019. *
  11020. * @type {Vector3}
  11021. */
  11022. this.c = c;
  11023. }
  11024. /**
  11025. * Computes the normal vector of a triangle.
  11026. *
  11027. * @param {Vector3} a - The first corner of the triangle.
  11028. * @param {Vector3} b - The second corner of the triangle.
  11029. * @param {Vector3} c - The third corner of the triangle.
  11030. * @param {Vector3} target - The target vector that is used to store the method's result.
  11031. * @return {Vector3} The triangle's normal.
  11032. */
  11033. static getNormal( a, b, c, target ) {
  11034. target.subVectors( c, b );
  11035. _v0$2.subVectors( a, b );
  11036. target.cross( _v0$2 );
  11037. const targetLengthSq = target.lengthSq();
  11038. if ( targetLengthSq > 0 ) {
  11039. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11040. }
  11041. return target.set( 0, 0, 0 );
  11042. }
  11043. /**
  11044. * Computes a barycentric coordinates from the given vector.
  11045. * Returns `null` if the triangle is degenerate.
  11046. *
  11047. * @param {Vector3} point - A point in 3D space.
  11048. * @param {Vector3} a - The first corner of the triangle.
  11049. * @param {Vector3} b - The second corner of the triangle.
  11050. * @param {Vector3} c - The third corner of the triangle.
  11051. * @param {Vector3} target - The target vector that is used to store the method's result.
  11052. * @return {?Vector3} The barycentric coordinates for the given point
  11053. */
  11054. static getBarycoord( point, a, b, c, target ) {
  11055. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11056. _v0$2.subVectors( c, a );
  11057. _v1$3.subVectors( b, a );
  11058. _v2$2.subVectors( point, a );
  11059. const dot00 = _v0$2.dot( _v0$2 );
  11060. const dot01 = _v0$2.dot( _v1$3 );
  11061. const dot02 = _v0$2.dot( _v2$2 );
  11062. const dot11 = _v1$3.dot( _v1$3 );
  11063. const dot12 = _v1$3.dot( _v2$2 );
  11064. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11065. // collinear or singular triangle
  11066. if ( denom === 0 ) {
  11067. target.set( 0, 0, 0 );
  11068. return null;
  11069. }
  11070. const invDenom = 1 / denom;
  11071. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11072. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11073. // barycentric coordinates must always sum to 1
  11074. return target.set( 1 - u - v, v, u );
  11075. }
  11076. /**
  11077. * Returns `true` if the given point, when projected onto the plane of the
  11078. * triangle, lies within the triangle.
  11079. *
  11080. * @param {Vector3} point - The point in 3D space to test.
  11081. * @param {Vector3} a - The first corner of the triangle.
  11082. * @param {Vector3} b - The second corner of the triangle.
  11083. * @param {Vector3} c - The third corner of the triangle.
  11084. * @return {boolean} Whether the given point, when projected onto the plane of the
  11085. * triangle, lies within the triangle or not.
  11086. */
  11087. static containsPoint( point, a, b, c ) {
  11088. // if the triangle is degenerate then we can't contain a point
  11089. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11090. return false;
  11091. }
  11092. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11093. }
  11094. /**
  11095. * Computes the value barycentrically interpolated for the given point on the
  11096. * triangle. Returns `null` if the triangle is degenerate.
  11097. *
  11098. * @param {Vector3} point - Position of interpolated point.
  11099. * @param {Vector3} p1 - The first corner of the triangle.
  11100. * @param {Vector3} p2 - The second corner of the triangle.
  11101. * @param {Vector3} p3 - The third corner of the triangle.
  11102. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11103. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11104. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11105. * @param {Vector3} target - The target vector that is used to store the method's result.
  11106. * @return {?Vector3} The interpolated value.
  11107. */
  11108. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11109. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11110. target.x = 0;
  11111. target.y = 0;
  11112. if ( 'z' in target ) target.z = 0;
  11113. if ( 'w' in target ) target.w = 0;
  11114. return null;
  11115. }
  11116. target.setScalar( 0 );
  11117. target.addScaledVector( v1, _v3$2.x );
  11118. target.addScaledVector( v2, _v3$2.y );
  11119. target.addScaledVector( v3, _v3$2.z );
  11120. return target;
  11121. }
  11122. /**
  11123. * Computes the value barycentrically interpolated for the given attribute and indices.
  11124. *
  11125. * @param {BufferAttribute} attr - The attribute to interpolate.
  11126. * @param {number} i1 - Index of first vertex.
  11127. * @param {number} i2 - Index of second vertex.
  11128. * @param {number} i3 - Index of third vertex.
  11129. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11130. * @param {Vector3} target - The target vector that is used to store the method's result.
  11131. * @return {Vector3} The interpolated attribute value.
  11132. */
  11133. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11134. _v40.setScalar( 0 );
  11135. _v41.setScalar( 0 );
  11136. _v42.setScalar( 0 );
  11137. _v40.fromBufferAttribute( attr, i1 );
  11138. _v41.fromBufferAttribute( attr, i2 );
  11139. _v42.fromBufferAttribute( attr, i3 );
  11140. target.setScalar( 0 );
  11141. target.addScaledVector( _v40, barycoord.x );
  11142. target.addScaledVector( _v41, barycoord.y );
  11143. target.addScaledVector( _v42, barycoord.z );
  11144. return target;
  11145. }
  11146. /**
  11147. * Returns `true` if the triangle is oriented towards the given direction.
  11148. *
  11149. * @param {Vector3} a - The first corner of the triangle.
  11150. * @param {Vector3} b - The second corner of the triangle.
  11151. * @param {Vector3} c - The third corner of the triangle.
  11152. * @param {Vector3} direction - The (normalized) direction vector.
  11153. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11154. */
  11155. static isFrontFacing( a, b, c, direction ) {
  11156. _v0$2.subVectors( c, b );
  11157. _v1$3.subVectors( a, b );
  11158. // strictly front facing
  11159. return ( _v0$2.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  11160. }
  11161. /**
  11162. * Sets the triangle's vertices by copying the given values.
  11163. *
  11164. * @param {Vector3} a - The first corner of the triangle.
  11165. * @param {Vector3} b - The second corner of the triangle.
  11166. * @param {Vector3} c - The third corner of the triangle.
  11167. * @return {Triangle} A reference to this triangle.
  11168. */
  11169. set( a, b, c ) {
  11170. this.a.copy( a );
  11171. this.b.copy( b );
  11172. this.c.copy( c );
  11173. return this;
  11174. }
  11175. /**
  11176. * Sets the triangle's vertices by copying the given array values.
  11177. *
  11178. * @param {Array<Vector3>} points - An array with 3D points.
  11179. * @param {number} i0 - The array index representing the first corner of the triangle.
  11180. * @param {number} i1 - The array index representing the second corner of the triangle.
  11181. * @param {number} i2 - The array index representing the third corner of the triangle.
  11182. * @return {Triangle} A reference to this triangle.
  11183. */
  11184. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11185. this.a.copy( points[ i0 ] );
  11186. this.b.copy( points[ i1 ] );
  11187. this.c.copy( points[ i2 ] );
  11188. return this;
  11189. }
  11190. /**
  11191. * Sets the triangle's vertices by copying the given attribute values.
  11192. *
  11193. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11194. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11195. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11196. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11197. * @return {Triangle} A reference to this triangle.
  11198. */
  11199. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11200. this.a.fromBufferAttribute( attribute, i0 );
  11201. this.b.fromBufferAttribute( attribute, i1 );
  11202. this.c.fromBufferAttribute( attribute, i2 );
  11203. return this;
  11204. }
  11205. /**
  11206. * Returns a new triangle with copied values from this instance.
  11207. *
  11208. * @return {Triangle} A clone of this instance.
  11209. */
  11210. clone() {
  11211. return new this.constructor().copy( this );
  11212. }
  11213. /**
  11214. * Copies the values of the given triangle to this instance.
  11215. *
  11216. * @param {Triangle} triangle - The triangle to copy.
  11217. * @return {Triangle} A reference to this triangle.
  11218. */
  11219. copy( triangle ) {
  11220. this.a.copy( triangle.a );
  11221. this.b.copy( triangle.b );
  11222. this.c.copy( triangle.c );
  11223. return this;
  11224. }
  11225. /**
  11226. * Computes the area of the triangle.
  11227. *
  11228. * @return {number} The triangle's area.
  11229. */
  11230. getArea() {
  11231. _v0$2.subVectors( this.c, this.b );
  11232. _v1$3.subVectors( this.a, this.b );
  11233. return _v0$2.cross( _v1$3 ).length() * 0.5;
  11234. }
  11235. /**
  11236. * Computes the midpoint of the triangle.
  11237. *
  11238. * @param {Vector3} target - The target vector that is used to store the method's result.
  11239. * @return {Vector3} The triangle's midpoint.
  11240. */
  11241. getMidpoint( target ) {
  11242. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11243. }
  11244. /**
  11245. * Computes the normal of the triangle.
  11246. *
  11247. * @param {Vector3} target - The target vector that is used to store the method's result.
  11248. * @return {Vector3} The triangle's normal.
  11249. */
  11250. getNormal( target ) {
  11251. return Triangle.getNormal( this.a, this.b, this.c, target );
  11252. }
  11253. /**
  11254. * Computes a plane the triangle lies within.
  11255. *
  11256. * @param {Plane} target - The target vector that is used to store the method's result.
  11257. * @return {Plane} The plane the triangle lies within.
  11258. */
  11259. getPlane( target ) {
  11260. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11261. }
  11262. /**
  11263. * Computes a barycentric coordinates from the given vector.
  11264. * Returns `null` if the triangle is degenerate.
  11265. *
  11266. * @param {Vector3} point - A point in 3D space.
  11267. * @param {Vector3} target - The target vector that is used to store the method's result.
  11268. * @return {?Vector3} The barycentric coordinates for the given point
  11269. */
  11270. getBarycoord( point, target ) {
  11271. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11272. }
  11273. /**
  11274. * Computes the value barycentrically interpolated for the given point on the
  11275. * triangle. Returns `null` if the triangle is degenerate.
  11276. *
  11277. * @param {Vector3} point - Position of interpolated point.
  11278. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11279. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11280. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11281. * @param {Vector3} target - The target vector that is used to store the method's result.
  11282. * @return {?Vector3} The interpolated value.
  11283. */
  11284. getInterpolation( point, v1, v2, v3, target ) {
  11285. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11286. }
  11287. /**
  11288. * Returns `true` if the given point, when projected onto the plane of the
  11289. * triangle, lies within the triangle.
  11290. *
  11291. * @param {Vector3} point - The point in 3D space to test.
  11292. * @return {boolean} Whether the given point, when projected onto the plane of the
  11293. * triangle, lies within the triangle or not.
  11294. */
  11295. containsPoint( point ) {
  11296. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11297. }
  11298. /**
  11299. * Returns `true` if the triangle is oriented towards the given direction.
  11300. *
  11301. * @param {Vector3} direction - The (normalized) direction vector.
  11302. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11303. */
  11304. isFrontFacing( direction ) {
  11305. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11306. }
  11307. /**
  11308. * Returns `true` if this triangle intersects with the given box.
  11309. *
  11310. * @param {Box3} box - The box to intersect.
  11311. * @return {boolean} Whether this triangle intersects with the given box or not.
  11312. */
  11313. intersectsBox( box ) {
  11314. return box.intersectsTriangle( this );
  11315. }
  11316. /**
  11317. * Returns the closest point on the triangle to the given point.
  11318. *
  11319. * @param {Vector3} p - The point to compute the closest point for.
  11320. * @param {Vector3} target - The target vector that is used to store the method's result.
  11321. * @return {Vector3} The closest point on the triangle.
  11322. */
  11323. closestPointToPoint( p, target ) {
  11324. const a = this.a, b = this.b, c = this.c;
  11325. let v, w;
  11326. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11327. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11328. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11329. // basically, we're distinguishing which of the voronoi regions of the triangle
  11330. // the point lies in with the minimum amount of redundant computation.
  11331. _vab.subVectors( b, a );
  11332. _vac.subVectors( c, a );
  11333. _vap.subVectors( p, a );
  11334. const d1 = _vab.dot( _vap );
  11335. const d2 = _vac.dot( _vap );
  11336. if ( d1 <= 0 && d2 <= 0 ) {
  11337. // vertex region of A; barycentric coords (1, 0, 0)
  11338. return target.copy( a );
  11339. }
  11340. _vbp.subVectors( p, b );
  11341. const d3 = _vab.dot( _vbp );
  11342. const d4 = _vac.dot( _vbp );
  11343. if ( d3 >= 0 && d4 <= d3 ) {
  11344. // vertex region of B; barycentric coords (0, 1, 0)
  11345. return target.copy( b );
  11346. }
  11347. const vc = d1 * d4 - d3 * d2;
  11348. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11349. v = d1 / ( d1 - d3 );
  11350. // edge region of AB; barycentric coords (1-v, v, 0)
  11351. return target.copy( a ).addScaledVector( _vab, v );
  11352. }
  11353. _vcp.subVectors( p, c );
  11354. const d5 = _vab.dot( _vcp );
  11355. const d6 = _vac.dot( _vcp );
  11356. if ( d6 >= 0 && d5 <= d6 ) {
  11357. // vertex region of C; barycentric coords (0, 0, 1)
  11358. return target.copy( c );
  11359. }
  11360. const vb = d5 * d2 - d1 * d6;
  11361. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11362. w = d2 / ( d2 - d6 );
  11363. // edge region of AC; barycentric coords (1-w, 0, w)
  11364. return target.copy( a ).addScaledVector( _vac, w );
  11365. }
  11366. const va = d3 * d6 - d5 * d4;
  11367. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11368. _vbc.subVectors( c, b );
  11369. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11370. // edge region of BC; barycentric coords (0, 1-w, w)
  11371. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11372. }
  11373. // face region
  11374. const denom = 1 / ( va + vb + vc );
  11375. // u = va * denom
  11376. v = vb * denom;
  11377. w = vc * denom;
  11378. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11379. }
  11380. /**
  11381. * Returns `true` if this triangle is equal with the given one.
  11382. *
  11383. * @param {Triangle} triangle - The triangle to test for equality.
  11384. * @return {boolean} Whether this triangle is equal with the given one.
  11385. */
  11386. equals( triangle ) {
  11387. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11388. }
  11389. }
  11390. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  11391. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  11392. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  11393. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  11394. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  11395. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  11396. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  11397. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  11398. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  11399. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  11400. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  11401. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  11402. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  11403. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  11404. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  11405. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  11406. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  11407. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  11408. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  11409. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  11410. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  11411. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  11412. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  11413. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  11414. const _hslA = { h: 0, s: 0, l: 0 };
  11415. const _hslB = { h: 0, s: 0, l: 0 };
  11416. function hue2rgb( p, q, t ) {
  11417. if ( t < 0 ) t += 1;
  11418. if ( t > 1 ) t -= 1;
  11419. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  11420. if ( t < 1 / 2 ) return q;
  11421. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  11422. return p;
  11423. }
  11424. /**
  11425. * A Color instance is represented by RGB components in the linear <i>working
  11426. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  11427. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  11428. * strings) are converted to the working color space automatically.
  11429. *
  11430. * ```js
  11431. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  11432. * const color = new THREE.Color().setHex( 0x112233 );
  11433. * ```
  11434. * Source color spaces may be specified explicitly, to ensure correct conversions.
  11435. * ```js
  11436. * // assumed already LinearSRGBColorSpace; no conversion
  11437. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  11438. *
  11439. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  11440. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  11441. * ```
  11442. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  11443. * see <i>Color management</i>. Iterating through a Color instance will yield
  11444. * its components (r, g, b) in the corresponding order. A Color can be initialised
  11445. * in any of the following ways:
  11446. * ```js
  11447. * //empty constructor - will default white
  11448. * const color1 = new THREE.Color();
  11449. *
  11450. * //Hexadecimal color (recommended)
  11451. * const color2 = new THREE.Color( 0xff0000 );
  11452. *
  11453. * //RGB string
  11454. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  11455. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  11456. *
  11457. * //X11 color name - all 140 color names are supported.
  11458. * //Note the lack of CamelCase in the name
  11459. * const color5 = new THREE.Color( 'skyblue' );
  11460. * //HSL string
  11461. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  11462. *
  11463. * //Separate RGB values between 0 and 1
  11464. * const color7 = new THREE.Color( 1, 0, 0 );
  11465. * ```
  11466. */
  11467. class Color {
  11468. /**
  11469. * Constructs a new color.
  11470. *
  11471. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  11472. * and that method is used throughout the rest of the documentation.
  11473. *
  11474. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11475. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11476. * @param {number} [g] - The green component.
  11477. * @param {number} [b] - The blue component.
  11478. */
  11479. constructor( r, g, b ) {
  11480. /**
  11481. * This flag can be used for type testing.
  11482. *
  11483. * @type {boolean}
  11484. * @readonly
  11485. * @default true
  11486. */
  11487. this.isColor = true;
  11488. /**
  11489. * The red component.
  11490. *
  11491. * @type {number}
  11492. * @default 1
  11493. */
  11494. this.r = 1;
  11495. /**
  11496. * The green component.
  11497. *
  11498. * @type {number}
  11499. * @default 1
  11500. */
  11501. this.g = 1;
  11502. /**
  11503. * The blue component.
  11504. *
  11505. * @type {number}
  11506. * @default 1
  11507. */
  11508. this.b = 1;
  11509. return this.set( r, g, b );
  11510. }
  11511. /**
  11512. * Sets the colors's components from the given values.
  11513. *
  11514. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11515. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11516. * @param {number} [g] - The green component.
  11517. * @param {number} [b] - The blue component.
  11518. * @return {Color} A reference to this color.
  11519. */
  11520. set( r, g, b ) {
  11521. if ( g === undefined && b === undefined ) {
  11522. // r is THREE.Color, hex or string
  11523. const value = r;
  11524. if ( value && value.isColor ) {
  11525. this.copy( value );
  11526. } else if ( typeof value === 'number' ) {
  11527. this.setHex( value );
  11528. } else if ( typeof value === 'string' ) {
  11529. this.setStyle( value );
  11530. }
  11531. } else {
  11532. this.setRGB( r, g, b );
  11533. }
  11534. return this;
  11535. }
  11536. /**
  11537. * Sets the colors's components to the given scalar value.
  11538. *
  11539. * @param {number} scalar - The scalar value.
  11540. * @return {Color} A reference to this color.
  11541. */
  11542. setScalar( scalar ) {
  11543. this.r = scalar;
  11544. this.g = scalar;
  11545. this.b = scalar;
  11546. return this;
  11547. }
  11548. /**
  11549. * Sets this color from a hexadecimal value.
  11550. *
  11551. * @param {number} hex - The hexadecimal value.
  11552. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11553. * @return {Color} A reference to this color.
  11554. */
  11555. setHex( hex, colorSpace = SRGBColorSpace ) {
  11556. hex = Math.floor( hex );
  11557. this.r = ( hex >> 16 & 255 ) / 255;
  11558. this.g = ( hex >> 8 & 255 ) / 255;
  11559. this.b = ( hex & 255 ) / 255;
  11560. ColorManagement.toWorkingColorSpace( this, colorSpace );
  11561. return this;
  11562. }
  11563. /**
  11564. * Sets this color from RGB values.
  11565. *
  11566. * @param {number} r - Red channel value between `0.0` and `1.0`.
  11567. * @param {number} g - Green channel value between `0.0` and `1.0`.
  11568. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  11569. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11570. * @return {Color} A reference to this color.
  11571. */
  11572. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  11573. this.r = r;
  11574. this.g = g;
  11575. this.b = b;
  11576. ColorManagement.toWorkingColorSpace( this, colorSpace );
  11577. return this;
  11578. }
  11579. /**
  11580. * Sets this color from RGB values.
  11581. *
  11582. * @param {number} h - Hue value between `0.0` and `1.0`.
  11583. * @param {number} s - Saturation value between `0.0` and `1.0`.
  11584. * @param {number} l - Lightness value between `0.0` and `1.0`.
  11585. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11586. * @return {Color} A reference to this color.
  11587. */
  11588. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  11589. // h,s,l ranges are in 0.0 - 1.0
  11590. h = euclideanModulo( h, 1 );
  11591. s = clamp( s, 0, 1 );
  11592. l = clamp( l, 0, 1 );
  11593. if ( s === 0 ) {
  11594. this.r = this.g = this.b = l;
  11595. } else {
  11596. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  11597. const q = ( 2 * l ) - p;
  11598. this.r = hue2rgb( q, p, h + 1 / 3 );
  11599. this.g = hue2rgb( q, p, h );
  11600. this.b = hue2rgb( q, p, h - 1 / 3 );
  11601. }
  11602. ColorManagement.toWorkingColorSpace( this, colorSpace );
  11603. return this;
  11604. }
  11605. /**
  11606. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  11607. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  11608. * any [X11 color name]{@link https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart} -
  11609. * all 140 color names are supported).
  11610. *
  11611. * @param {string} style - Color as a CSS-style string.
  11612. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11613. * @return {Color} A reference to this color.
  11614. */
  11615. setStyle( style, colorSpace = SRGBColorSpace ) {
  11616. function handleAlpha( string ) {
  11617. if ( string === undefined ) return;
  11618. if ( parseFloat( string ) < 1 ) {
  11619. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  11620. }
  11621. }
  11622. let m;
  11623. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  11624. // rgb / hsl
  11625. let color;
  11626. const name = m[ 1 ];
  11627. const components = m[ 2 ];
  11628. switch ( name ) {
  11629. case 'rgb':
  11630. case 'rgba':
  11631. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11632. // rgb(255,0,0) rgba(255,0,0,0.5)
  11633. handleAlpha( color[ 4 ] );
  11634. return this.setRGB(
  11635. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  11636. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  11637. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  11638. colorSpace
  11639. );
  11640. }
  11641. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11642. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  11643. handleAlpha( color[ 4 ] );
  11644. return this.setRGB(
  11645. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  11646. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  11647. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  11648. colorSpace
  11649. );
  11650. }
  11651. break;
  11652. case 'hsl':
  11653. case 'hsla':
  11654. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11655. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  11656. handleAlpha( color[ 4 ] );
  11657. return this.setHSL(
  11658. parseFloat( color[ 1 ] ) / 360,
  11659. parseFloat( color[ 2 ] ) / 100,
  11660. parseFloat( color[ 3 ] ) / 100,
  11661. colorSpace
  11662. );
  11663. }
  11664. break;
  11665. default:
  11666. console.warn( 'THREE.Color: Unknown color model ' + style );
  11667. }
  11668. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  11669. // hex color
  11670. const hex = m[ 1 ];
  11671. const size = hex.length;
  11672. if ( size === 3 ) {
  11673. // #ff0
  11674. return this.setRGB(
  11675. parseInt( hex.charAt( 0 ), 16 ) / 15,
  11676. parseInt( hex.charAt( 1 ), 16 ) / 15,
  11677. parseInt( hex.charAt( 2 ), 16 ) / 15,
  11678. colorSpace
  11679. );
  11680. } else if ( size === 6 ) {
  11681. // #ff0000
  11682. return this.setHex( parseInt( hex, 16 ), colorSpace );
  11683. } else {
  11684. console.warn( 'THREE.Color: Invalid hex color ' + style );
  11685. }
  11686. } else if ( style && style.length > 0 ) {
  11687. return this.setColorName( style, colorSpace );
  11688. }
  11689. return this;
  11690. }
  11691. /**
  11692. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  11693. * you don't need the other CSS-style formats.
  11694. *
  11695. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  11696. * ```js
  11697. * Color.NAMES.aliceblue // returns 0xF0F8FF
  11698. * ```
  11699. *
  11700. * @param {string} style - The color name.
  11701. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11702. * @return {Color} A reference to this color.
  11703. */
  11704. setColorName( style, colorSpace = SRGBColorSpace ) {
  11705. // color keywords
  11706. const hex = _colorKeywords[ style.toLowerCase() ];
  11707. if ( hex !== undefined ) {
  11708. // red
  11709. this.setHex( hex, colorSpace );
  11710. } else {
  11711. // unknown color
  11712. console.warn( 'THREE.Color: Unknown color ' + style );
  11713. }
  11714. return this;
  11715. }
  11716. /**
  11717. * Returns a new color with copied values from this instance.
  11718. *
  11719. * @return {Color} A clone of this instance.
  11720. */
  11721. clone() {
  11722. return new this.constructor( this.r, this.g, this.b );
  11723. }
  11724. /**
  11725. * Copies the values of the given color to this instance.
  11726. *
  11727. * @param {Color} color - The color to copy.
  11728. * @return {Color} A reference to this color.
  11729. */
  11730. copy( color ) {
  11731. this.r = color.r;
  11732. this.g = color.g;
  11733. this.b = color.b;
  11734. return this;
  11735. }
  11736. /**
  11737. * Copies the given color into this color, and then converts this color from
  11738. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11739. *
  11740. * @param {Color} color - The color to copy/convert.
  11741. * @return {Color} A reference to this color.
  11742. */
  11743. copySRGBToLinear( color ) {
  11744. this.r = SRGBToLinear( color.r );
  11745. this.g = SRGBToLinear( color.g );
  11746. this.b = SRGBToLinear( color.b );
  11747. return this;
  11748. }
  11749. /**
  11750. * Copies the given color into this color, and then converts this color from
  11751. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11752. *
  11753. * @param {Color} color - The color to copy/convert.
  11754. * @return {Color} A reference to this color.
  11755. */
  11756. copyLinearToSRGB( color ) {
  11757. this.r = LinearToSRGB( color.r );
  11758. this.g = LinearToSRGB( color.g );
  11759. this.b = LinearToSRGB( color.b );
  11760. return this;
  11761. }
  11762. /**
  11763. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11764. *
  11765. * @return {Color} A reference to this color.
  11766. */
  11767. convertSRGBToLinear() {
  11768. this.copySRGBToLinear( this );
  11769. return this;
  11770. }
  11771. /**
  11772. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11773. *
  11774. * @return {Color} A reference to this color.
  11775. */
  11776. convertLinearToSRGB() {
  11777. this.copyLinearToSRGB( this );
  11778. return this;
  11779. }
  11780. /**
  11781. * Returns the hexadecimal value of this color.
  11782. *
  11783. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11784. * @return {number} The hexadecimal value.
  11785. */
  11786. getHex( colorSpace = SRGBColorSpace ) {
  11787. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  11788. 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 ) );
  11789. }
  11790. /**
  11791. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  11792. *
  11793. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11794. * @return {string} The hexadecimal value as a string.
  11795. */
  11796. getHexString( colorSpace = SRGBColorSpace ) {
  11797. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  11798. }
  11799. /**
  11800. * Converts the colors RGB values into the HSL format and stores them into the
  11801. * given target object.
  11802. *
  11803. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  11804. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11805. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  11806. */
  11807. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  11808. // h,s,l ranges are in 0.0 - 1.0
  11809. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  11810. const r = _color.r, g = _color.g, b = _color.b;
  11811. const max = Math.max( r, g, b );
  11812. const min = Math.min( r, g, b );
  11813. let hue, saturation;
  11814. const lightness = ( min + max ) / 2.0;
  11815. if ( min === max ) {
  11816. hue = 0;
  11817. saturation = 0;
  11818. } else {
  11819. const delta = max - min;
  11820. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  11821. switch ( max ) {
  11822. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  11823. case g: hue = ( b - r ) / delta + 2; break;
  11824. case b: hue = ( r - g ) / delta + 4; break;
  11825. }
  11826. hue /= 6;
  11827. }
  11828. target.h = hue;
  11829. target.s = saturation;
  11830. target.l = lightness;
  11831. return target;
  11832. }
  11833. /**
  11834. * Returns the RGB values of this color and stores them into the given target object.
  11835. *
  11836. * @param {Color} target - The target color that is used to store the method's result.
  11837. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11838. * @return {Color} The RGB representation of this color.
  11839. */
  11840. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  11841. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  11842. target.r = _color.r;
  11843. target.g = _color.g;
  11844. target.b = _color.b;
  11845. return target;
  11846. }
  11847. /**
  11848. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  11849. *
  11850. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11851. * @return {string} The CSS representation of this color.
  11852. */
  11853. getStyle( colorSpace = SRGBColorSpace ) {
  11854. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  11855. const r = _color.r, g = _color.g, b = _color.b;
  11856. if ( colorSpace !== SRGBColorSpace ) {
  11857. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  11858. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  11859. }
  11860. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  11861. }
  11862. /**
  11863. * Adds the given HSL values to this color's values.
  11864. * Internally, this converts the color's RGB values to HSL, adds HSL
  11865. * and then converts the color back to RGB.
  11866. *
  11867. * @param {number} h - Hue value between `0.0` and `1.0`.
  11868. * @param {number} s - Saturation value between `0.0` and `1.0`.
  11869. * @param {number} l - Lightness value between `0.0` and `1.0`.
  11870. * @return {Color} A reference to this color.
  11871. */
  11872. offsetHSL( h, s, l ) {
  11873. this.getHSL( _hslA );
  11874. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  11875. }
  11876. /**
  11877. * Adds the RGB values of the given color to the RGB values of this color.
  11878. *
  11879. * @param {Color} color - The color to add.
  11880. * @return {Color} A reference to this color.
  11881. */
  11882. add( color ) {
  11883. this.r += color.r;
  11884. this.g += color.g;
  11885. this.b += color.b;
  11886. return this;
  11887. }
  11888. /**
  11889. * Adds the RGB values of the given colors and stores the result in this instance.
  11890. *
  11891. * @param {Color} color1 - The first color.
  11892. * @param {Color} color2 - The second color.
  11893. * @return {Color} A reference to this color.
  11894. */
  11895. addColors( color1, color2 ) {
  11896. this.r = color1.r + color2.r;
  11897. this.g = color1.g + color2.g;
  11898. this.b = color1.b + color2.b;
  11899. return this;
  11900. }
  11901. /**
  11902. * Adds the given scalar value to the RGB values of this color.
  11903. *
  11904. * @param {number} s - The scalar to add.
  11905. * @return {Color} A reference to this color.
  11906. */
  11907. addScalar( s ) {
  11908. this.r += s;
  11909. this.g += s;
  11910. this.b += s;
  11911. return this;
  11912. }
  11913. /**
  11914. * Subtracts the RGB values of the given color from the RGB values of this color.
  11915. *
  11916. * @param {Color} color - The color to subtract.
  11917. * @return {Color} A reference to this color.
  11918. */
  11919. sub( color ) {
  11920. this.r = Math.max( 0, this.r - color.r );
  11921. this.g = Math.max( 0, this.g - color.g );
  11922. this.b = Math.max( 0, this.b - color.b );
  11923. return this;
  11924. }
  11925. /**
  11926. * Multiplies the RGB values of the given color with the RGB values of this color.
  11927. *
  11928. * @param {Color} color - The color to multiply.
  11929. * @return {Color} A reference to this color.
  11930. */
  11931. multiply( color ) {
  11932. this.r *= color.r;
  11933. this.g *= color.g;
  11934. this.b *= color.b;
  11935. return this;
  11936. }
  11937. /**
  11938. * Multiplies the given scalar value with the RGB values of this color.
  11939. *
  11940. * @param {number} s - The scalar to multiply.
  11941. * @return {Color} A reference to this color.
  11942. */
  11943. multiplyScalar( s ) {
  11944. this.r *= s;
  11945. this.g *= s;
  11946. this.b *= s;
  11947. return this;
  11948. }
  11949. /**
  11950. * Linearly interpolates this color's RGB values toward the RGB values of the
  11951. * given color. The alpha argument can be thought of as the ratio between
  11952. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  11953. *
  11954. * @param {Color} color - The color to converge on.
  11955. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11956. * @return {Color} A reference to this color.
  11957. */
  11958. lerp( color, alpha ) {
  11959. this.r += ( color.r - this.r ) * alpha;
  11960. this.g += ( color.g - this.g ) * alpha;
  11961. this.b += ( color.b - this.b ) * alpha;
  11962. return this;
  11963. }
  11964. /**
  11965. * Linearly interpolates between the given colors and stores the result in this instance.
  11966. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  11967. * is the first and `1.0` is the second color.
  11968. *
  11969. * @param {Color} color1 - The first color.
  11970. * @param {Color} color2 - The second color.
  11971. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11972. * @return {Color} A reference to this color.
  11973. */
  11974. lerpColors( color1, color2, alpha ) {
  11975. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  11976. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  11977. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  11978. return this;
  11979. }
  11980. /**
  11981. * Linearly interpolates this color's HSL values toward the HSL values of the
  11982. * given color. It differs from {@link Color#lerp} by not interpolating straight
  11983. * from one color to the other, but instead going through all the hues in between
  11984. * those two colors. The alpha argument can be thought of as the ratio between
  11985. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  11986. *
  11987. * @param {Color} color - The color to converge on.
  11988. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11989. * @return {Color} A reference to this color.
  11990. */
  11991. lerpHSL( color, alpha ) {
  11992. this.getHSL( _hslA );
  11993. color.getHSL( _hslB );
  11994. const h = lerp( _hslA.h, _hslB.h, alpha );
  11995. const s = lerp( _hslA.s, _hslB.s, alpha );
  11996. const l = lerp( _hslA.l, _hslB.l, alpha );
  11997. this.setHSL( h, s, l );
  11998. return this;
  11999. }
  12000. /**
  12001. * Sets the color's RGB components from the given 3D vector.
  12002. *
  12003. * @param {Vector3} v - The vector to set.
  12004. * @return {Color} A reference to this color.
  12005. */
  12006. setFromVector3( v ) {
  12007. this.r = v.x;
  12008. this.g = v.y;
  12009. this.b = v.z;
  12010. return this;
  12011. }
  12012. /**
  12013. * Transforms this color with the given 3x3 matrix.
  12014. *
  12015. * @param {Matrix3} m - The matrix.
  12016. * @return {Color} A reference to this color.
  12017. */
  12018. applyMatrix3( m ) {
  12019. const r = this.r, g = this.g, b = this.b;
  12020. const e = m.elements;
  12021. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  12022. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  12023. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  12024. return this;
  12025. }
  12026. /**
  12027. * Returns `true` if this color is equal with the given one.
  12028. *
  12029. * @param {Color} c - The color to test for equality.
  12030. * @return {boolean} Whether this bounding color is equal with the given one.
  12031. */
  12032. equals( c ) {
  12033. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  12034. }
  12035. /**
  12036. * Sets this color's RGB components from the given array.
  12037. *
  12038. * @param {Array<number>} array - An array holding the RGB values.
  12039. * @param {number} [offset=0] - The offset into the array.
  12040. * @return {Color} A reference to this color.
  12041. */
  12042. fromArray( array, offset = 0 ) {
  12043. this.r = array[ offset ];
  12044. this.g = array[ offset + 1 ];
  12045. this.b = array[ offset + 2 ];
  12046. return this;
  12047. }
  12048. /**
  12049. * Writes the RGB components of this color to the given array. If no array is provided,
  12050. * the method returns a new instance.
  12051. *
  12052. * @param {Array<number>} [array=[]] - The target array holding the color components.
  12053. * @param {number} [offset=0] - Index of the first element in the array.
  12054. * @return {Array<number>} The color components.
  12055. */
  12056. toArray( array = [], offset = 0 ) {
  12057. array[ offset ] = this.r;
  12058. array[ offset + 1 ] = this.g;
  12059. array[ offset + 2 ] = this.b;
  12060. return array;
  12061. }
  12062. /**
  12063. * Sets the components of this color from the given buffer attribute.
  12064. *
  12065. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  12066. * @param {number} index - The index into the attribute.
  12067. * @return {Color} A reference to this color.
  12068. */
  12069. fromBufferAttribute( attribute, index ) {
  12070. this.r = attribute.getX( index );
  12071. this.g = attribute.getY( index );
  12072. this.b = attribute.getZ( index );
  12073. return this;
  12074. }
  12075. /**
  12076. * This methods defines the serialization result of this class. Returns the color
  12077. * as a hexadecimal value.
  12078. *
  12079. * @return {number} The hexadecimal value.
  12080. */
  12081. toJSON() {
  12082. return this.getHex();
  12083. }
  12084. *[ Symbol.iterator ]() {
  12085. yield this.r;
  12086. yield this.g;
  12087. yield this.b;
  12088. }
  12089. }
  12090. const _color = /*@__PURE__*/ new Color();
  12091. /**
  12092. * A dictionary with X11 color names.
  12093. *
  12094. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  12095. *
  12096. * @static
  12097. * @type {Object}
  12098. */
  12099. Color.NAMES = _colorKeywords;
  12100. let _materialId = 0;
  12101. /**
  12102. * Abstract base class for materials.
  12103. *
  12104. * Materials define the appearance of renderable 3D objects.
  12105. *
  12106. * @abstract
  12107. * @augments EventDispatcher
  12108. */
  12109. class Material extends EventDispatcher {
  12110. /**
  12111. * Constructs a new material.
  12112. */
  12113. constructor() {
  12114. super();
  12115. /**
  12116. * This flag can be used for type testing.
  12117. *
  12118. * @type {boolean}
  12119. * @readonly
  12120. * @default true
  12121. */
  12122. this.isMaterial = true;
  12123. /**
  12124. * The ID of the material.
  12125. *
  12126. * @name Material#id
  12127. * @type {number}
  12128. * @readonly
  12129. */
  12130. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  12131. /**
  12132. * The UUID of the material.
  12133. *
  12134. * @type {string}
  12135. * @readonly
  12136. */
  12137. this.uuid = generateUUID();
  12138. /**
  12139. * The name of the material.
  12140. *
  12141. * @type {string}
  12142. */
  12143. this.name = '';
  12144. /**
  12145. * The type property is used for detecting the object type
  12146. * in context of serialization/deserialization.
  12147. *
  12148. * @type {string}
  12149. * @readonly
  12150. */
  12151. this.type = 'Material';
  12152. /**
  12153. * Defines the blending type of the material.
  12154. *
  12155. * It must be set to `CustomBlending` if custom blending properties like
  12156. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  12157. * should have any effect.
  12158. *
  12159. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  12160. * @default NormalBlending
  12161. */
  12162. this.blending = NormalBlending;
  12163. /**
  12164. * Defines which side of faces will be rendered - front, back or both.
  12165. *
  12166. * @type {(FrontSide|BackSide|DoubleSide)}
  12167. * @default FrontSide
  12168. */
  12169. this.side = FrontSide;
  12170. /**
  12171. * If set to `true`, vertex colors should be used.
  12172. *
  12173. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  12174. * four (RGBA) component color buffer attribute is used.
  12175. *
  12176. * @type {boolean}
  12177. * @default false
  12178. */
  12179. this.vertexColors = false;
  12180. /**
  12181. * Defines how transparent the material is.
  12182. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  12183. *
  12184. * If the {@link Material#transparent} is not set to `true`,
  12185. * the material will remain fully opaque and this value will only affect its color.
  12186. *
  12187. * @type {number}
  12188. * @default 1
  12189. */
  12190. this.opacity = 1;
  12191. /**
  12192. * Defines whether this material is transparent. This has an effect on
  12193. * rendering as transparent objects need special treatment and are rendered
  12194. * after non-transparent objects.
  12195. *
  12196. * When set to true, the extent to which the material is transparent is
  12197. * controlled by {@link Material#opacity}.
  12198. *
  12199. * @type {boolean}
  12200. * @default false
  12201. */
  12202. this.transparent = false;
  12203. /**
  12204. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  12205. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  12206. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  12207. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  12208. *
  12209. * @type {boolean}
  12210. * @default false
  12211. */
  12212. this.alphaHash = false;
  12213. /**
  12214. * Defines the blending source factor.
  12215. *
  12216. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12217. * @default SrcAlphaFactor
  12218. */
  12219. this.blendSrc = SrcAlphaFactor;
  12220. /**
  12221. * Defines the blending destination factor.
  12222. *
  12223. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12224. * @default OneMinusSrcAlphaFactor
  12225. */
  12226. this.blendDst = OneMinusSrcAlphaFactor;
  12227. /**
  12228. * Defines the blending equation.
  12229. *
  12230. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12231. * @default AddEquation
  12232. */
  12233. this.blendEquation = AddEquation;
  12234. /**
  12235. * Defines the blending source alpha factor.
  12236. *
  12237. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12238. * @default null
  12239. */
  12240. this.blendSrcAlpha = null;
  12241. /**
  12242. * Defines the blending destination alpha factor.
  12243. *
  12244. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12245. * @default null
  12246. */
  12247. this.blendDstAlpha = null;
  12248. /**
  12249. * Defines the blending equation of the alpha channel.
  12250. *
  12251. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12252. * @default null
  12253. */
  12254. this.blendEquationAlpha = null;
  12255. /**
  12256. * Represents the RGB values of the constant blend color.
  12257. *
  12258. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  12259. *
  12260. * @type {Color}
  12261. * @default (0,0,0)
  12262. */
  12263. this.blendColor = new Color( 0, 0, 0 );
  12264. /**
  12265. * Represents the alpha value of the constant blend color.
  12266. *
  12267. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  12268. *
  12269. * @type {number}
  12270. * @default 0
  12271. */
  12272. this.blendAlpha = 0;
  12273. /**
  12274. * Defines the depth function.
  12275. *
  12276. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  12277. * @default LessEqualDepth
  12278. */
  12279. this.depthFunc = LessEqualDepth;
  12280. /**
  12281. * Whether to have depth test enabled when rendering this material.
  12282. * When the depth test is disabled, the depth write will also be implicitly disabled.
  12283. *
  12284. * @type {boolean}
  12285. * @default true
  12286. */
  12287. this.depthTest = true;
  12288. /**
  12289. * Whether rendering this material has any effect on the depth buffer.
  12290. *
  12291. * When drawing 2D overlays it can be useful to disable the depth writing in
  12292. * order to layer several things together without creating z-index artifacts.
  12293. *
  12294. * @type {boolean}
  12295. * @default true
  12296. */
  12297. this.depthWrite = true;
  12298. /**
  12299. * The bit mask to use when writing to the stencil buffer.
  12300. *
  12301. * @type {number}
  12302. * @default 0xff
  12303. */
  12304. this.stencilWriteMask = 0xff;
  12305. /**
  12306. * The stencil comparison function to use.
  12307. *
  12308. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  12309. * @default AlwaysStencilFunc
  12310. */
  12311. this.stencilFunc = AlwaysStencilFunc;
  12312. /**
  12313. * The value to use when performing stencil comparisons or stencil operations.
  12314. *
  12315. * @type {number}
  12316. * @default 0
  12317. */
  12318. this.stencilRef = 0;
  12319. /**
  12320. * The bit mask to use when comparing against the stencil buffer.
  12321. *
  12322. * @type {number}
  12323. * @default 0xff
  12324. */
  12325. this.stencilFuncMask = 0xff;
  12326. /**
  12327. * Which stencil operation to perform when the comparison function returns `false`.
  12328. *
  12329. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12330. * @default KeepStencilOp
  12331. */
  12332. this.stencilFail = KeepStencilOp;
  12333. /**
  12334. * Which stencil operation to perform when the comparison function returns
  12335. * `true` but the depth test fails.
  12336. *
  12337. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12338. * @default KeepStencilOp
  12339. */
  12340. this.stencilZFail = KeepStencilOp;
  12341. /**
  12342. * Which stencil operation to perform when the comparison function returns
  12343. * `true` and the depth test passes.
  12344. *
  12345. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12346. * @default KeepStencilOp
  12347. */
  12348. this.stencilZPass = KeepStencilOp;
  12349. /**
  12350. * Whether stencil operations are performed against the stencil buffer. In
  12351. * order to perform writes or comparisons against the stencil buffer this
  12352. * value must be `true`.
  12353. *
  12354. * @type {boolean}
  12355. * @default false
  12356. */
  12357. this.stencilWrite = false;
  12358. /**
  12359. * User-defined clipping planes specified as THREE.Plane objects in world
  12360. * space. These planes apply to the objects this material is attached to.
  12361. * Points in space whose signed distance to the plane is negative are clipped
  12362. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  12363. * be `true`.
  12364. *
  12365. * @type {?Array<Plane>}
  12366. * @default null
  12367. */
  12368. this.clippingPlanes = null;
  12369. /**
  12370. * Changes the behavior of clipping planes so that only their intersection is
  12371. * clipped, rather than their union.
  12372. *
  12373. * @type {boolean}
  12374. * @default false
  12375. */
  12376. this.clipIntersection = false;
  12377. /**
  12378. * Defines whether to clip shadows according to the clipping planes specified
  12379. * on this material.
  12380. *
  12381. * @type {boolean}
  12382. * @default false
  12383. */
  12384. this.clipShadows = false;
  12385. /**
  12386. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  12387. * is determined as follows:
  12388. *
  12389. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  12390. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  12391. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  12392. *
  12393. * @type {?(FrontSide|BackSide|DoubleSide)}
  12394. * @default null
  12395. */
  12396. this.shadowSide = null;
  12397. /**
  12398. * Whether to render the material's color.
  12399. *
  12400. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  12401. * objects that occlude other objects.
  12402. *
  12403. * @type {boolean}
  12404. * @default true
  12405. */
  12406. this.colorWrite = true;
  12407. /**
  12408. * Override the renderer's default precision for this material.
  12409. *
  12410. * @type {?('highp'|'mediump'|'lowp')}
  12411. * @default null
  12412. */
  12413. this.precision = null;
  12414. /**
  12415. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  12416. * be offset after it is interpolated from the depth values of the appropriate vertices.
  12417. * The offset is added before the depth test is performed and before the value is written
  12418. * into the depth buffer.
  12419. *
  12420. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  12421. * rendering solids with highlighted edges.
  12422. *
  12423. * @type {boolean}
  12424. * @default false
  12425. */
  12426. this.polygonOffset = false;
  12427. /**
  12428. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  12429. *
  12430. * @type {number}
  12431. * @default 0
  12432. */
  12433. this.polygonOffsetFactor = 0;
  12434. /**
  12435. * Is multiplied by an implementation-specific value to create a constant depth offset.
  12436. *
  12437. * @type {number}
  12438. * @default 0
  12439. */
  12440. this.polygonOffsetUnits = 0;
  12441. /**
  12442. * Whether to apply dithering to the color to remove the appearance of banding.
  12443. *
  12444. * @type {boolean}
  12445. * @default false
  12446. */
  12447. this.dithering = false;
  12448. /**
  12449. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  12450. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  12451. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  12452. *
  12453. * @type {boolean}
  12454. * @default false
  12455. */
  12456. this.alphaToCoverage = false;
  12457. /**
  12458. * Whether to premultiply the alpha (transparency) value.
  12459. *
  12460. * @type {boolean}
  12461. * @default false
  12462. */
  12463. this.premultipliedAlpha = false;
  12464. /**
  12465. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  12466. *
  12467. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  12468. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  12469. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  12470. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  12471. * disable the two pass rendering to avoid performance issues.
  12472. *
  12473. * @type {boolean}
  12474. * @default false
  12475. */
  12476. this.forceSinglePass = false;
  12477. /**
  12478. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  12479. *
  12480. * @type {boolean}
  12481. * @default true
  12482. */
  12483. this.allowOverride = true;
  12484. /**
  12485. * Defines whether 3D objects using this material are visible.
  12486. *
  12487. * @type {boolean}
  12488. * @default true
  12489. */
  12490. this.visible = true;
  12491. /**
  12492. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  12493. *
  12494. * It is ignored when rendering to a render target or using post processing or when using
  12495. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  12496. *
  12497. * @type {boolean}
  12498. * @default true
  12499. */
  12500. this.toneMapped = true;
  12501. /**
  12502. * An object that can be used to store custom data about the Material. It
  12503. * should not hold references to functions as these will not be cloned.
  12504. *
  12505. * @type {Object}
  12506. */
  12507. this.userData = {};
  12508. /**
  12509. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  12510. *
  12511. * @type {number}
  12512. * @readonly
  12513. * @default 0
  12514. */
  12515. this.version = 0;
  12516. this._alphaTest = 0;
  12517. }
  12518. /**
  12519. * Sets the alpha value to be used when running an alpha test. The material
  12520. * will not be rendered if the opacity is lower than this value.
  12521. *
  12522. * @type {number}
  12523. * @readonly
  12524. * @default 0
  12525. */
  12526. get alphaTest() {
  12527. return this._alphaTest;
  12528. }
  12529. set alphaTest( value ) {
  12530. if ( this._alphaTest > 0 !== value > 0 ) {
  12531. this.version ++;
  12532. }
  12533. this._alphaTest = value;
  12534. }
  12535. /**
  12536. * An optional callback that is executed immediately before the material is used to render a 3D object.
  12537. *
  12538. * This method can only be used when rendering with {@link WebGLRenderer}.
  12539. *
  12540. * @param {WebGLRenderer} renderer - The renderer.
  12541. * @param {Scene} scene - The scene.
  12542. * @param {Camera} camera - The camera that is used to render the scene.
  12543. * @param {BufferGeometry} geometry - The 3D object's geometry.
  12544. * @param {Object3D} object - The 3D object.
  12545. * @param {Object} group - The geometry group data.
  12546. */
  12547. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  12548. /**
  12549. * An optional callback that is executed immediately before the shader
  12550. * program is compiled. This function is called with the shader source code
  12551. * as a parameter. Useful for the modification of built-in materials.
  12552. *
  12553. * This method can only be used when rendering with {@link WebGLRenderer}. The
  12554. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  12555. * Node Material system and [TSL]{@link https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language}.
  12556. *
  12557. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  12558. * @param {WebGLRenderer} renderer - A reference to the renderer.
  12559. */
  12560. onBeforeCompile( /* shaderobject, renderer */ ) {}
  12561. /**
  12562. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  12563. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  12564. * shader or recompile the shader for this material as needed.
  12565. *
  12566. * This method can only be used when rendering with {@link WebGLRenderer}.
  12567. *
  12568. * @return {string} The custom program cache key.
  12569. */
  12570. customProgramCacheKey() {
  12571. return this.onBeforeCompile.toString();
  12572. }
  12573. /**
  12574. * This method can be used to set default values from parameter objects.
  12575. * It is a generic implementation so it can be used with different types
  12576. * of materials.
  12577. *
  12578. * @param {Object} [values] - The material values to set.
  12579. */
  12580. setValues( values ) {
  12581. if ( values === undefined ) return;
  12582. for ( const key in values ) {
  12583. const newValue = values[ key ];
  12584. if ( newValue === undefined ) {
  12585. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  12586. continue;
  12587. }
  12588. const currentValue = this[ key ];
  12589. if ( currentValue === undefined ) {
  12590. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  12591. continue;
  12592. }
  12593. if ( currentValue && currentValue.isColor ) {
  12594. currentValue.set( newValue );
  12595. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  12596. currentValue.copy( newValue );
  12597. } else {
  12598. this[ key ] = newValue;
  12599. }
  12600. }
  12601. }
  12602. /**
  12603. * Serializes the material into JSON.
  12604. *
  12605. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  12606. * @return {Object} A JSON object representing the serialized material.
  12607. * @see {@link ObjectLoader#parse}
  12608. */
  12609. toJSON( meta ) {
  12610. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  12611. if ( isRootObject ) {
  12612. meta = {
  12613. textures: {},
  12614. images: {}
  12615. };
  12616. }
  12617. const data = {
  12618. metadata: {
  12619. version: 4.6,
  12620. type: 'Material',
  12621. generator: 'Material.toJSON'
  12622. }
  12623. };
  12624. // standard Material serialization
  12625. data.uuid = this.uuid;
  12626. data.type = this.type;
  12627. if ( this.name !== '' ) data.name = this.name;
  12628. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  12629. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  12630. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  12631. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  12632. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  12633. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  12634. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  12635. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  12636. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  12637. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  12638. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  12639. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  12640. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  12641. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  12642. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  12643. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  12644. }
  12645. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  12646. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  12647. }
  12648. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  12649. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  12650. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  12651. }
  12652. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  12653. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  12654. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  12655. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  12656. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  12657. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  12658. }
  12659. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  12660. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  12661. }
  12662. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  12663. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  12664. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  12665. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  12666. }
  12667. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  12668. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  12669. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  12670. if ( this.lightMap && this.lightMap.isTexture ) {
  12671. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  12672. data.lightMapIntensity = this.lightMapIntensity;
  12673. }
  12674. if ( this.aoMap && this.aoMap.isTexture ) {
  12675. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  12676. data.aoMapIntensity = this.aoMapIntensity;
  12677. }
  12678. if ( this.bumpMap && this.bumpMap.isTexture ) {
  12679. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  12680. data.bumpScale = this.bumpScale;
  12681. }
  12682. if ( this.normalMap && this.normalMap.isTexture ) {
  12683. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  12684. data.normalMapType = this.normalMapType;
  12685. data.normalScale = this.normalScale.toArray();
  12686. }
  12687. if ( this.displacementMap && this.displacementMap.isTexture ) {
  12688. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  12689. data.displacementScale = this.displacementScale;
  12690. data.displacementBias = this.displacementBias;
  12691. }
  12692. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  12693. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  12694. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  12695. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  12696. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  12697. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  12698. if ( this.envMap && this.envMap.isTexture ) {
  12699. data.envMap = this.envMap.toJSON( meta ).uuid;
  12700. if ( this.combine !== undefined ) data.combine = this.combine;
  12701. }
  12702. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  12703. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  12704. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  12705. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  12706. if ( this.gradientMap && this.gradientMap.isTexture ) {
  12707. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  12708. }
  12709. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  12710. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  12711. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  12712. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  12713. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  12714. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  12715. if ( this.size !== undefined ) data.size = this.size;
  12716. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  12717. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  12718. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  12719. if ( this.side !== FrontSide ) data.side = this.side;
  12720. if ( this.vertexColors === true ) data.vertexColors = true;
  12721. if ( this.opacity < 1 ) data.opacity = this.opacity;
  12722. if ( this.transparent === true ) data.transparent = true;
  12723. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  12724. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  12725. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  12726. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  12727. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  12728. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  12729. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  12730. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  12731. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  12732. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  12733. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  12734. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  12735. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  12736. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  12737. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  12738. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  12739. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  12740. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  12741. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  12742. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  12743. // rotation (SpriteMaterial)
  12744. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  12745. if ( this.polygonOffset === true ) data.polygonOffset = true;
  12746. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  12747. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  12748. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  12749. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  12750. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  12751. if ( this.scale !== undefined ) data.scale = this.scale;
  12752. if ( this.dithering === true ) data.dithering = true;
  12753. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  12754. if ( this.alphaHash === true ) data.alphaHash = true;
  12755. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  12756. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  12757. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  12758. if ( this.wireframe === true ) data.wireframe = true;
  12759. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  12760. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  12761. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  12762. if ( this.flatShading === true ) data.flatShading = true;
  12763. if ( this.visible === false ) data.visible = false;
  12764. if ( this.toneMapped === false ) data.toneMapped = false;
  12765. if ( this.fog === false ) data.fog = false;
  12766. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  12767. // TODO: Copied from Object3D.toJSON
  12768. function extractFromCache( cache ) {
  12769. const values = [];
  12770. for ( const key in cache ) {
  12771. const data = cache[ key ];
  12772. delete data.metadata;
  12773. values.push( data );
  12774. }
  12775. return values;
  12776. }
  12777. if ( isRootObject ) {
  12778. const textures = extractFromCache( meta.textures );
  12779. const images = extractFromCache( meta.images );
  12780. if ( textures.length > 0 ) data.textures = textures;
  12781. if ( images.length > 0 ) data.images = images;
  12782. }
  12783. return data;
  12784. }
  12785. /**
  12786. * Returns a new material with copied values from this instance.
  12787. *
  12788. * @return {Material} A clone of this instance.
  12789. */
  12790. clone() {
  12791. return new this.constructor().copy( this );
  12792. }
  12793. /**
  12794. * Copies the values of the given material to this instance.
  12795. *
  12796. * @param {Material} source - The material to copy.
  12797. * @return {Material} A reference to this instance.
  12798. */
  12799. copy( source ) {
  12800. this.name = source.name;
  12801. this.blending = source.blending;
  12802. this.side = source.side;
  12803. this.vertexColors = source.vertexColors;
  12804. this.opacity = source.opacity;
  12805. this.transparent = source.transparent;
  12806. this.blendSrc = source.blendSrc;
  12807. this.blendDst = source.blendDst;
  12808. this.blendEquation = source.blendEquation;
  12809. this.blendSrcAlpha = source.blendSrcAlpha;
  12810. this.blendDstAlpha = source.blendDstAlpha;
  12811. this.blendEquationAlpha = source.blendEquationAlpha;
  12812. this.blendColor.copy( source.blendColor );
  12813. this.blendAlpha = source.blendAlpha;
  12814. this.depthFunc = source.depthFunc;
  12815. this.depthTest = source.depthTest;
  12816. this.depthWrite = source.depthWrite;
  12817. this.stencilWriteMask = source.stencilWriteMask;
  12818. this.stencilFunc = source.stencilFunc;
  12819. this.stencilRef = source.stencilRef;
  12820. this.stencilFuncMask = source.stencilFuncMask;
  12821. this.stencilFail = source.stencilFail;
  12822. this.stencilZFail = source.stencilZFail;
  12823. this.stencilZPass = source.stencilZPass;
  12824. this.stencilWrite = source.stencilWrite;
  12825. const srcPlanes = source.clippingPlanes;
  12826. let dstPlanes = null;
  12827. if ( srcPlanes !== null ) {
  12828. const n = srcPlanes.length;
  12829. dstPlanes = new Array( n );
  12830. for ( let i = 0; i !== n; ++ i ) {
  12831. dstPlanes[ i ] = srcPlanes[ i ].clone();
  12832. }
  12833. }
  12834. this.clippingPlanes = dstPlanes;
  12835. this.clipIntersection = source.clipIntersection;
  12836. this.clipShadows = source.clipShadows;
  12837. this.shadowSide = source.shadowSide;
  12838. this.colorWrite = source.colorWrite;
  12839. this.precision = source.precision;
  12840. this.polygonOffset = source.polygonOffset;
  12841. this.polygonOffsetFactor = source.polygonOffsetFactor;
  12842. this.polygonOffsetUnits = source.polygonOffsetUnits;
  12843. this.dithering = source.dithering;
  12844. this.alphaTest = source.alphaTest;
  12845. this.alphaHash = source.alphaHash;
  12846. this.alphaToCoverage = source.alphaToCoverage;
  12847. this.premultipliedAlpha = source.premultipliedAlpha;
  12848. this.forceSinglePass = source.forceSinglePass;
  12849. this.visible = source.visible;
  12850. this.toneMapped = source.toneMapped;
  12851. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  12852. return this;
  12853. }
  12854. /**
  12855. * Frees the GPU-related resources allocated by this instance. Call this
  12856. * method whenever this instance is no longer used in your app.
  12857. *
  12858. * @fires Material#dispose
  12859. */
  12860. dispose() {
  12861. /**
  12862. * Fires when the material has been disposed of.
  12863. *
  12864. * @event Material#dispose
  12865. * @type {Object}
  12866. */
  12867. this.dispatchEvent( { type: 'dispose' } );
  12868. }
  12869. /**
  12870. * Setting this property to `true` indicates the engine the material
  12871. * needs to be recompiled.
  12872. *
  12873. * @type {boolean}
  12874. * @default false
  12875. * @param {boolean} value
  12876. */
  12877. set needsUpdate( value ) {
  12878. if ( value === true ) this.version ++;
  12879. }
  12880. }
  12881. /**
  12882. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  12883. *
  12884. * This material is not affected by lights.
  12885. *
  12886. * @augments Material
  12887. */
  12888. class MeshBasicMaterial extends Material {
  12889. /**
  12890. * Constructs a new mesh basic material.
  12891. *
  12892. * @param {Object} [parameters] - An object with one or more properties
  12893. * defining the material's appearance. Any property of the material
  12894. * (including any property from inherited materials) can be passed
  12895. * in here. Color values can be passed any type of value accepted
  12896. * by {@link Color#set}.
  12897. */
  12898. constructor( parameters ) {
  12899. super();
  12900. /**
  12901. * This flag can be used for type testing.
  12902. *
  12903. * @type {boolean}
  12904. * @readonly
  12905. * @default true
  12906. */
  12907. this.isMeshBasicMaterial = true;
  12908. this.type = 'MeshBasicMaterial';
  12909. /**
  12910. * Color of the material.
  12911. *
  12912. * @type {Color}
  12913. * @default (1,1,1)
  12914. */
  12915. this.color = new Color( 0xffffff ); // emissive
  12916. /**
  12917. * The color map. May optionally include an alpha channel, typically combined
  12918. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  12919. * color is modulated by the diffuse `color`.
  12920. *
  12921. * @type {?Texture}
  12922. * @default null
  12923. */
  12924. this.map = null;
  12925. /**
  12926. * The light map. Requires a second set of UVs.
  12927. *
  12928. * @type {?Texture}
  12929. * @default null
  12930. */
  12931. this.lightMap = null;
  12932. /**
  12933. * Intensity of the baked light.
  12934. *
  12935. * @type {number}
  12936. * @default 1
  12937. */
  12938. this.lightMapIntensity = 1.0;
  12939. /**
  12940. * The red channel of this texture is used as the ambient occlusion map.
  12941. * Requires a second set of UVs.
  12942. *
  12943. * @type {?Texture}
  12944. * @default null
  12945. */
  12946. this.aoMap = null;
  12947. /**
  12948. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  12949. * disables ambient occlusion. Where intensity is `1` and the AO map's
  12950. * red channel is also `1`, ambient light is fully occluded on a surface.
  12951. *
  12952. * @type {number}
  12953. * @default 1
  12954. */
  12955. this.aoMapIntensity = 1.0;
  12956. /**
  12957. * Specular map used by the material.
  12958. *
  12959. * @type {?Texture}
  12960. * @default null
  12961. */
  12962. this.specularMap = null;
  12963. /**
  12964. * The alpha map is a grayscale texture that controls the opacity across the
  12965. * surface (black: fully transparent; white: fully opaque).
  12966. *
  12967. * Only the color of the texture is used, ignoring the alpha channel if one
  12968. * exists. For RGB and RGBA textures, the renderer will use the green channel
  12969. * when sampling this texture due to the extra bit of precision provided for
  12970. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  12971. * luminance/alpha textures will also still work as expected.
  12972. *
  12973. * @type {?Texture}
  12974. * @default null
  12975. */
  12976. this.alphaMap = null;
  12977. /**
  12978. * The environment map.
  12979. *
  12980. * @type {?Texture}
  12981. * @default null
  12982. */
  12983. this.envMap = null;
  12984. /**
  12985. * The rotation of the environment map in radians.
  12986. *
  12987. * @type {Euler}
  12988. * @default (0,0,0)
  12989. */
  12990. this.envMapRotation = new Euler();
  12991. /**
  12992. * How to combine the result of the surface's color with the environment map, if any.
  12993. *
  12994. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  12995. * blend between the two colors.
  12996. *
  12997. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  12998. * @default MultiplyOperation
  12999. */
  13000. this.combine = MultiplyOperation;
  13001. /**
  13002. * How much the environment map affects the surface.
  13003. * The valid range is between `0` (no reflections) and `1` (full reflections).
  13004. *
  13005. * @type {number}
  13006. * @default 1
  13007. */
  13008. this.reflectivity = 1;
  13009. /**
  13010. * The index of refraction (IOR) of air (approximately 1) divided by the
  13011. * index of refraction of the material. It is used with environment mapping
  13012. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  13013. * The refraction ratio should not exceed `1`.
  13014. *
  13015. * @type {number}
  13016. * @default 0.98
  13017. */
  13018. this.refractionRatio = 0.98;
  13019. /**
  13020. * Renders the geometry as a wireframe.
  13021. *
  13022. * @type {boolean}
  13023. * @default false
  13024. */
  13025. this.wireframe = false;
  13026. /**
  13027. * Controls the thickness of the wireframe.
  13028. *
  13029. * Can only be used with {@link SVGRenderer}.
  13030. *
  13031. * @type {number}
  13032. * @default 1
  13033. */
  13034. this.wireframeLinewidth = 1;
  13035. /**
  13036. * Defines appearance of wireframe ends.
  13037. *
  13038. * Can only be used with {@link SVGRenderer}.
  13039. *
  13040. * @type {('round'|'bevel'|'miter')}
  13041. * @default 'round'
  13042. */
  13043. this.wireframeLinecap = 'round';
  13044. /**
  13045. * Defines appearance of wireframe joints.
  13046. *
  13047. * Can only be used with {@link SVGRenderer}.
  13048. *
  13049. * @type {('round'|'bevel'|'miter')}
  13050. * @default 'round'
  13051. */
  13052. this.wireframeLinejoin = 'round';
  13053. /**
  13054. * Whether the material is affected by fog or not.
  13055. *
  13056. * @type {boolean}
  13057. * @default true
  13058. */
  13059. this.fog = true;
  13060. this.setValues( parameters );
  13061. }
  13062. copy( source ) {
  13063. super.copy( source );
  13064. this.color.copy( source.color );
  13065. this.map = source.map;
  13066. this.lightMap = source.lightMap;
  13067. this.lightMapIntensity = source.lightMapIntensity;
  13068. this.aoMap = source.aoMap;
  13069. this.aoMapIntensity = source.aoMapIntensity;
  13070. this.specularMap = source.specularMap;
  13071. this.alphaMap = source.alphaMap;
  13072. this.envMap = source.envMap;
  13073. this.envMapRotation.copy( source.envMapRotation );
  13074. this.combine = source.combine;
  13075. this.reflectivity = source.reflectivity;
  13076. this.refractionRatio = source.refractionRatio;
  13077. this.wireframe = source.wireframe;
  13078. this.wireframeLinewidth = source.wireframeLinewidth;
  13079. this.wireframeLinecap = source.wireframeLinecap;
  13080. this.wireframeLinejoin = source.wireframeLinejoin;
  13081. this.fog = source.fog;
  13082. return this;
  13083. }
  13084. }
  13085. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  13086. const _tables = /*@__PURE__*/ _generateTables();
  13087. function _generateTables() {
  13088. // float32 to float16 helpers
  13089. const buffer = new ArrayBuffer( 4 );
  13090. const floatView = new Float32Array( buffer );
  13091. const uint32View = new Uint32Array( buffer );
  13092. const baseTable = new Uint32Array( 512 );
  13093. const shiftTable = new Uint32Array( 512 );
  13094. for ( let i = 0; i < 256; ++ i ) {
  13095. const e = i - 127;
  13096. // very small number (0, -0)
  13097. if ( e < -27 ) {
  13098. baseTable[ i ] = 0x0000;
  13099. baseTable[ i | 0x100 ] = 0x8000;
  13100. shiftTable[ i ] = 24;
  13101. shiftTable[ i | 0x100 ] = 24;
  13102. // small number (denorm)
  13103. } else if ( e < -14 ) {
  13104. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  13105. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  13106. shiftTable[ i ] = - e - 1;
  13107. shiftTable[ i | 0x100 ] = - e - 1;
  13108. // normal number
  13109. } else if ( e <= 15 ) {
  13110. baseTable[ i ] = ( e + 15 ) << 10;
  13111. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  13112. shiftTable[ i ] = 13;
  13113. shiftTable[ i | 0x100 ] = 13;
  13114. // large number (Infinity, -Infinity)
  13115. } else if ( e < 128 ) {
  13116. baseTable[ i ] = 0x7c00;
  13117. baseTable[ i | 0x100 ] = 0xfc00;
  13118. shiftTable[ i ] = 24;
  13119. shiftTable[ i | 0x100 ] = 24;
  13120. // stay (NaN, Infinity, -Infinity)
  13121. } else {
  13122. baseTable[ i ] = 0x7c00;
  13123. baseTable[ i | 0x100 ] = 0xfc00;
  13124. shiftTable[ i ] = 13;
  13125. shiftTable[ i | 0x100 ] = 13;
  13126. }
  13127. }
  13128. // float16 to float32 helpers
  13129. const mantissaTable = new Uint32Array( 2048 );
  13130. const exponentTable = new Uint32Array( 64 );
  13131. const offsetTable = new Uint32Array( 64 );
  13132. for ( let i = 1; i < 1024; ++ i ) {
  13133. let m = i << 13; // zero pad mantissa bits
  13134. let e = 0; // zero exponent
  13135. // normalized
  13136. while ( ( m & 0x00800000 ) === 0 ) {
  13137. m <<= 1;
  13138. e -= 0x00800000; // decrement exponent
  13139. }
  13140. m &= -8388609; // clear leading 1 bit
  13141. e += 0x38800000; // adjust bias
  13142. mantissaTable[ i ] = m | e;
  13143. }
  13144. for ( let i = 1024; i < 2048; ++ i ) {
  13145. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  13146. }
  13147. for ( let i = 1; i < 31; ++ i ) {
  13148. exponentTable[ i ] = i << 23;
  13149. }
  13150. exponentTable[ 31 ] = 0x47800000;
  13151. exponentTable[ 32 ] = 0x80000000;
  13152. for ( let i = 33; i < 63; ++ i ) {
  13153. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  13154. }
  13155. exponentTable[ 63 ] = 0xc7800000;
  13156. for ( let i = 1; i < 64; ++ i ) {
  13157. if ( i !== 32 ) {
  13158. offsetTable[ i ] = 1024;
  13159. }
  13160. }
  13161. return {
  13162. floatView: floatView,
  13163. uint32View: uint32View,
  13164. baseTable: baseTable,
  13165. shiftTable: shiftTable,
  13166. mantissaTable: mantissaTable,
  13167. exponentTable: exponentTable,
  13168. offsetTable: offsetTable
  13169. };
  13170. }
  13171. /**
  13172. * Returns a half precision floating point value (FP16) from the given single
  13173. * precision floating point value (FP32).
  13174. *
  13175. * @param {number} val - A single precision floating point value.
  13176. * @return {number} The FP16 value.
  13177. */
  13178. function toHalfFloat( val ) {
  13179. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  13180. val = clamp( val, -65504, 65504 );
  13181. _tables.floatView[ 0 ] = val;
  13182. const f = _tables.uint32View[ 0 ];
  13183. const e = ( f >> 23 ) & 0x1ff;
  13184. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  13185. }
  13186. /**
  13187. * Returns a single precision floating point value (FP32) from the given half
  13188. * precision floating point value (FP16).
  13189. *
  13190. * @param {number} val - A half precision floating point value.
  13191. * @return {number} The FP32 value.
  13192. */
  13193. function fromHalfFloat( val ) {
  13194. const m = val >> 10;
  13195. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  13196. return _tables.floatView[ 0 ];
  13197. }
  13198. /**
  13199. * A class containing utility functions for data.
  13200. *
  13201. * @hideconstructor
  13202. */
  13203. class DataUtils {
  13204. /**
  13205. * Returns a half precision floating point value (FP16) from the given single
  13206. * precision floating point value (FP32).
  13207. *
  13208. * @param {number} val - A single precision floating point value.
  13209. * @return {number} The FP16 value.
  13210. */
  13211. static toHalfFloat( val ) {
  13212. return toHalfFloat( val );
  13213. }
  13214. /**
  13215. * Returns a single precision floating point value (FP32) from the given half
  13216. * precision floating point value (FP16).
  13217. *
  13218. * @param {number} val - A half precision floating point value.
  13219. * @return {number} The FP32 value.
  13220. */
  13221. static fromHalfFloat( val ) {
  13222. return fromHalfFloat( val );
  13223. }
  13224. }
  13225. const _vector$9 = /*@__PURE__*/ new Vector3();
  13226. const _vector2$1 = /*@__PURE__*/ new Vector2();
  13227. let _id$3 = 0;
  13228. /**
  13229. * This class stores data for an attribute (such as vertex positions, face
  13230. * indices, normals, colors, UVs, and any custom attributes ) associated with
  13231. * a geometry, which allows for more efficient passing of data to the GPU.
  13232. *
  13233. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  13234. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  13235. */
  13236. class BufferAttribute {
  13237. /**
  13238. * Constructs a new buffer attribute.
  13239. *
  13240. * @param {TypedArray} array - The array holding the attribute data.
  13241. * @param {number} itemSize - The item size.
  13242. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13243. */
  13244. constructor( array, itemSize, normalized = false ) {
  13245. if ( Array.isArray( array ) ) {
  13246. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  13247. }
  13248. /**
  13249. * This flag can be used for type testing.
  13250. *
  13251. * @type {boolean}
  13252. * @readonly
  13253. * @default true
  13254. */
  13255. this.isBufferAttribute = true;
  13256. /**
  13257. * The ID of the buffer attribute.
  13258. *
  13259. * @name BufferAttribute#id
  13260. * @type {number}
  13261. * @readonly
  13262. */
  13263. Object.defineProperty( this, 'id', { value: _id$3 ++ } );
  13264. /**
  13265. * The name of the buffer attribute.
  13266. *
  13267. * @type {string}
  13268. */
  13269. this.name = '';
  13270. /**
  13271. * The array holding the attribute data. It should have `itemSize * numVertices`
  13272. * elements, where `numVertices` is the number of vertices in the associated geometry.
  13273. *
  13274. * @type {TypedArray}
  13275. */
  13276. this.array = array;
  13277. /**
  13278. * The number of values of the array that should be associated with a particular vertex.
  13279. * For instance, if this attribute is storing a 3-component vector (such as a position,
  13280. * normal, or color), then the value should be `3`.
  13281. *
  13282. * @type {number}
  13283. */
  13284. this.itemSize = itemSize;
  13285. /**
  13286. * Represents the number of items this buffer attribute stores. It is internally computed
  13287. * by dividing the `array` length by the `itemSize`.
  13288. *
  13289. * @type {number}
  13290. * @readonly
  13291. */
  13292. this.count = array !== undefined ? array.length / itemSize : 0;
  13293. /**
  13294. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  13295. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  13296. * and `normalized` is `true`, the values `0 -+65535` in the array data will be mapped to
  13297. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  13298. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  13299. *
  13300. * @type {boolean}
  13301. */
  13302. this.normalized = normalized;
  13303. /**
  13304. * Defines the intended usage pattern of the data store for optimization purposes.
  13305. *
  13306. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  13307. * instantiate a new one and set the desired usage before the next render.
  13308. *
  13309. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  13310. * @default StaticDrawUsage
  13311. */
  13312. this.usage = StaticDrawUsage;
  13313. /**
  13314. * This can be used to only update some components of stored vectors (for example, just the
  13315. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  13316. *
  13317. * @type {Array<Object>}
  13318. */
  13319. this.updateRanges = [];
  13320. /**
  13321. * Configures the bound GPU type for use in shaders.
  13322. *
  13323. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  13324. * For lower precision float types, use `Float16BufferAttribute`.
  13325. *
  13326. * @type {(FloatType|IntType)}
  13327. * @default FloatType
  13328. */
  13329. this.gpuType = FloatType;
  13330. /**
  13331. * A version number, incremented every time the `needsUpdate` is set to `true`.
  13332. *
  13333. * @type {number}
  13334. */
  13335. this.version = 0;
  13336. }
  13337. /**
  13338. * A callback function that is executed after the renderer has transferred the attribute
  13339. * array data to the GPU.
  13340. */
  13341. onUploadCallback() {}
  13342. /**
  13343. * Flag to indicate that this attribute has changed and should be re-sent to
  13344. * the GPU. Set this to `true` when you modify the value of the array.
  13345. *
  13346. * @type {number}
  13347. * @default false
  13348. * @param {boolean} value
  13349. */
  13350. set needsUpdate( value ) {
  13351. if ( value === true ) this.version ++;
  13352. }
  13353. /**
  13354. * Sets the usage of this buffer attribute.
  13355. *
  13356. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  13357. * @return {BufferAttribute} A reference to this buffer attribute.
  13358. */
  13359. setUsage( value ) {
  13360. this.usage = value;
  13361. return this;
  13362. }
  13363. /**
  13364. * Adds a range of data in the data array to be updated on the GPU.
  13365. *
  13366. * @param {number} start - Position at which to start update.
  13367. * @param {number} count - The number of components to update.
  13368. */
  13369. addUpdateRange( start, count ) {
  13370. this.updateRanges.push( { start, count } );
  13371. }
  13372. /**
  13373. * Clears the update ranges.
  13374. */
  13375. clearUpdateRanges() {
  13376. this.updateRanges.length = 0;
  13377. }
  13378. /**
  13379. * Copies the values of the given buffer attribute to this instance.
  13380. *
  13381. * @param {BufferAttribute} source - The buffer attribute to copy.
  13382. * @return {BufferAttribute} A reference to this instance.
  13383. */
  13384. copy( source ) {
  13385. this.name = source.name;
  13386. this.array = new source.array.constructor( source.array );
  13387. this.itemSize = source.itemSize;
  13388. this.count = source.count;
  13389. this.normalized = source.normalized;
  13390. this.usage = source.usage;
  13391. this.gpuType = source.gpuType;
  13392. return this;
  13393. }
  13394. /**
  13395. * Copies a vector from the given buffer attribute to this one. The start
  13396. * and destination position in the attribute buffers are represented by the
  13397. * given indices.
  13398. *
  13399. * @param {number} index1 - The destination index into this buffer attribute.
  13400. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  13401. * @param {number} index2 - The source index into the given buffer attribute.
  13402. * @return {BufferAttribute} A reference to this instance.
  13403. */
  13404. copyAt( index1, attribute, index2 ) {
  13405. index1 *= this.itemSize;
  13406. index2 *= attribute.itemSize;
  13407. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  13408. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13409. }
  13410. return this;
  13411. }
  13412. /**
  13413. * Copies the given array data into this buffer attribute.
  13414. *
  13415. * @param {(TypedArray|Array)} array - The array to copy.
  13416. * @return {BufferAttribute} A reference to this instance.
  13417. */
  13418. copyArray( array ) {
  13419. this.array.set( array );
  13420. return this;
  13421. }
  13422. /**
  13423. * Applies the given 3x3 matrix to the given attribute. Works with
  13424. * item size `2` and `3`.
  13425. *
  13426. * @param {Matrix3} m - The matrix to apply.
  13427. * @return {BufferAttribute} A reference to this instance.
  13428. */
  13429. applyMatrix3( m ) {
  13430. if ( this.itemSize === 2 ) {
  13431. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13432. _vector2$1.fromBufferAttribute( this, i );
  13433. _vector2$1.applyMatrix3( m );
  13434. this.setXY( i, _vector2$1.x, _vector2$1.y );
  13435. }
  13436. } else if ( this.itemSize === 3 ) {
  13437. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13438. _vector$9.fromBufferAttribute( this, i );
  13439. _vector$9.applyMatrix3( m );
  13440. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13441. }
  13442. }
  13443. return this;
  13444. }
  13445. /**
  13446. * Applies the given 4x4 matrix to the given attribute. Only works with
  13447. * item size `3`.
  13448. *
  13449. * @param {Matrix4} m - The matrix to apply.
  13450. * @return {BufferAttribute} A reference to this instance.
  13451. */
  13452. applyMatrix4( m ) {
  13453. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13454. _vector$9.fromBufferAttribute( this, i );
  13455. _vector$9.applyMatrix4( m );
  13456. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13457. }
  13458. return this;
  13459. }
  13460. /**
  13461. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  13462. * item size `3`.
  13463. *
  13464. * @param {Matrix3} m - The normal matrix to apply.
  13465. * @return {BufferAttribute} A reference to this instance.
  13466. */
  13467. applyNormalMatrix( m ) {
  13468. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13469. _vector$9.fromBufferAttribute( this, i );
  13470. _vector$9.applyNormalMatrix( m );
  13471. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13472. }
  13473. return this;
  13474. }
  13475. /**
  13476. * Applies the given 4x4 matrix to the given attribute. Only works with
  13477. * item size `3` and with direction vectors.
  13478. *
  13479. * @param {Matrix4} m - The matrix to apply.
  13480. * @return {BufferAttribute} A reference to this instance.
  13481. */
  13482. transformDirection( m ) {
  13483. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13484. _vector$9.fromBufferAttribute( this, i );
  13485. _vector$9.transformDirection( m );
  13486. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13487. }
  13488. return this;
  13489. }
  13490. /**
  13491. * Sets the given array data in the buffer attribute.
  13492. *
  13493. * @param {(TypedArray|Array)} value - The array data to set.
  13494. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  13495. * @return {BufferAttribute} A reference to this instance.
  13496. */
  13497. set( value, offset = 0 ) {
  13498. // Matching BufferAttribute constructor, do not normalize the array.
  13499. this.array.set( value, offset );
  13500. return this;
  13501. }
  13502. /**
  13503. * Returns the given component of the vector at the given index.
  13504. *
  13505. * @param {number} index - The index into the buffer attribute.
  13506. * @param {number} component - The component index.
  13507. * @return {number} The returned value.
  13508. */
  13509. getComponent( index, component ) {
  13510. let value = this.array[ index * this.itemSize + component ];
  13511. if ( this.normalized ) value = denormalize( value, this.array );
  13512. return value;
  13513. }
  13514. /**
  13515. * Sets the given value to the given component of the vector at the given index.
  13516. *
  13517. * @param {number} index - The index into the buffer attribute.
  13518. * @param {number} component - The component index.
  13519. * @param {number} value - The value to set.
  13520. * @return {BufferAttribute} A reference to this instance.
  13521. */
  13522. setComponent( index, component, value ) {
  13523. if ( this.normalized ) value = normalize( value, this.array );
  13524. this.array[ index * this.itemSize + component ] = value;
  13525. return this;
  13526. }
  13527. /**
  13528. * Returns the x component of the vector at the given index.
  13529. *
  13530. * @param {number} index - The index into the buffer attribute.
  13531. * @return {number} The x component.
  13532. */
  13533. getX( index ) {
  13534. let x = this.array[ index * this.itemSize ];
  13535. if ( this.normalized ) x = denormalize( x, this.array );
  13536. return x;
  13537. }
  13538. /**
  13539. * Sets the x component of the vector at the given index.
  13540. *
  13541. * @param {number} index - The index into the buffer attribute.
  13542. * @param {number} x - The value to set.
  13543. * @return {BufferAttribute} A reference to this instance.
  13544. */
  13545. setX( index, x ) {
  13546. if ( this.normalized ) x = normalize( x, this.array );
  13547. this.array[ index * this.itemSize ] = x;
  13548. return this;
  13549. }
  13550. /**
  13551. * Returns the y component of the vector at the given index.
  13552. *
  13553. * @param {number} index - The index into the buffer attribute.
  13554. * @return {number} The y component.
  13555. */
  13556. getY( index ) {
  13557. let y = this.array[ index * this.itemSize + 1 ];
  13558. if ( this.normalized ) y = denormalize( y, this.array );
  13559. return y;
  13560. }
  13561. /**
  13562. * Sets the y component of the vector at the given index.
  13563. *
  13564. * @param {number} index - The index into the buffer attribute.
  13565. * @param {number} y - The value to set.
  13566. * @return {BufferAttribute} A reference to this instance.
  13567. */
  13568. setY( index, y ) {
  13569. if ( this.normalized ) y = normalize( y, this.array );
  13570. this.array[ index * this.itemSize + 1 ] = y;
  13571. return this;
  13572. }
  13573. /**
  13574. * Returns the z component of the vector at the given index.
  13575. *
  13576. * @param {number} index - The index into the buffer attribute.
  13577. * @return {number} The z component.
  13578. */
  13579. getZ( index ) {
  13580. let z = this.array[ index * this.itemSize + 2 ];
  13581. if ( this.normalized ) z = denormalize( z, this.array );
  13582. return z;
  13583. }
  13584. /**
  13585. * Sets the z component of the vector at the given index.
  13586. *
  13587. * @param {number} index - The index into the buffer attribute.
  13588. * @param {number} z - The value to set.
  13589. * @return {BufferAttribute} A reference to this instance.
  13590. */
  13591. setZ( index, z ) {
  13592. if ( this.normalized ) z = normalize( z, this.array );
  13593. this.array[ index * this.itemSize + 2 ] = z;
  13594. return this;
  13595. }
  13596. /**
  13597. * Returns the w component of the vector at the given index.
  13598. *
  13599. * @param {number} index - The index into the buffer attribute.
  13600. * @return {number} The w component.
  13601. */
  13602. getW( index ) {
  13603. let w = this.array[ index * this.itemSize + 3 ];
  13604. if ( this.normalized ) w = denormalize( w, this.array );
  13605. return w;
  13606. }
  13607. /**
  13608. * Sets the w component of the vector at the given index.
  13609. *
  13610. * @param {number} index - The index into the buffer attribute.
  13611. * @param {number} w - The value to set.
  13612. * @return {BufferAttribute} A reference to this instance.
  13613. */
  13614. setW( index, w ) {
  13615. if ( this.normalized ) w = normalize( w, this.array );
  13616. this.array[ index * this.itemSize + 3 ] = w;
  13617. return this;
  13618. }
  13619. /**
  13620. * Sets the x and y component of the vector at the given index.
  13621. *
  13622. * @param {number} index - The index into the buffer attribute.
  13623. * @param {number} x - The value for the x component to set.
  13624. * @param {number} y - The value for the y component to set.
  13625. * @return {BufferAttribute} A reference to this instance.
  13626. */
  13627. setXY( index, x, y ) {
  13628. index *= this.itemSize;
  13629. if ( this.normalized ) {
  13630. x = normalize( x, this.array );
  13631. y = normalize( y, this.array );
  13632. }
  13633. this.array[ index + 0 ] = x;
  13634. this.array[ index + 1 ] = y;
  13635. return this;
  13636. }
  13637. /**
  13638. * Sets the x, y and z component of the vector at the given index.
  13639. *
  13640. * @param {number} index - The index into the buffer attribute.
  13641. * @param {number} x - The value for the x component to set.
  13642. * @param {number} y - The value for the y component to set.
  13643. * @param {number} z - The value for the z component to set.
  13644. * @return {BufferAttribute} A reference to this instance.
  13645. */
  13646. setXYZ( index, x, y, z ) {
  13647. index *= this.itemSize;
  13648. if ( this.normalized ) {
  13649. x = normalize( x, this.array );
  13650. y = normalize( y, this.array );
  13651. z = normalize( z, this.array );
  13652. }
  13653. this.array[ index + 0 ] = x;
  13654. this.array[ index + 1 ] = y;
  13655. this.array[ index + 2 ] = z;
  13656. return this;
  13657. }
  13658. /**
  13659. * Sets the x, y, z and w component of the vector at the given index.
  13660. *
  13661. * @param {number} index - The index into the buffer attribute.
  13662. * @param {number} x - The value for the x component to set.
  13663. * @param {number} y - The value for the y component to set.
  13664. * @param {number} z - The value for the z component to set.
  13665. * @param {number} w - The value for the w component to set.
  13666. * @return {BufferAttribute} A reference to this instance.
  13667. */
  13668. setXYZW( index, x, y, z, w ) {
  13669. index *= this.itemSize;
  13670. if ( this.normalized ) {
  13671. x = normalize( x, this.array );
  13672. y = normalize( y, this.array );
  13673. z = normalize( z, this.array );
  13674. w = normalize( w, this.array );
  13675. }
  13676. this.array[ index + 0 ] = x;
  13677. this.array[ index + 1 ] = y;
  13678. this.array[ index + 2 ] = z;
  13679. this.array[ index + 3 ] = w;
  13680. return this;
  13681. }
  13682. /**
  13683. * Sets the given callback function that is executed after the Renderer has transferred
  13684. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  13685. * the upload when attribute data are not needed anymore on the CPU side.
  13686. *
  13687. * @param {Function} callback - The `onUpload()` callback.
  13688. * @return {BufferAttribute} A reference to this instance.
  13689. */
  13690. onUpload( callback ) {
  13691. this.onUploadCallback = callback;
  13692. return this;
  13693. }
  13694. /**
  13695. * Returns a new buffer attribute with copied values from this instance.
  13696. *
  13697. * @return {BufferAttribute} A clone of this instance.
  13698. */
  13699. clone() {
  13700. return new this.constructor( this.array, this.itemSize ).copy( this );
  13701. }
  13702. /**
  13703. * Serializes the buffer attribute into JSON.
  13704. *
  13705. * @return {Object} A JSON object representing the serialized buffer attribute.
  13706. */
  13707. toJSON() {
  13708. const data = {
  13709. itemSize: this.itemSize,
  13710. type: this.array.constructor.name,
  13711. array: Array.from( this.array ),
  13712. normalized: this.normalized
  13713. };
  13714. if ( this.name !== '' ) data.name = this.name;
  13715. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  13716. return data;
  13717. }
  13718. }
  13719. /**
  13720. * Convenient class that can be used when creating a `Int8` buffer attribute with
  13721. * a plain `Array` instance.
  13722. *
  13723. * @augments BufferAttribute
  13724. */
  13725. class Int8BufferAttribute extends BufferAttribute {
  13726. /**
  13727. * Constructs a new buffer attribute.
  13728. *
  13729. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  13730. * @param {number} itemSize - The item size.
  13731. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13732. */
  13733. constructor( array, itemSize, normalized ) {
  13734. super( new Int8Array( array ), itemSize, normalized );
  13735. }
  13736. }
  13737. /**
  13738. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  13739. * a plain `Array` instance.
  13740. *
  13741. * @augments BufferAttribute
  13742. */
  13743. class Uint8BufferAttribute extends BufferAttribute {
  13744. /**
  13745. * Constructs a new buffer attribute.
  13746. *
  13747. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  13748. * @param {number} itemSize - The item size.
  13749. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13750. */
  13751. constructor( array, itemSize, normalized ) {
  13752. super( new Uint8Array( array ), itemSize, normalized );
  13753. }
  13754. }
  13755. /**
  13756. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  13757. * a plain `Array` instance.
  13758. *
  13759. * @augments BufferAttribute
  13760. */
  13761. class Uint8ClampedBufferAttribute extends BufferAttribute {
  13762. /**
  13763. * Constructs a new buffer attribute.
  13764. *
  13765. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  13766. * @param {number} itemSize - The item size.
  13767. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13768. */
  13769. constructor( array, itemSize, normalized ) {
  13770. super( new Uint8ClampedArray( array ), itemSize, normalized );
  13771. }
  13772. }
  13773. /**
  13774. * Convenient class that can be used when creating a `Int16` buffer attribute with
  13775. * a plain `Array` instance.
  13776. *
  13777. * @augments BufferAttribute
  13778. */
  13779. class Int16BufferAttribute extends BufferAttribute {
  13780. /**
  13781. * Constructs a new buffer attribute.
  13782. *
  13783. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  13784. * @param {number} itemSize - The item size.
  13785. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13786. */
  13787. constructor( array, itemSize, normalized ) {
  13788. super( new Int16Array( array ), itemSize, normalized );
  13789. }
  13790. }
  13791. /**
  13792. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  13793. * a plain `Array` instance.
  13794. *
  13795. * @augments BufferAttribute
  13796. */
  13797. class Uint16BufferAttribute extends BufferAttribute {
  13798. /**
  13799. * Constructs a new buffer attribute.
  13800. *
  13801. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13802. * @param {number} itemSize - The item size.
  13803. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13804. */
  13805. constructor( array, itemSize, normalized ) {
  13806. super( new Uint16Array( array ), itemSize, normalized );
  13807. }
  13808. }
  13809. /**
  13810. * Convenient class that can be used when creating a `Int32` buffer attribute with
  13811. * a plain `Array` instance.
  13812. *
  13813. * @augments BufferAttribute
  13814. */
  13815. class Int32BufferAttribute extends BufferAttribute {
  13816. /**
  13817. * Constructs a new buffer attribute.
  13818. *
  13819. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  13820. * @param {number} itemSize - The item size.
  13821. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13822. */
  13823. constructor( array, itemSize, normalized ) {
  13824. super( new Int32Array( array ), itemSize, normalized );
  13825. }
  13826. }
  13827. /**
  13828. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  13829. * a plain `Array` instance.
  13830. *
  13831. * @augments BufferAttribute
  13832. */
  13833. class Uint32BufferAttribute extends BufferAttribute {
  13834. /**
  13835. * Constructs a new buffer attribute.
  13836. *
  13837. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  13838. * @param {number} itemSize - The item size.
  13839. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13840. */
  13841. constructor( array, itemSize, normalized ) {
  13842. super( new Uint32Array( array ), itemSize, normalized );
  13843. }
  13844. }
  13845. /**
  13846. * Convenient class that can be used when creating a `Float16` buffer attribute with
  13847. * a plain `Array` instance.
  13848. *
  13849. * This class automatically converts to and from FP16 since `Float16Array` is not
  13850. * natively supported in JavaScript.
  13851. *
  13852. * @augments BufferAttribute
  13853. */
  13854. class Float16BufferAttribute extends BufferAttribute {
  13855. /**
  13856. * Constructs a new buffer attribute.
  13857. *
  13858. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13859. * @param {number} itemSize - The item size.
  13860. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13861. */
  13862. constructor( array, itemSize, normalized ) {
  13863. super( new Uint16Array( array ), itemSize, normalized );
  13864. this.isFloat16BufferAttribute = true;
  13865. }
  13866. getX( index ) {
  13867. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  13868. if ( this.normalized ) x = denormalize( x, this.array );
  13869. return x;
  13870. }
  13871. setX( index, x ) {
  13872. if ( this.normalized ) x = normalize( x, this.array );
  13873. this.array[ index * this.itemSize ] = toHalfFloat( x );
  13874. return this;
  13875. }
  13876. getY( index ) {
  13877. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  13878. if ( this.normalized ) y = denormalize( y, this.array );
  13879. return y;
  13880. }
  13881. setY( index, y ) {
  13882. if ( this.normalized ) y = normalize( y, this.array );
  13883. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  13884. return this;
  13885. }
  13886. getZ( index ) {
  13887. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  13888. if ( this.normalized ) z = denormalize( z, this.array );
  13889. return z;
  13890. }
  13891. setZ( index, z ) {
  13892. if ( this.normalized ) z = normalize( z, this.array );
  13893. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  13894. return this;
  13895. }
  13896. getW( index ) {
  13897. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  13898. if ( this.normalized ) w = denormalize( w, this.array );
  13899. return w;
  13900. }
  13901. setW( index, w ) {
  13902. if ( this.normalized ) w = normalize( w, this.array );
  13903. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  13904. return this;
  13905. }
  13906. setXY( index, x, y ) {
  13907. index *= this.itemSize;
  13908. if ( this.normalized ) {
  13909. x = normalize( x, this.array );
  13910. y = normalize( y, this.array );
  13911. }
  13912. this.array[ index + 0 ] = toHalfFloat( x );
  13913. this.array[ index + 1 ] = toHalfFloat( y );
  13914. return this;
  13915. }
  13916. setXYZ( index, x, y, z ) {
  13917. index *= this.itemSize;
  13918. if ( this.normalized ) {
  13919. x = normalize( x, this.array );
  13920. y = normalize( y, this.array );
  13921. z = normalize( z, this.array );
  13922. }
  13923. this.array[ index + 0 ] = toHalfFloat( x );
  13924. this.array[ index + 1 ] = toHalfFloat( y );
  13925. this.array[ index + 2 ] = toHalfFloat( z );
  13926. return this;
  13927. }
  13928. setXYZW( index, x, y, z, w ) {
  13929. index *= this.itemSize;
  13930. if ( this.normalized ) {
  13931. x = normalize( x, this.array );
  13932. y = normalize( y, this.array );
  13933. z = normalize( z, this.array );
  13934. w = normalize( w, this.array );
  13935. }
  13936. this.array[ index + 0 ] = toHalfFloat( x );
  13937. this.array[ index + 1 ] = toHalfFloat( y );
  13938. this.array[ index + 2 ] = toHalfFloat( z );
  13939. this.array[ index + 3 ] = toHalfFloat( w );
  13940. return this;
  13941. }
  13942. }
  13943. /**
  13944. * Convenient class that can be used when creating a `Float32` buffer attribute with
  13945. * a plain `Array` instance.
  13946. *
  13947. * @augments BufferAttribute
  13948. */
  13949. class Float32BufferAttribute extends BufferAttribute {
  13950. /**
  13951. * Constructs a new buffer attribute.
  13952. *
  13953. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  13954. * @param {number} itemSize - The item size.
  13955. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13956. */
  13957. constructor( array, itemSize, normalized ) {
  13958. super( new Float32Array( array ), itemSize, normalized );
  13959. }
  13960. }
  13961. let _id$2 = 0;
  13962. const _m1$2 = /*@__PURE__*/ new Matrix4();
  13963. const _obj = /*@__PURE__*/ new Object3D();
  13964. const _offset = /*@__PURE__*/ new Vector3();
  13965. const _box$2 = /*@__PURE__*/ new Box3();
  13966. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  13967. const _vector$8 = /*@__PURE__*/ new Vector3();
  13968. /**
  13969. * A representation of mesh, line, or point geometry. Includes vertex
  13970. * positions, face indices, normals, colors, UVs, and custom attributes
  13971. * within buffers, reducing the cost of passing all this data to the GPU.
  13972. *
  13973. * ```js
  13974. * const geometry = new THREE.BufferGeometry();
  13975. * // create a simple square shape. We duplicate the top left and bottom right
  13976. * // vertices because each vertex needs to appear once per triangle.
  13977. * const vertices = new Float32Array( [
  13978. * -1.0, -1.0, 1.0, // v0
  13979. * 1.0, -1.0, 1.0, // v1
  13980. * 1.0, 1.0, 1.0, // v2
  13981. *
  13982. * 1.0, 1.0, 1.0, // v3
  13983. * -1.0, 1.0, 1.0, // v4
  13984. * -1.0, -1.0, 1.0 // v5
  13985. * ] );
  13986. * // itemSize = 3 because there are 3 values (components) per vertex
  13987. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  13988. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  13989. * const mesh = new THREE.Mesh( geometry, material );
  13990. * ```
  13991. *
  13992. * @augments EventDispatcher
  13993. */
  13994. class BufferGeometry extends EventDispatcher {
  13995. /**
  13996. * Constructs a new geometry.
  13997. */
  13998. constructor() {
  13999. super();
  14000. /**
  14001. * This flag can be used for type testing.
  14002. *
  14003. * @type {boolean}
  14004. * @readonly
  14005. * @default true
  14006. */
  14007. this.isBufferGeometry = true;
  14008. /**
  14009. * The ID of the geometry.
  14010. *
  14011. * @name BufferGeometry#id
  14012. * @type {number}
  14013. * @readonly
  14014. */
  14015. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  14016. /**
  14017. * The UUID of the geometry.
  14018. *
  14019. * @type {string}
  14020. * @readonly
  14021. */
  14022. this.uuid = generateUUID();
  14023. /**
  14024. * The name of the geometry.
  14025. *
  14026. * @type {string}
  14027. */
  14028. this.name = '';
  14029. this.type = 'BufferGeometry';
  14030. /**
  14031. * Allows for vertices to be re-used across multiple triangles; this is
  14032. * called using "indexed triangles". Each triangle is associated with the
  14033. * indices of three vertices. This attribute therefore stores the index of
  14034. * each vertex for each triangular face. If this attribute is not set, the
  14035. * renderer assumes that each three contiguous positions represent a single triangle.
  14036. *
  14037. * @type {?BufferAttribute}
  14038. * @default null
  14039. */
  14040. this.index = null;
  14041. /**
  14042. * A (storage) buffer attribute which was generated with a compute shader and
  14043. * now defines indirect draw calls.
  14044. *
  14045. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14046. *
  14047. * @type {?BufferAttribute}
  14048. * @default null
  14049. */
  14050. this.indirect = null;
  14051. /**
  14052. * This dictionary has as id the name of the attribute to be set and as value
  14053. * the buffer attribute to set it to. Rather than accessing this property directly,
  14054. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  14055. *
  14056. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  14057. */
  14058. this.attributes = {};
  14059. /**
  14060. * This dictionary holds the morph targets of the geometry.
  14061. *
  14062. * Note: Once the geometry has been rendered, the morph attribute data cannot
  14063. * be changed. You will have to call `dispose()?, and create a new geometry instance.
  14064. *
  14065. * @type {Object}
  14066. */
  14067. this.morphAttributes = {};
  14068. /**
  14069. * Used to control the morph target behavior; when set to `true`, the morph
  14070. * target data is treated as relative offsets, rather than as absolute
  14071. * positions/normals.
  14072. *
  14073. * @type {boolean}
  14074. * @default false
  14075. */
  14076. this.morphTargetsRelative = false;
  14077. /**
  14078. * Split the geometry into groups, each of which will be rendered in a
  14079. * separate draw call. This allows an array of materials to be used with the geometry.
  14080. *
  14081. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  14082. *
  14083. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  14084. * indices, and must not leave vertices or indices unused.
  14085. *
  14086. * @type {Array<Object>}
  14087. */
  14088. this.groups = [];
  14089. /**
  14090. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  14091. *
  14092. * @type {Box3}
  14093. * @default null
  14094. */
  14095. this.boundingBox = null;
  14096. /**
  14097. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  14098. *
  14099. * @type {Sphere}
  14100. * @default null
  14101. */
  14102. this.boundingSphere = null;
  14103. /**
  14104. * Determines the part of the geometry to render. This should not be set directly,
  14105. * instead use `setDrawRange()`.
  14106. *
  14107. * @type {{start:number,count:number}}
  14108. */
  14109. this.drawRange = { start: 0, count: Infinity };
  14110. /**
  14111. * An object that can be used to store custom data about the geometry.
  14112. * It should not hold references to functions as these will not be cloned.
  14113. *
  14114. * @type {Object}
  14115. */
  14116. this.userData = {};
  14117. }
  14118. /**
  14119. * Returns the index of this geometry.
  14120. *
  14121. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  14122. */
  14123. getIndex() {
  14124. return this.index;
  14125. }
  14126. /**
  14127. * Sets the given index to this geometry.
  14128. *
  14129. * @param {Array<number>|BufferAttribute} index - The index to set.
  14130. * @return {BufferGeometry} A reference to this instance.
  14131. */
  14132. setIndex( index ) {
  14133. if ( Array.isArray( index ) ) {
  14134. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  14135. } else {
  14136. this.index = index;
  14137. }
  14138. return this;
  14139. }
  14140. /**
  14141. * Sets the given indirect attribute to this geometry.
  14142. *
  14143. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  14144. * @return {BufferGeometry} A reference to this instance.
  14145. */
  14146. setIndirect( indirect ) {
  14147. this.indirect = indirect;
  14148. return this;
  14149. }
  14150. /**
  14151. * Returns the indirect attribute of this geometry.
  14152. *
  14153. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  14154. */
  14155. getIndirect() {
  14156. return this.indirect;
  14157. }
  14158. /**
  14159. * Returns the buffer attribute for the given name.
  14160. *
  14161. * @param {string} name - The attribute name.
  14162. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  14163. * Returns `undefined` if not attribute has been found.
  14164. */
  14165. getAttribute( name ) {
  14166. return this.attributes[ name ];
  14167. }
  14168. /**
  14169. * Sets the given attribute for the given name.
  14170. *
  14171. * @param {string} name - The attribute name.
  14172. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  14173. * @return {BufferGeometry} A reference to this instance.
  14174. */
  14175. setAttribute( name, attribute ) {
  14176. this.attributes[ name ] = attribute;
  14177. return this;
  14178. }
  14179. /**
  14180. * Deletes the attribute for the given name.
  14181. *
  14182. * @param {string} name - The attribute name to delete.
  14183. * @return {BufferGeometry} A reference to this instance.
  14184. */
  14185. deleteAttribute( name ) {
  14186. delete this.attributes[ name ];
  14187. return this;
  14188. }
  14189. /**
  14190. * Returns `true` if this geometry has an attribute for the given name.
  14191. *
  14192. * @param {string} name - The attribute name.
  14193. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  14194. */
  14195. hasAttribute( name ) {
  14196. return this.attributes[ name ] !== undefined;
  14197. }
  14198. /**
  14199. * Adds a group to this geometry.
  14200. *
  14201. * @param {number} start - The first element in this draw call. That is the first
  14202. * vertex for non-indexed geometry, otherwise the first triangle index.
  14203. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  14204. * @param {number} [materialIndex=0] - The material array index to use.
  14205. */
  14206. addGroup( start, count, materialIndex = 0 ) {
  14207. this.groups.push( {
  14208. start: start,
  14209. count: count,
  14210. materialIndex: materialIndex
  14211. } );
  14212. }
  14213. /**
  14214. * Clears all groups.
  14215. */
  14216. clearGroups() {
  14217. this.groups = [];
  14218. }
  14219. /**
  14220. * Sets the draw range for this geometry.
  14221. *
  14222. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  14223. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  14224. * For indexed BufferGeometry, `count` is the number of indices to render.
  14225. */
  14226. setDrawRange( start, count ) {
  14227. this.drawRange.start = start;
  14228. this.drawRange.count = count;
  14229. }
  14230. /**
  14231. * Applies the given 4x4 transformation matrix to the geometry.
  14232. *
  14233. * @param {Matrix4} matrix - The matrix to apply.
  14234. * @return {BufferGeometry} A reference to this instance.
  14235. */
  14236. applyMatrix4( matrix ) {
  14237. const position = this.attributes.position;
  14238. if ( position !== undefined ) {
  14239. position.applyMatrix4( matrix );
  14240. position.needsUpdate = true;
  14241. }
  14242. const normal = this.attributes.normal;
  14243. if ( normal !== undefined ) {
  14244. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  14245. normal.applyNormalMatrix( normalMatrix );
  14246. normal.needsUpdate = true;
  14247. }
  14248. const tangent = this.attributes.tangent;
  14249. if ( tangent !== undefined ) {
  14250. tangent.transformDirection( matrix );
  14251. tangent.needsUpdate = true;
  14252. }
  14253. if ( this.boundingBox !== null ) {
  14254. this.computeBoundingBox();
  14255. }
  14256. if ( this.boundingSphere !== null ) {
  14257. this.computeBoundingSphere();
  14258. }
  14259. return this;
  14260. }
  14261. /**
  14262. * Applies the rotation represented by the Quaternion to the geometry.
  14263. *
  14264. * @param {Quaternion} q - The Quaternion to apply.
  14265. * @return {BufferGeometry} A reference to this instance.
  14266. */
  14267. applyQuaternion( q ) {
  14268. _m1$2.makeRotationFromQuaternion( q );
  14269. this.applyMatrix4( _m1$2 );
  14270. return this;
  14271. }
  14272. /**
  14273. * Rotates the geometry about the X axis. This is typically done as a one time
  14274. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14275. * real-time mesh rotation.
  14276. *
  14277. * @param {number} angle - The angle in radians.
  14278. * @return {BufferGeometry} A reference to this instance.
  14279. */
  14280. rotateX( angle ) {
  14281. // rotate geometry around world x-axis
  14282. _m1$2.makeRotationX( angle );
  14283. this.applyMatrix4( _m1$2 );
  14284. return this;
  14285. }
  14286. /**
  14287. * Rotates the geometry about the Y axis. This is typically done as a one time
  14288. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14289. * real-time mesh rotation.
  14290. *
  14291. * @param {number} angle - The angle in radians.
  14292. * @return {BufferGeometry} A reference to this instance.
  14293. */
  14294. rotateY( angle ) {
  14295. // rotate geometry around world y-axis
  14296. _m1$2.makeRotationY( angle );
  14297. this.applyMatrix4( _m1$2 );
  14298. return this;
  14299. }
  14300. /**
  14301. * Rotates the geometry about the Z axis. This is typically done as a one time
  14302. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14303. * real-time mesh rotation.
  14304. *
  14305. * @param {number} angle - The angle in radians.
  14306. * @return {BufferGeometry} A reference to this instance.
  14307. */
  14308. rotateZ( angle ) {
  14309. // rotate geometry around world z-axis
  14310. _m1$2.makeRotationZ( angle );
  14311. this.applyMatrix4( _m1$2 );
  14312. return this;
  14313. }
  14314. /**
  14315. * Translates the geometry. This is typically done as a one time
  14316. * operation, and not during a loop. Use {@link Object3D#position} for typical
  14317. * real-time mesh rotation.
  14318. *
  14319. * @param {number} x - The x offset.
  14320. * @param {number} y - The y offset.
  14321. * @param {number} z - The z offset.
  14322. * @return {BufferGeometry} A reference to this instance.
  14323. */
  14324. translate( x, y, z ) {
  14325. // translate geometry
  14326. _m1$2.makeTranslation( x, y, z );
  14327. this.applyMatrix4( _m1$2 );
  14328. return this;
  14329. }
  14330. /**
  14331. * Scales the geometry. This is typically done as a one time
  14332. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14333. * real-time mesh rotation.
  14334. *
  14335. * @param {number} x - The x scale.
  14336. * @param {number} y - The y scale.
  14337. * @param {number} z - The z scale.
  14338. * @return {BufferGeometry} A reference to this instance.
  14339. */
  14340. scale( x, y, z ) {
  14341. // scale geometry
  14342. _m1$2.makeScale( x, y, z );
  14343. this.applyMatrix4( _m1$2 );
  14344. return this;
  14345. }
  14346. /**
  14347. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14348. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14349. * real-time mesh rotation.
  14350. *
  14351. * @param {Vector3} vector - The target point.
  14352. * @return {BufferGeometry} A reference to this instance.
  14353. */
  14354. lookAt( vector ) {
  14355. _obj.lookAt( vector );
  14356. _obj.updateMatrix();
  14357. this.applyMatrix4( _obj.matrix );
  14358. return this;
  14359. }
  14360. /**
  14361. * Center the geometry based on its bounding box.
  14362. *
  14363. * @return {BufferGeometry} A reference to this instance.
  14364. */
  14365. center() {
  14366. this.computeBoundingBox();
  14367. this.boundingBox.getCenter( _offset ).negate();
  14368. this.translate( _offset.x, _offset.y, _offset.z );
  14369. return this;
  14370. }
  14371. /**
  14372. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14373. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14374. * set to `0`.
  14375. *
  14376. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14377. * data from the array. The length of the array must match the vertex count.
  14378. *
  14379. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14380. * @return {BufferGeometry} A reference to this instance.
  14381. */
  14382. setFromPoints( points ) {
  14383. const positionAttribute = this.getAttribute( 'position' );
  14384. if ( positionAttribute === undefined ) {
  14385. const position = [];
  14386. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14387. const point = points[ i ];
  14388. position.push( point.x, point.y, point.z || 0 );
  14389. }
  14390. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14391. } else {
  14392. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14393. for ( let i = 0; i < l; i ++ ) {
  14394. const point = points[ i ];
  14395. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14396. }
  14397. if ( points.length > positionAttribute.count ) {
  14398. console.warn( 'THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14399. }
  14400. positionAttribute.needsUpdate = true;
  14401. }
  14402. return this;
  14403. }
  14404. /**
  14405. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14406. * The bounding box is not computed by the engine; it must be computed by your app.
  14407. * You may need to recompute the bounding box if the geometry vertices are modified.
  14408. */
  14409. computeBoundingBox() {
  14410. if ( this.boundingBox === null ) {
  14411. this.boundingBox = new Box3();
  14412. }
  14413. const position = this.attributes.position;
  14414. const morphAttributesPosition = this.morphAttributes.position;
  14415. if ( position && position.isGLBufferAttribute ) {
  14416. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14417. this.boundingBox.set(
  14418. new Vector3( - Infinity, - Infinity, - Infinity ),
  14419. new Vector3( + Infinity, + Infinity, + Infinity )
  14420. );
  14421. return;
  14422. }
  14423. if ( position !== undefined ) {
  14424. this.boundingBox.setFromBufferAttribute( position );
  14425. // process morph attributes if present
  14426. if ( morphAttributesPosition ) {
  14427. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14428. const morphAttribute = morphAttributesPosition[ i ];
  14429. _box$2.setFromBufferAttribute( morphAttribute );
  14430. if ( this.morphTargetsRelative ) {
  14431. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  14432. this.boundingBox.expandByPoint( _vector$8 );
  14433. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  14434. this.boundingBox.expandByPoint( _vector$8 );
  14435. } else {
  14436. this.boundingBox.expandByPoint( _box$2.min );
  14437. this.boundingBox.expandByPoint( _box$2.max );
  14438. }
  14439. }
  14440. }
  14441. } else {
  14442. this.boundingBox.makeEmpty();
  14443. }
  14444. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14445. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14446. }
  14447. }
  14448. /**
  14449. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14450. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14451. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14452. */
  14453. computeBoundingSphere() {
  14454. if ( this.boundingSphere === null ) {
  14455. this.boundingSphere = new Sphere();
  14456. }
  14457. const position = this.attributes.position;
  14458. const morphAttributesPosition = this.morphAttributes.position;
  14459. if ( position && position.isGLBufferAttribute ) {
  14460. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14461. this.boundingSphere.set( new Vector3(), Infinity );
  14462. return;
  14463. }
  14464. if ( position ) {
  14465. // first, find the center of the bounding sphere
  14466. const center = this.boundingSphere.center;
  14467. _box$2.setFromBufferAttribute( position );
  14468. // process morph attributes if present
  14469. if ( morphAttributesPosition ) {
  14470. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14471. const morphAttribute = morphAttributesPosition[ i ];
  14472. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14473. if ( this.morphTargetsRelative ) {
  14474. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  14475. _box$2.expandByPoint( _vector$8 );
  14476. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  14477. _box$2.expandByPoint( _vector$8 );
  14478. } else {
  14479. _box$2.expandByPoint( _boxMorphTargets.min );
  14480. _box$2.expandByPoint( _boxMorphTargets.max );
  14481. }
  14482. }
  14483. }
  14484. _box$2.getCenter( center );
  14485. // second, try to find a boundingSphere with a radius smaller than the
  14486. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14487. let maxRadiusSq = 0;
  14488. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14489. _vector$8.fromBufferAttribute( position, i );
  14490. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14491. }
  14492. // process morph attributes if present
  14493. if ( morphAttributesPosition ) {
  14494. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14495. const morphAttribute = morphAttributesPosition[ i ];
  14496. const morphTargetsRelative = this.morphTargetsRelative;
  14497. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14498. _vector$8.fromBufferAttribute( morphAttribute, j );
  14499. if ( morphTargetsRelative ) {
  14500. _offset.fromBufferAttribute( position, j );
  14501. _vector$8.add( _offset );
  14502. }
  14503. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14504. }
  14505. }
  14506. }
  14507. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14508. if ( isNaN( this.boundingSphere.radius ) ) {
  14509. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14510. }
  14511. }
  14512. }
  14513. /**
  14514. * Calculates and adds a tangent attribute to this geometry.
  14515. *
  14516. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14517. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14518. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14519. */
  14520. computeTangents() {
  14521. const index = this.index;
  14522. const attributes = this.attributes;
  14523. // based on http://www.terathon.com/code/tangent.html
  14524. // (per vertex tangents)
  14525. if ( index === null ||
  14526. attributes.position === undefined ||
  14527. attributes.normal === undefined ||
  14528. attributes.uv === undefined ) {
  14529. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14530. return;
  14531. }
  14532. const positionAttribute = attributes.position;
  14533. const normalAttribute = attributes.normal;
  14534. const uvAttribute = attributes.uv;
  14535. if ( this.hasAttribute( 'tangent' ) === false ) {
  14536. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14537. }
  14538. const tangentAttribute = this.getAttribute( 'tangent' );
  14539. const tan1 = [], tan2 = [];
  14540. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14541. tan1[ i ] = new Vector3();
  14542. tan2[ i ] = new Vector3();
  14543. }
  14544. const vA = new Vector3(),
  14545. vB = new Vector3(),
  14546. vC = new Vector3(),
  14547. uvA = new Vector2(),
  14548. uvB = new Vector2(),
  14549. uvC = new Vector2(),
  14550. sdir = new Vector3(),
  14551. tdir = new Vector3();
  14552. function handleTriangle( a, b, c ) {
  14553. vA.fromBufferAttribute( positionAttribute, a );
  14554. vB.fromBufferAttribute( positionAttribute, b );
  14555. vC.fromBufferAttribute( positionAttribute, c );
  14556. uvA.fromBufferAttribute( uvAttribute, a );
  14557. uvB.fromBufferAttribute( uvAttribute, b );
  14558. uvC.fromBufferAttribute( uvAttribute, c );
  14559. vB.sub( vA );
  14560. vC.sub( vA );
  14561. uvB.sub( uvA );
  14562. uvC.sub( uvA );
  14563. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14564. // silently ignore degenerate uv triangles having coincident or colinear vertices
  14565. if ( ! isFinite( r ) ) return;
  14566. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  14567. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  14568. tan1[ a ].add( sdir );
  14569. tan1[ b ].add( sdir );
  14570. tan1[ c ].add( sdir );
  14571. tan2[ a ].add( tdir );
  14572. tan2[ b ].add( tdir );
  14573. tan2[ c ].add( tdir );
  14574. }
  14575. let groups = this.groups;
  14576. if ( groups.length === 0 ) {
  14577. groups = [ {
  14578. start: 0,
  14579. count: index.count
  14580. } ];
  14581. }
  14582. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14583. const group = groups[ i ];
  14584. const start = group.start;
  14585. const count = group.count;
  14586. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14587. handleTriangle(
  14588. index.getX( j + 0 ),
  14589. index.getX( j + 1 ),
  14590. index.getX( j + 2 )
  14591. );
  14592. }
  14593. }
  14594. const tmp = new Vector3(), tmp2 = new Vector3();
  14595. const n = new Vector3(), n2 = new Vector3();
  14596. function handleVertex( v ) {
  14597. n.fromBufferAttribute( normalAttribute, v );
  14598. n2.copy( n );
  14599. const t = tan1[ v ];
  14600. // Gram-Schmidt orthogonalize
  14601. tmp.copy( t );
  14602. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  14603. // Calculate handedness
  14604. tmp2.crossVectors( n2, t );
  14605. const test = tmp2.dot( tan2[ v ] );
  14606. const w = ( test < 0.0 ) ? -1 : 1.0;
  14607. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  14608. }
  14609. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14610. const group = groups[ i ];
  14611. const start = group.start;
  14612. const count = group.count;
  14613. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14614. handleVertex( index.getX( j + 0 ) );
  14615. handleVertex( index.getX( j + 1 ) );
  14616. handleVertex( index.getX( j + 2 ) );
  14617. }
  14618. }
  14619. }
  14620. /**
  14621. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  14622. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  14623. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  14624. * to be the same as the face normal.
  14625. */
  14626. computeVertexNormals() {
  14627. const index = this.index;
  14628. const positionAttribute = this.getAttribute( 'position' );
  14629. if ( positionAttribute !== undefined ) {
  14630. let normalAttribute = this.getAttribute( 'normal' );
  14631. if ( normalAttribute === undefined ) {
  14632. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  14633. this.setAttribute( 'normal', normalAttribute );
  14634. } else {
  14635. // reset existing normals to zero
  14636. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  14637. normalAttribute.setXYZ( i, 0, 0, 0 );
  14638. }
  14639. }
  14640. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  14641. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  14642. const cb = new Vector3(), ab = new Vector3();
  14643. // indexed elements
  14644. if ( index ) {
  14645. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  14646. const vA = index.getX( i + 0 );
  14647. const vB = index.getX( i + 1 );
  14648. const vC = index.getX( i + 2 );
  14649. pA.fromBufferAttribute( positionAttribute, vA );
  14650. pB.fromBufferAttribute( positionAttribute, vB );
  14651. pC.fromBufferAttribute( positionAttribute, vC );
  14652. cb.subVectors( pC, pB );
  14653. ab.subVectors( pA, pB );
  14654. cb.cross( ab );
  14655. nA.fromBufferAttribute( normalAttribute, vA );
  14656. nB.fromBufferAttribute( normalAttribute, vB );
  14657. nC.fromBufferAttribute( normalAttribute, vC );
  14658. nA.add( cb );
  14659. nB.add( cb );
  14660. nC.add( cb );
  14661. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  14662. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  14663. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  14664. }
  14665. } else {
  14666. // non-indexed elements (unconnected triangle soup)
  14667. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  14668. pA.fromBufferAttribute( positionAttribute, i + 0 );
  14669. pB.fromBufferAttribute( positionAttribute, i + 1 );
  14670. pC.fromBufferAttribute( positionAttribute, i + 2 );
  14671. cb.subVectors( pC, pB );
  14672. ab.subVectors( pA, pB );
  14673. cb.cross( ab );
  14674. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  14675. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  14676. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  14677. }
  14678. }
  14679. this.normalizeNormals();
  14680. normalAttribute.needsUpdate = true;
  14681. }
  14682. }
  14683. /**
  14684. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  14685. * correct lighting on the geometry surfaces.
  14686. */
  14687. normalizeNormals() {
  14688. const normals = this.attributes.normal;
  14689. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  14690. _vector$8.fromBufferAttribute( normals, i );
  14691. _vector$8.normalize();
  14692. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14693. }
  14694. }
  14695. /**
  14696. * Return a new non-index version of this indexed geometry. If the geometry
  14697. * is already non-indexed, the method is a NOOP.
  14698. *
  14699. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  14700. */
  14701. toNonIndexed() {
  14702. function convertBufferAttribute( attribute, indices ) {
  14703. const array = attribute.array;
  14704. const itemSize = attribute.itemSize;
  14705. const normalized = attribute.normalized;
  14706. const array2 = new array.constructor( indices.length * itemSize );
  14707. let index = 0, index2 = 0;
  14708. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  14709. if ( attribute.isInterleavedBufferAttribute ) {
  14710. index = indices[ i ] * attribute.data.stride + attribute.offset;
  14711. } else {
  14712. index = indices[ i ] * itemSize;
  14713. }
  14714. for ( let j = 0; j < itemSize; j ++ ) {
  14715. array2[ index2 ++ ] = array[ index ++ ];
  14716. }
  14717. }
  14718. return new BufferAttribute( array2, itemSize, normalized );
  14719. }
  14720. //
  14721. if ( this.index === null ) {
  14722. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  14723. return this;
  14724. }
  14725. const geometry2 = new BufferGeometry();
  14726. const indices = this.index.array;
  14727. const attributes = this.attributes;
  14728. // attributes
  14729. for ( const name in attributes ) {
  14730. const attribute = attributes[ name ];
  14731. const newAttribute = convertBufferAttribute( attribute, indices );
  14732. geometry2.setAttribute( name, newAttribute );
  14733. }
  14734. // morph attributes
  14735. const morphAttributes = this.morphAttributes;
  14736. for ( const name in morphAttributes ) {
  14737. const morphArray = [];
  14738. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14739. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  14740. const attribute = morphAttribute[ i ];
  14741. const newAttribute = convertBufferAttribute( attribute, indices );
  14742. morphArray.push( newAttribute );
  14743. }
  14744. geometry2.morphAttributes[ name ] = morphArray;
  14745. }
  14746. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  14747. // groups
  14748. const groups = this.groups;
  14749. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14750. const group = groups[ i ];
  14751. geometry2.addGroup( group.start, group.count, group.materialIndex );
  14752. }
  14753. return geometry2;
  14754. }
  14755. /**
  14756. * Serializes the geometry into JSON.
  14757. *
  14758. * @return {Object} A JSON object representing the serialized geometry.
  14759. */
  14760. toJSON() {
  14761. const data = {
  14762. metadata: {
  14763. version: 4.6,
  14764. type: 'BufferGeometry',
  14765. generator: 'BufferGeometry.toJSON'
  14766. }
  14767. };
  14768. // standard BufferGeometry serialization
  14769. data.uuid = this.uuid;
  14770. data.type = this.type;
  14771. if ( this.name !== '' ) data.name = this.name;
  14772. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  14773. if ( this.parameters !== undefined ) {
  14774. const parameters = this.parameters;
  14775. for ( const key in parameters ) {
  14776. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  14777. }
  14778. return data;
  14779. }
  14780. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  14781. data.data = { attributes: {} };
  14782. const index = this.index;
  14783. if ( index !== null ) {
  14784. data.data.index = {
  14785. type: index.array.constructor.name,
  14786. array: Array.prototype.slice.call( index.array )
  14787. };
  14788. }
  14789. const attributes = this.attributes;
  14790. for ( const key in attributes ) {
  14791. const attribute = attributes[ key ];
  14792. data.data.attributes[ key ] = attribute.toJSON( data.data );
  14793. }
  14794. const morphAttributes = {};
  14795. let hasMorphAttributes = false;
  14796. for ( const key in this.morphAttributes ) {
  14797. const attributeArray = this.morphAttributes[ key ];
  14798. const array = [];
  14799. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  14800. const attribute = attributeArray[ i ];
  14801. array.push( attribute.toJSON( data.data ) );
  14802. }
  14803. if ( array.length > 0 ) {
  14804. morphAttributes[ key ] = array;
  14805. hasMorphAttributes = true;
  14806. }
  14807. }
  14808. if ( hasMorphAttributes ) {
  14809. data.data.morphAttributes = morphAttributes;
  14810. data.data.morphTargetsRelative = this.morphTargetsRelative;
  14811. }
  14812. const groups = this.groups;
  14813. if ( groups.length > 0 ) {
  14814. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  14815. }
  14816. const boundingSphere = this.boundingSphere;
  14817. if ( boundingSphere !== null ) {
  14818. data.data.boundingSphere = {
  14819. center: boundingSphere.center.toArray(),
  14820. radius: boundingSphere.radius
  14821. };
  14822. }
  14823. return data;
  14824. }
  14825. /**
  14826. * Returns a new geometry with copied values from this instance.
  14827. *
  14828. * @return {BufferGeometry} A clone of this instance.
  14829. */
  14830. clone() {
  14831. return new this.constructor().copy( this );
  14832. }
  14833. /**
  14834. * Copies the values of the given geometry to this instance.
  14835. *
  14836. * @param {BufferGeometry} source - The geometry to copy.
  14837. * @return {BufferGeometry} A reference to this instance.
  14838. */
  14839. copy( source ) {
  14840. // reset
  14841. this.index = null;
  14842. this.attributes = {};
  14843. this.morphAttributes = {};
  14844. this.groups = [];
  14845. this.boundingBox = null;
  14846. this.boundingSphere = null;
  14847. // used for storing cloned, shared data
  14848. const data = {};
  14849. // name
  14850. this.name = source.name;
  14851. // index
  14852. const index = source.index;
  14853. if ( index !== null ) {
  14854. this.setIndex( index.clone() );
  14855. }
  14856. // attributes
  14857. const attributes = source.attributes;
  14858. for ( const name in attributes ) {
  14859. const attribute = attributes[ name ];
  14860. this.setAttribute( name, attribute.clone( data ) );
  14861. }
  14862. // morph attributes
  14863. const morphAttributes = source.morphAttributes;
  14864. for ( const name in morphAttributes ) {
  14865. const array = [];
  14866. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14867. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  14868. array.push( morphAttribute[ i ].clone( data ) );
  14869. }
  14870. this.morphAttributes[ name ] = array;
  14871. }
  14872. this.morphTargetsRelative = source.morphTargetsRelative;
  14873. // groups
  14874. const groups = source.groups;
  14875. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14876. const group = groups[ i ];
  14877. this.addGroup( group.start, group.count, group.materialIndex );
  14878. }
  14879. // bounding box
  14880. const boundingBox = source.boundingBox;
  14881. if ( boundingBox !== null ) {
  14882. this.boundingBox = boundingBox.clone();
  14883. }
  14884. // bounding sphere
  14885. const boundingSphere = source.boundingSphere;
  14886. if ( boundingSphere !== null ) {
  14887. this.boundingSphere = boundingSphere.clone();
  14888. }
  14889. // draw range
  14890. this.drawRange.start = source.drawRange.start;
  14891. this.drawRange.count = source.drawRange.count;
  14892. // user data
  14893. this.userData = source.userData;
  14894. return this;
  14895. }
  14896. /**
  14897. * Frees the GPU-related resources allocated by this instance. Call this
  14898. * method whenever this instance is no longer used in your app.
  14899. *
  14900. * @fires BufferGeometry#dispose
  14901. */
  14902. dispose() {
  14903. this.dispatchEvent( { type: 'dispose' } );
  14904. }
  14905. }
  14906. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  14907. const _ray$3 = /*@__PURE__*/ new Ray();
  14908. const _sphere$6 = /*@__PURE__*/ new Sphere();
  14909. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  14910. const _vA$1 = /*@__PURE__*/ new Vector3();
  14911. const _vB$1 = /*@__PURE__*/ new Vector3();
  14912. const _vC$1 = /*@__PURE__*/ new Vector3();
  14913. const _tempA = /*@__PURE__*/ new Vector3();
  14914. const _morphA = /*@__PURE__*/ new Vector3();
  14915. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  14916. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  14917. /**
  14918. * Class representing triangular polygon mesh based objects.
  14919. *
  14920. * ```js
  14921. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  14922. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  14923. * const mesh = new THREE.Mesh( geometry, material );
  14924. * scene.add( mesh );
  14925. * ```
  14926. *
  14927. * @augments Object3D
  14928. */
  14929. class Mesh extends Object3D {
  14930. /**
  14931. * Constructs a new mesh.
  14932. *
  14933. * @param {BufferGeometry} [geometry] - The mesh geometry.
  14934. * @param {Material|Array<Material>} [material] - The mesh material.
  14935. */
  14936. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  14937. super();
  14938. /**
  14939. * This flag can be used for type testing.
  14940. *
  14941. * @type {boolean}
  14942. * @readonly
  14943. * @default true
  14944. */
  14945. this.isMesh = true;
  14946. this.type = 'Mesh';
  14947. /**
  14948. * The mesh geometry.
  14949. *
  14950. * @type {BufferGeometry}
  14951. */
  14952. this.geometry = geometry;
  14953. /**
  14954. * The mesh material.
  14955. *
  14956. * @type {Material|Array<Material>}
  14957. * @default MeshBasicMaterial
  14958. */
  14959. this.material = material;
  14960. /**
  14961. * A dictionary representing the morph targets in the geometry. The key is the
  14962. * morph targets name, the value its attribute index. This member is `undefined`
  14963. * by default and only set when morph targets are detected in the geometry.
  14964. *
  14965. * @type {Object<String,number>|undefined}
  14966. * @default undefined
  14967. */
  14968. this.morphTargetDictionary = undefined;
  14969. /**
  14970. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  14971. * is applied. This member is `undefined` by default and only set when morph targets are
  14972. * detected in the geometry.
  14973. *
  14974. * @type {Array<number>|undefined}
  14975. * @default undefined
  14976. */
  14977. this.morphTargetInfluences = undefined;
  14978. this.updateMorphTargets();
  14979. }
  14980. copy( source, recursive ) {
  14981. super.copy( source, recursive );
  14982. if ( source.morphTargetInfluences !== undefined ) {
  14983. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  14984. }
  14985. if ( source.morphTargetDictionary !== undefined ) {
  14986. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  14987. }
  14988. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  14989. this.geometry = source.geometry;
  14990. return this;
  14991. }
  14992. /**
  14993. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  14994. * to make sure existing morph targets can influence this 3D object.
  14995. */
  14996. updateMorphTargets() {
  14997. const geometry = this.geometry;
  14998. const morphAttributes = geometry.morphAttributes;
  14999. const keys = Object.keys( morphAttributes );
  15000. if ( keys.length > 0 ) {
  15001. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  15002. if ( morphAttribute !== undefined ) {
  15003. this.morphTargetInfluences = [];
  15004. this.morphTargetDictionary = {};
  15005. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  15006. const name = morphAttribute[ m ].name || String( m );
  15007. this.morphTargetInfluences.push( 0 );
  15008. this.morphTargetDictionary[ name ] = m;
  15009. }
  15010. }
  15011. }
  15012. }
  15013. /**
  15014. * Returns the local-space position of the vertex at the given index, taking into
  15015. * account the current animation state of both morph targets and skinning.
  15016. *
  15017. * @param {number} index - The vertex index.
  15018. * @param {Vector3} target - The target object that is used to store the method's result.
  15019. * @return {Vector3} The vertex position in local space.
  15020. */
  15021. getVertexPosition( index, target ) {
  15022. const geometry = this.geometry;
  15023. const position = geometry.attributes.position;
  15024. const morphPosition = geometry.morphAttributes.position;
  15025. const morphTargetsRelative = geometry.morphTargetsRelative;
  15026. target.fromBufferAttribute( position, index );
  15027. const morphInfluences = this.morphTargetInfluences;
  15028. if ( morphPosition && morphInfluences ) {
  15029. _morphA.set( 0, 0, 0 );
  15030. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  15031. const influence = morphInfluences[ i ];
  15032. const morphAttribute = morphPosition[ i ];
  15033. if ( influence === 0 ) continue;
  15034. _tempA.fromBufferAttribute( morphAttribute, index );
  15035. if ( morphTargetsRelative ) {
  15036. _morphA.addScaledVector( _tempA, influence );
  15037. } else {
  15038. _morphA.addScaledVector( _tempA.sub( target ), influence );
  15039. }
  15040. }
  15041. target.add( _morphA );
  15042. }
  15043. return target;
  15044. }
  15045. /**
  15046. * Computes intersection points between a casted ray and this line.
  15047. *
  15048. * @param {Raycaster} raycaster - The raycaster.
  15049. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  15050. */
  15051. raycast( raycaster, intersects ) {
  15052. const geometry = this.geometry;
  15053. const material = this.material;
  15054. const matrixWorld = this.matrixWorld;
  15055. if ( material === undefined ) return;
  15056. // test with bounding sphere in world space
  15057. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15058. _sphere$6.copy( geometry.boundingSphere );
  15059. _sphere$6.applyMatrix4( matrixWorld );
  15060. // check distance from ray origin to bounding sphere
  15061. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  15062. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  15063. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  15064. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  15065. }
  15066. // convert ray to local space of mesh
  15067. _inverseMatrix$3.copy( matrixWorld ).invert();
  15068. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  15069. // test with bounding box in local space
  15070. if ( geometry.boundingBox !== null ) {
  15071. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  15072. }
  15073. // test for intersections with geometry
  15074. this._computeIntersections( raycaster, intersects, _ray$3 );
  15075. }
  15076. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  15077. let intersection;
  15078. const geometry = this.geometry;
  15079. const material = this.material;
  15080. const index = geometry.index;
  15081. const position = geometry.attributes.position;
  15082. const uv = geometry.attributes.uv;
  15083. const uv1 = geometry.attributes.uv1;
  15084. const normal = geometry.attributes.normal;
  15085. const groups = geometry.groups;
  15086. const drawRange = geometry.drawRange;
  15087. if ( index !== null ) {
  15088. // indexed buffer geometry
  15089. if ( Array.isArray( material ) ) {
  15090. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15091. const group = groups[ i ];
  15092. const groupMaterial = material[ group.materialIndex ];
  15093. const start = Math.max( group.start, drawRange.start );
  15094. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15095. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15096. const a = index.getX( j );
  15097. const b = index.getX( j + 1 );
  15098. const c = index.getX( j + 2 );
  15099. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15100. if ( intersection ) {
  15101. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  15102. intersection.face.materialIndex = group.materialIndex;
  15103. intersects.push( intersection );
  15104. }
  15105. }
  15106. }
  15107. } else {
  15108. const start = Math.max( 0, drawRange.start );
  15109. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15110. for ( let i = start, il = end; i < il; i += 3 ) {
  15111. const a = index.getX( i );
  15112. const b = index.getX( i + 1 );
  15113. const c = index.getX( i + 2 );
  15114. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15115. if ( intersection ) {
  15116. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  15117. intersects.push( intersection );
  15118. }
  15119. }
  15120. }
  15121. } else if ( position !== undefined ) {
  15122. // non-indexed buffer geometry
  15123. if ( Array.isArray( material ) ) {
  15124. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15125. const group = groups[ i ];
  15126. const groupMaterial = material[ group.materialIndex ];
  15127. const start = Math.max( group.start, drawRange.start );
  15128. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15129. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15130. const a = j;
  15131. const b = j + 1;
  15132. const c = j + 2;
  15133. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15134. if ( intersection ) {
  15135. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  15136. intersection.face.materialIndex = group.materialIndex;
  15137. intersects.push( intersection );
  15138. }
  15139. }
  15140. }
  15141. } else {
  15142. const start = Math.max( 0, drawRange.start );
  15143. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  15144. for ( let i = start, il = end; i < il; i += 3 ) {
  15145. const a = i;
  15146. const b = i + 1;
  15147. const c = i + 2;
  15148. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15149. if ( intersection ) {
  15150. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  15151. intersects.push( intersection );
  15152. }
  15153. }
  15154. }
  15155. }
  15156. }
  15157. }
  15158. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  15159. let intersect;
  15160. if ( material.side === BackSide ) {
  15161. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  15162. } else {
  15163. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  15164. }
  15165. if ( intersect === null ) return null;
  15166. _intersectionPointWorld.copy( point );
  15167. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  15168. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  15169. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  15170. return {
  15171. distance: distance,
  15172. point: _intersectionPointWorld.clone(),
  15173. object: object
  15174. };
  15175. }
  15176. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  15177. object.getVertexPosition( a, _vA$1 );
  15178. object.getVertexPosition( b, _vB$1 );
  15179. object.getVertexPosition( c, _vC$1 );
  15180. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  15181. if ( intersection ) {
  15182. const barycoord = new Vector3();
  15183. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  15184. if ( uv ) {
  15185. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  15186. }
  15187. if ( uv1 ) {
  15188. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  15189. }
  15190. if ( normal ) {
  15191. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  15192. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  15193. intersection.normal.multiplyScalar( -1 );
  15194. }
  15195. }
  15196. const face = {
  15197. a: a,
  15198. b: b,
  15199. c: c,
  15200. normal: new Vector3(),
  15201. materialIndex: 0
  15202. };
  15203. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  15204. intersection.face = face;
  15205. intersection.barycoord = barycoord;
  15206. }
  15207. return intersection;
  15208. }
  15209. /**
  15210. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  15211. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  15212. * of the axes.
  15213. *
  15214. * ```js
  15215. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15216. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  15217. * const cube = new THREE.Mesh( geometry, material );
  15218. * scene.add( cube );
  15219. * ```
  15220. *
  15221. * @augments BufferGeometry
  15222. */
  15223. class BoxGeometry extends BufferGeometry {
  15224. /**
  15225. * Constructs a new box geometry.
  15226. *
  15227. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  15228. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  15229. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  15230. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  15231. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  15232. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  15233. */
  15234. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  15235. super();
  15236. this.type = 'BoxGeometry';
  15237. /**
  15238. * Holds the constructor parameters that have been
  15239. * used to generate the geometry. Any modification
  15240. * after instantiation does not change the geometry.
  15241. *
  15242. * @type {Object}
  15243. */
  15244. this.parameters = {
  15245. width: width,
  15246. height: height,
  15247. depth: depth,
  15248. widthSegments: widthSegments,
  15249. heightSegments: heightSegments,
  15250. depthSegments: depthSegments
  15251. };
  15252. const scope = this;
  15253. // segments
  15254. widthSegments = Math.floor( widthSegments );
  15255. heightSegments = Math.floor( heightSegments );
  15256. depthSegments = Math.floor( depthSegments );
  15257. // buffers
  15258. const indices = [];
  15259. const vertices = [];
  15260. const normals = [];
  15261. const uvs = [];
  15262. // helper variables
  15263. let numberOfVertices = 0;
  15264. let groupStart = 0;
  15265. // build each side of the box geometry
  15266. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  15267. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  15268. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  15269. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  15270. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  15271. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  15272. // build geometry
  15273. this.setIndex( indices );
  15274. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15275. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15276. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15277. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  15278. const segmentWidth = width / gridX;
  15279. const segmentHeight = height / gridY;
  15280. const widthHalf = width / 2;
  15281. const heightHalf = height / 2;
  15282. const depthHalf = depth / 2;
  15283. const gridX1 = gridX + 1;
  15284. const gridY1 = gridY + 1;
  15285. let vertexCounter = 0;
  15286. let groupCount = 0;
  15287. const vector = new Vector3();
  15288. // generate vertices, normals and uvs
  15289. for ( let iy = 0; iy < gridY1; iy ++ ) {
  15290. const y = iy * segmentHeight - heightHalf;
  15291. for ( let ix = 0; ix < gridX1; ix ++ ) {
  15292. const x = ix * segmentWidth - widthHalf;
  15293. // set values to correct vector component
  15294. vector[ u ] = x * udir;
  15295. vector[ v ] = y * vdir;
  15296. vector[ w ] = depthHalf;
  15297. // now apply vector to vertex buffer
  15298. vertices.push( vector.x, vector.y, vector.z );
  15299. // set values to correct vector component
  15300. vector[ u ] = 0;
  15301. vector[ v ] = 0;
  15302. vector[ w ] = depth > 0 ? 1 : -1;
  15303. // now apply vector to normal buffer
  15304. normals.push( vector.x, vector.y, vector.z );
  15305. // uvs
  15306. uvs.push( ix / gridX );
  15307. uvs.push( 1 - ( iy / gridY ) );
  15308. // counters
  15309. vertexCounter += 1;
  15310. }
  15311. }
  15312. // indices
  15313. // 1. you need three indices to draw a single face
  15314. // 2. a single segment consists of two faces
  15315. // 3. so we need to generate six (2*3) indices per segment
  15316. for ( let iy = 0; iy < gridY; iy ++ ) {
  15317. for ( let ix = 0; ix < gridX; ix ++ ) {
  15318. const a = numberOfVertices + ix + gridX1 * iy;
  15319. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  15320. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  15321. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  15322. // faces
  15323. indices.push( a, b, d );
  15324. indices.push( b, c, d );
  15325. // increase counter
  15326. groupCount += 6;
  15327. }
  15328. }
  15329. // add a group to the geometry. this will ensure multi material support
  15330. scope.addGroup( groupStart, groupCount, materialIndex );
  15331. // calculate new start value for groups
  15332. groupStart += groupCount;
  15333. // update total number of vertices
  15334. numberOfVertices += vertexCounter;
  15335. }
  15336. }
  15337. copy( source ) {
  15338. super.copy( source );
  15339. this.parameters = Object.assign( {}, source.parameters );
  15340. return this;
  15341. }
  15342. /**
  15343. * Factory method for creating an instance of this class from the given
  15344. * JSON object.
  15345. *
  15346. * @param {Object} data - A JSON object representing the serialized geometry.
  15347. * @return {BoxGeometry} A new instance.
  15348. */
  15349. static fromJSON( data ) {
  15350. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  15351. }
  15352. }
  15353. // Uniform Utilities
  15354. function cloneUniforms( src ) {
  15355. const dst = {};
  15356. for ( const u in src ) {
  15357. dst[ u ] = {};
  15358. for ( const p in src[ u ] ) {
  15359. const property = src[ u ][ p ];
  15360. if ( property && ( property.isColor ||
  15361. property.isMatrix3 || property.isMatrix4 ||
  15362. property.isVector2 || property.isVector3 || property.isVector4 ||
  15363. property.isTexture || property.isQuaternion ) ) {
  15364. if ( property.isRenderTargetTexture ) {
  15365. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  15366. dst[ u ][ p ] = null;
  15367. } else {
  15368. dst[ u ][ p ] = property.clone();
  15369. }
  15370. } else if ( Array.isArray( property ) ) {
  15371. dst[ u ][ p ] = property.slice();
  15372. } else {
  15373. dst[ u ][ p ] = property;
  15374. }
  15375. }
  15376. }
  15377. return dst;
  15378. }
  15379. function mergeUniforms( uniforms ) {
  15380. const merged = {};
  15381. for ( let u = 0; u < uniforms.length; u ++ ) {
  15382. const tmp = cloneUniforms( uniforms[ u ] );
  15383. for ( const p in tmp ) {
  15384. merged[ p ] = tmp[ p ];
  15385. }
  15386. }
  15387. return merged;
  15388. }
  15389. function cloneUniformsGroups( src ) {
  15390. const dst = [];
  15391. for ( let u = 0; u < src.length; u ++ ) {
  15392. dst.push( src[ u ].clone() );
  15393. }
  15394. return dst;
  15395. }
  15396. function getUnlitUniformColorSpace( renderer ) {
  15397. const currentRenderTarget = renderer.getRenderTarget();
  15398. if ( currentRenderTarget === null ) {
  15399. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  15400. return renderer.outputColorSpace;
  15401. }
  15402. // https://github.com/mrdoob/three.js/issues/27868
  15403. if ( currentRenderTarget.isXRRenderTarget === true ) {
  15404. return currentRenderTarget.texture.colorSpace;
  15405. }
  15406. return ColorManagement.workingColorSpace;
  15407. }
  15408. // Legacy
  15409. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  15410. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  15411. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  15412. /**
  15413. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  15414. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  15415. * effect not included with any of the built-in materials.
  15416. *
  15417. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  15418. *
  15419. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  15420. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  15421. * you don't want that, use {@link RawShaderMaterial} instead.
  15422. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  15423. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  15424. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  15425. * - The loop has to be [normalized]{@link https://en.wikipedia.org/wiki/Normalized_loop}.
  15426. * - The loop variable has to be *i*.
  15427. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  15428. * value of *i* for the given iteration and can be used in preprocessor
  15429. * statements.
  15430. *
  15431. * ```js
  15432. * const material = new THREE.ShaderMaterial( {
  15433. * uniforms: {
  15434. * time: { value: 1.0 },
  15435. * resolution: { value: new THREE.Vector2() }
  15436. * },
  15437. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  15438. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  15439. * } );
  15440. * ```
  15441. *
  15442. * @augments Material
  15443. */
  15444. class ShaderMaterial extends Material {
  15445. /**
  15446. * Constructs a new shader material.
  15447. *
  15448. * @param {Object} [parameters] - An object with one or more properties
  15449. * defining the material's appearance. Any property of the material
  15450. * (including any property from inherited materials) can be passed
  15451. * in here. Color values can be passed any type of value accepted
  15452. * by {@link Color#set}.
  15453. */
  15454. constructor( parameters ) {
  15455. super();
  15456. /**
  15457. * This flag can be used for type testing.
  15458. *
  15459. * @type {boolean}
  15460. * @readonly
  15461. * @default true
  15462. */
  15463. this.isShaderMaterial = true;
  15464. this.type = 'ShaderMaterial';
  15465. /**
  15466. * Defines custom constants using `#define` directives within the GLSL code
  15467. * for both the vertex shader and the fragment shader; each key/value pair
  15468. * yields another directive.
  15469. * ```js
  15470. * defines: {
  15471. * FOO: 15,
  15472. * BAR: true
  15473. * }
  15474. * ```
  15475. * Yields the lines:
  15476. * ```
  15477. * #define FOO 15
  15478. * #define BAR true
  15479. * ```
  15480. *
  15481. * @type {Object}
  15482. */
  15483. this.defines = {};
  15484. /**
  15485. * An object of the form:
  15486. * ```js
  15487. * {
  15488. * "uniform1": { value: 1.0 },
  15489. * "uniform2": { value: 2 }
  15490. * }
  15491. * ```
  15492. * specifying the uniforms to be passed to the shader code; keys are uniform
  15493. * names, values are definitions of the form
  15494. * ```
  15495. * {
  15496. * value: 1.0
  15497. * }
  15498. * ```
  15499. * where `value` is the value of the uniform. Names must match the name of
  15500. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  15501. * on every frame, so updating the value of the uniform will immediately
  15502. * update the value available to the GLSL code.
  15503. *
  15504. * @type {Object}
  15505. */
  15506. this.uniforms = {};
  15507. /**
  15508. * An array holding uniforms groups for configuring UBOs.
  15509. *
  15510. * @type {Array<UniformsGroup>}
  15511. */
  15512. this.uniformsGroups = [];
  15513. /**
  15514. * Vertex shader GLSL code. This is the actual code for the shader.
  15515. *
  15516. * @type {string}
  15517. */
  15518. this.vertexShader = default_vertex;
  15519. /**
  15520. * Fragment shader GLSL code. This is the actual code for the shader.
  15521. *
  15522. * @type {string}
  15523. */
  15524. this.fragmentShader = default_fragment;
  15525. /**
  15526. * Controls line thickness or lines.
  15527. *
  15528. * WebGL and WebGPU ignore this setting and always render line primitives with a
  15529. * width of one pixel.
  15530. *
  15531. * @type {number}
  15532. * @default 1
  15533. */
  15534. this.linewidth = 1;
  15535. /**
  15536. * Renders the geometry as a wireframe.
  15537. *
  15538. * @type {boolean}
  15539. * @default false
  15540. */
  15541. this.wireframe = false;
  15542. /**
  15543. * Controls the thickness of the wireframe.
  15544. *
  15545. * WebGL and WebGPU ignore this property and always render
  15546. * 1 pixel wide lines.
  15547. *
  15548. * @type {number}
  15549. * @default 1
  15550. */
  15551. this.wireframeLinewidth = 1;
  15552. /**
  15553. * Define whether the material color is affected by global fog settings; `true`
  15554. * to pass fog uniforms to the shader.
  15555. *
  15556. * @type {boolean}
  15557. * @default false
  15558. */
  15559. this.fog = false;
  15560. /**
  15561. * Defines whether this material uses lighting; `true` to pass uniform data
  15562. * related to lighting to this shader.
  15563. *
  15564. * @type {boolean}
  15565. * @default false
  15566. */
  15567. this.lights = false;
  15568. /**
  15569. * Defines whether this material supports clipping; `true` to let the renderer
  15570. * pass the clippingPlanes uniform.
  15571. *
  15572. * @type {boolean}
  15573. * @default false
  15574. */
  15575. this.clipping = false;
  15576. /**
  15577. * Overwritten and set to `true` by default.
  15578. *
  15579. * @type {boolean}
  15580. * @default true
  15581. */
  15582. this.forceSinglePass = true;
  15583. /**
  15584. * This object allows to enable certain WebGL 2 extensions.
  15585. *
  15586. * - clipCullDistance: set to `true` to use vertex shader clipping
  15587. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  15588. *
  15589. * @type {{clipCullDistance:false,multiDraw:false}}
  15590. */
  15591. this.extensions = {
  15592. clipCullDistance: false, // set to use vertex shader clipping
  15593. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  15594. };
  15595. /**
  15596. * When the rendered geometry doesn't include these attributes but the
  15597. * material does, these default values will be passed to the shaders. This
  15598. * avoids errors when buffer data is missing.
  15599. *
  15600. * - color: [ 1, 1, 1 ]
  15601. * - uv: [ 0, 0 ]
  15602. * - uv1: [ 0, 0 ]
  15603. *
  15604. * @type {Object}
  15605. */
  15606. this.defaultAttributeValues = {
  15607. 'color': [ 1, 1, 1 ],
  15608. 'uv': [ 0, 0 ],
  15609. 'uv1': [ 0, 0 ]
  15610. };
  15611. /**
  15612. * If set, this calls [gl.bindAttribLocation]{@link https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation}
  15613. * to bind a generic vertex index to an attribute variable.
  15614. *
  15615. * @type {string|undefined}
  15616. * @default undefined
  15617. */
  15618. this.index0AttributeName = undefined;
  15619. /**
  15620. * Can be used to force a uniform update while changing uniforms in
  15621. * {@link Object3D#onBeforeRender}.
  15622. *
  15623. * @type {boolean}
  15624. * @default false
  15625. */
  15626. this.uniformsNeedUpdate = false;
  15627. /**
  15628. * Defines the GLSL version of custom shader code.
  15629. *
  15630. * @type {?(GLSL1|GLSL3)}
  15631. * @default null
  15632. */
  15633. this.glslVersion = null;
  15634. if ( parameters !== undefined ) {
  15635. this.setValues( parameters );
  15636. }
  15637. }
  15638. copy( source ) {
  15639. super.copy( source );
  15640. this.fragmentShader = source.fragmentShader;
  15641. this.vertexShader = source.vertexShader;
  15642. this.uniforms = cloneUniforms( source.uniforms );
  15643. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  15644. this.defines = Object.assign( {}, source.defines );
  15645. this.wireframe = source.wireframe;
  15646. this.wireframeLinewidth = source.wireframeLinewidth;
  15647. this.fog = source.fog;
  15648. this.lights = source.lights;
  15649. this.clipping = source.clipping;
  15650. this.extensions = Object.assign( {}, source.extensions );
  15651. this.glslVersion = source.glslVersion;
  15652. return this;
  15653. }
  15654. toJSON( meta ) {
  15655. const data = super.toJSON( meta );
  15656. data.glslVersion = this.glslVersion;
  15657. data.uniforms = {};
  15658. for ( const name in this.uniforms ) {
  15659. const uniform = this.uniforms[ name ];
  15660. const value = uniform.value;
  15661. if ( value && value.isTexture ) {
  15662. data.uniforms[ name ] = {
  15663. type: 't',
  15664. value: value.toJSON( meta ).uuid
  15665. };
  15666. } else if ( value && value.isColor ) {
  15667. data.uniforms[ name ] = {
  15668. type: 'c',
  15669. value: value.getHex()
  15670. };
  15671. } else if ( value && value.isVector2 ) {
  15672. data.uniforms[ name ] = {
  15673. type: 'v2',
  15674. value: value.toArray()
  15675. };
  15676. } else if ( value && value.isVector3 ) {
  15677. data.uniforms[ name ] = {
  15678. type: 'v3',
  15679. value: value.toArray()
  15680. };
  15681. } else if ( value && value.isVector4 ) {
  15682. data.uniforms[ name ] = {
  15683. type: 'v4',
  15684. value: value.toArray()
  15685. };
  15686. } else if ( value && value.isMatrix3 ) {
  15687. data.uniforms[ name ] = {
  15688. type: 'm3',
  15689. value: value.toArray()
  15690. };
  15691. } else if ( value && value.isMatrix4 ) {
  15692. data.uniforms[ name ] = {
  15693. type: 'm4',
  15694. value: value.toArray()
  15695. };
  15696. } else {
  15697. data.uniforms[ name ] = {
  15698. value: value
  15699. };
  15700. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  15701. }
  15702. }
  15703. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  15704. data.vertexShader = this.vertexShader;
  15705. data.fragmentShader = this.fragmentShader;
  15706. data.lights = this.lights;
  15707. data.clipping = this.clipping;
  15708. const extensions = {};
  15709. for ( const key in this.extensions ) {
  15710. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  15711. }
  15712. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  15713. return data;
  15714. }
  15715. }
  15716. /**
  15717. * Abstract base class for cameras. This class should always be inherited
  15718. * when you build a new camera.
  15719. *
  15720. * @abstract
  15721. * @augments Object3D
  15722. */
  15723. class Camera extends Object3D {
  15724. /**
  15725. * Constructs a new camera.
  15726. */
  15727. constructor() {
  15728. super();
  15729. /**
  15730. * This flag can be used for type testing.
  15731. *
  15732. * @type {boolean}
  15733. * @readonly
  15734. * @default true
  15735. */
  15736. this.isCamera = true;
  15737. this.type = 'Camera';
  15738. /**
  15739. * The inverse of the camera's world matrix.
  15740. *
  15741. * @type {Matrix4}
  15742. */
  15743. this.matrixWorldInverse = new Matrix4();
  15744. /**
  15745. * The camera's projection matrix.
  15746. *
  15747. * @type {Matrix4}
  15748. */
  15749. this.projectionMatrix = new Matrix4();
  15750. /**
  15751. * The inverse of the camera's projection matrix.
  15752. *
  15753. * @type {Matrix4}
  15754. */
  15755. this.projectionMatrixInverse = new Matrix4();
  15756. /**
  15757. * The coordinate system in which the camera is used.
  15758. *
  15759. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  15760. */
  15761. this.coordinateSystem = WebGLCoordinateSystem;
  15762. }
  15763. copy( source, recursive ) {
  15764. super.copy( source, recursive );
  15765. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  15766. this.projectionMatrix.copy( source.projectionMatrix );
  15767. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  15768. this.coordinateSystem = source.coordinateSystem;
  15769. return this;
  15770. }
  15771. /**
  15772. * Returns a vector representing the ("look") direction of the 3D object in world space.
  15773. *
  15774. * This method is overwritten since cameras have a different forward vector compared to other
  15775. * 3D objects. A camera looks down its local, negative z-axis by default.
  15776. *
  15777. * @param {Vector3} target - The target vector the result is stored to.
  15778. * @return {Vector3} The 3D object's direction in world space.
  15779. */
  15780. getWorldDirection( target ) {
  15781. return super.getWorldDirection( target ).negate();
  15782. }
  15783. updateMatrixWorld( force ) {
  15784. super.updateMatrixWorld( force );
  15785. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  15786. }
  15787. updateWorldMatrix( updateParents, updateChildren ) {
  15788. super.updateWorldMatrix( updateParents, updateChildren );
  15789. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  15790. }
  15791. clone() {
  15792. return new this.constructor().copy( this );
  15793. }
  15794. }
  15795. const _v3$1 = /*@__PURE__*/ new Vector3();
  15796. const _minTarget = /*@__PURE__*/ new Vector2();
  15797. const _maxTarget = /*@__PURE__*/ new Vector2();
  15798. /**
  15799. * Camera that uses [perspective projection]{@link https://en.wikipedia.org/wiki/Perspective_(graphical)}.
  15800. *
  15801. * This projection mode is designed to mimic the way the human eye sees. It
  15802. * is the most common projection mode used for rendering a 3D scene.
  15803. *
  15804. * ```js
  15805. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  15806. * scene.add( camera );
  15807. * ```
  15808. *
  15809. * @augments Camera
  15810. */
  15811. class PerspectiveCamera extends Camera {
  15812. /**
  15813. * Constructs a new perspective camera.
  15814. *
  15815. * @param {number} [fov=50] - The vertical field of view.
  15816. * @param {number} [aspect=1] - The aspect ratio.
  15817. * @param {number} [near=0.1] - The camera's near plane.
  15818. * @param {number} [far=2000] - The camera's far plane.
  15819. */
  15820. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  15821. super();
  15822. /**
  15823. * This flag can be used for type testing.
  15824. *
  15825. * @type {boolean}
  15826. * @readonly
  15827. * @default true
  15828. */
  15829. this.isPerspectiveCamera = true;
  15830. this.type = 'PerspectiveCamera';
  15831. /**
  15832. * The vertical field of view, from bottom to top of view,
  15833. * in degrees.
  15834. *
  15835. * @type {number}
  15836. * @default 50
  15837. */
  15838. this.fov = fov;
  15839. /**
  15840. * The zoom factor of the camera.
  15841. *
  15842. * @type {number}
  15843. * @default 1
  15844. */
  15845. this.zoom = 1;
  15846. /**
  15847. * The camera's near plane. The valid range is greater than `0`
  15848. * and less than the current value of {@link PerspectiveCamera#far}.
  15849. *
  15850. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  15851. * valid value for a perspective camera's near plane.
  15852. *
  15853. * @type {number}
  15854. * @default 0.1
  15855. */
  15856. this.near = near;
  15857. /**
  15858. * The camera's far plane. Must be greater than the
  15859. * current value of {@link PerspectiveCamera#near}.
  15860. *
  15861. * @type {number}
  15862. * @default 2000
  15863. */
  15864. this.far = far;
  15865. /**
  15866. * Object distance used for stereoscopy and depth-of-field effects. This
  15867. * parameter does not influence the projection matrix unless a
  15868. * {@link StereoCamera} is being used.
  15869. *
  15870. * @type {number}
  15871. * @default 10
  15872. */
  15873. this.focus = 10;
  15874. /**
  15875. * The aspect ratio, usually the canvas width / canvas height.
  15876. *
  15877. * @type {number}
  15878. * @default 1
  15879. */
  15880. this.aspect = aspect;
  15881. /**
  15882. * Represents the frustum window specification. This property should not be edited
  15883. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  15884. *
  15885. * @type {?Object}
  15886. * @default null
  15887. */
  15888. this.view = null;
  15889. /**
  15890. * Film size used for the larger axis. Default is `35` (millimeters). This
  15891. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  15892. * is set to a nonzero value.
  15893. *
  15894. * @type {number}
  15895. * @default 35
  15896. */
  15897. this.filmGauge = 35;
  15898. /**
  15899. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  15900. *
  15901. * @type {number}
  15902. * @default 0
  15903. */
  15904. this.filmOffset = 0;
  15905. this.updateProjectionMatrix();
  15906. }
  15907. copy( source, recursive ) {
  15908. super.copy( source, recursive );
  15909. this.fov = source.fov;
  15910. this.zoom = source.zoom;
  15911. this.near = source.near;
  15912. this.far = source.far;
  15913. this.focus = source.focus;
  15914. this.aspect = source.aspect;
  15915. this.view = source.view === null ? null : Object.assign( {}, source.view );
  15916. this.filmGauge = source.filmGauge;
  15917. this.filmOffset = source.filmOffset;
  15918. return this;
  15919. }
  15920. /**
  15921. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  15922. *
  15923. * The default film gauge is 35, so that the focal length can be specified for
  15924. * a 35mm (full frame) camera.
  15925. *
  15926. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  15927. */
  15928. setFocalLength( focalLength ) {
  15929. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  15930. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  15931. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  15932. this.updateProjectionMatrix();
  15933. }
  15934. /**
  15935. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  15936. * {@link PerspectiveCamera#filmGauge}.
  15937. *
  15938. * @return {number} The computed focal length.
  15939. */
  15940. getFocalLength() {
  15941. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  15942. return 0.5 * this.getFilmHeight() / vExtentSlope;
  15943. }
  15944. /**
  15945. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  15946. *
  15947. * @return {number} The effective FOV.
  15948. */
  15949. getEffectiveFOV() {
  15950. return RAD2DEG * 2 * Math.atan(
  15951. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  15952. }
  15953. /**
  15954. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  15955. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  15956. *
  15957. * @return {number} The film width.
  15958. */
  15959. getFilmWidth() {
  15960. // film not completely covered in portrait format (aspect < 1)
  15961. return this.filmGauge * Math.min( this.aspect, 1 );
  15962. }
  15963. /**
  15964. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  15965. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  15966. *
  15967. * @return {number} The film width.
  15968. */
  15969. getFilmHeight() {
  15970. // film not completely covered in landscape format (aspect > 1)
  15971. return this.filmGauge / Math.max( this.aspect, 1 );
  15972. }
  15973. /**
  15974. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  15975. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  15976. *
  15977. * @param {number} distance - The viewing distance.
  15978. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  15979. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  15980. */
  15981. getViewBounds( distance, minTarget, maxTarget ) {
  15982. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  15983. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  15984. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  15985. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  15986. }
  15987. /**
  15988. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  15989. *
  15990. * @param {number} distance - The viewing distance.
  15991. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  15992. * @returns {Vector2} The view size.
  15993. */
  15994. getViewSize( distance, target ) {
  15995. this.getViewBounds( distance, _minTarget, _maxTarget );
  15996. return target.subVectors( _maxTarget, _minTarget );
  15997. }
  15998. /**
  15999. * Sets an offset in a larger frustum. This is useful for multi-window or
  16000. * multi-monitor/multi-machine setups.
  16001. *
  16002. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  16003. * the monitors are in grid like this
  16004. *```
  16005. * +---+---+---+
  16006. * | A | B | C |
  16007. * +---+---+---+
  16008. * | D | E | F |
  16009. * +---+---+---+
  16010. *```
  16011. * then for each monitor you would call it like this:
  16012. *```js
  16013. * const w = 1920;
  16014. * const h = 1080;
  16015. * const fullWidth = w * 3;
  16016. * const fullHeight = h * 2;
  16017. *
  16018. * // --A--
  16019. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  16020. * // --B--
  16021. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  16022. * // --C--
  16023. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  16024. * // --D--
  16025. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  16026. * // --E--
  16027. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  16028. * // --F--
  16029. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  16030. * ```
  16031. *
  16032. * Note there is no reason monitors have to be the same size or in a grid.
  16033. *
  16034. * @param {number} fullWidth - The full width of multiview setup.
  16035. * @param {number} fullHeight - The full height of multiview setup.
  16036. * @param {number} x - The horizontal offset of the subcamera.
  16037. * @param {number} y - The vertical offset of the subcamera.
  16038. * @param {number} width - The width of subcamera.
  16039. * @param {number} height - The height of subcamera.
  16040. */
  16041. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16042. this.aspect = fullWidth / fullHeight;
  16043. if ( this.view === null ) {
  16044. this.view = {
  16045. enabled: true,
  16046. fullWidth: 1,
  16047. fullHeight: 1,
  16048. offsetX: 0,
  16049. offsetY: 0,
  16050. width: 1,
  16051. height: 1
  16052. };
  16053. }
  16054. this.view.enabled = true;
  16055. this.view.fullWidth = fullWidth;
  16056. this.view.fullHeight = fullHeight;
  16057. this.view.offsetX = x;
  16058. this.view.offsetY = y;
  16059. this.view.width = width;
  16060. this.view.height = height;
  16061. this.updateProjectionMatrix();
  16062. }
  16063. /**
  16064. * Removes the view offset from the projection matrix.
  16065. */
  16066. clearViewOffset() {
  16067. if ( this.view !== null ) {
  16068. this.view.enabled = false;
  16069. }
  16070. this.updateProjectionMatrix();
  16071. }
  16072. /**
  16073. * Updates the camera's projection matrix. Must be called after any change of
  16074. * camera properties.
  16075. */
  16076. updateProjectionMatrix() {
  16077. const near = this.near;
  16078. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  16079. let height = 2 * top;
  16080. let width = this.aspect * height;
  16081. let left = -0.5 * width;
  16082. const view = this.view;
  16083. if ( this.view !== null && this.view.enabled ) {
  16084. const fullWidth = view.fullWidth,
  16085. fullHeight = view.fullHeight;
  16086. left += view.offsetX * width / fullWidth;
  16087. top -= view.offsetY * height / fullHeight;
  16088. width *= view.width / fullWidth;
  16089. height *= view.height / fullHeight;
  16090. }
  16091. const skew = this.filmOffset;
  16092. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16093. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  16094. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16095. }
  16096. toJSON( meta ) {
  16097. const data = super.toJSON( meta );
  16098. data.object.fov = this.fov;
  16099. data.object.zoom = this.zoom;
  16100. data.object.near = this.near;
  16101. data.object.far = this.far;
  16102. data.object.focus = this.focus;
  16103. data.object.aspect = this.aspect;
  16104. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16105. data.object.filmGauge = this.filmGauge;
  16106. data.object.filmOffset = this.filmOffset;
  16107. return data;
  16108. }
  16109. }
  16110. const fov = -90; // negative fov is not an error
  16111. const aspect = 1;
  16112. /**
  16113. * A special type of camera that is positioned in 3D space to render its surroundings into a
  16114. * cube render target. The render target can then be used as an environment map for rendering
  16115. * realtime reflections in your scene.
  16116. *
  16117. * ```js
  16118. * // Create cube render target
  16119. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  16120. *
  16121. * // Create cube camera
  16122. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  16123. * scene.add( cubeCamera );
  16124. *
  16125. * // Create car
  16126. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  16127. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  16128. * scene.add( car );
  16129. *
  16130. * // Update the render target cube
  16131. * car.visible = false;
  16132. * cubeCamera.position.copy( car.position );
  16133. * cubeCamera.update( renderer, scene );
  16134. *
  16135. * // Render the scene
  16136. * car.visible = true;
  16137. * renderer.render( scene, camera );
  16138. * ```
  16139. *
  16140. * @augments Object3D
  16141. */
  16142. class CubeCamera extends Object3D {
  16143. /**
  16144. * Constructs a new cube camera.
  16145. *
  16146. * @param {number} near - The camera's near plane.
  16147. * @param {number} far - The camera's far plane.
  16148. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  16149. */
  16150. constructor( near, far, renderTarget ) {
  16151. super();
  16152. this.type = 'CubeCamera';
  16153. /**
  16154. * A reference to the cube render target.
  16155. *
  16156. * @type {WebGLCubeRenderTarget}
  16157. */
  16158. this.renderTarget = renderTarget;
  16159. /**
  16160. * The current active coordinate system.
  16161. *
  16162. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16163. * @default null
  16164. */
  16165. this.coordinateSystem = null;
  16166. /**
  16167. * The current active mipmap level
  16168. *
  16169. * @type {number}
  16170. * @default 0
  16171. */
  16172. this.activeMipmapLevel = 0;
  16173. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  16174. cameraPX.layers = this.layers;
  16175. this.add( cameraPX );
  16176. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  16177. cameraNX.layers = this.layers;
  16178. this.add( cameraNX );
  16179. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  16180. cameraPY.layers = this.layers;
  16181. this.add( cameraPY );
  16182. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  16183. cameraNY.layers = this.layers;
  16184. this.add( cameraNY );
  16185. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  16186. cameraPZ.layers = this.layers;
  16187. this.add( cameraPZ );
  16188. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  16189. cameraNZ.layers = this.layers;
  16190. this.add( cameraNZ );
  16191. }
  16192. /**
  16193. * Must be called when the coordinate system of the cube camera is changed.
  16194. */
  16195. updateCoordinateSystem() {
  16196. const coordinateSystem = this.coordinateSystem;
  16197. const cameras = this.children.concat();
  16198. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  16199. for ( const camera of cameras ) this.remove( camera );
  16200. if ( coordinateSystem === WebGLCoordinateSystem ) {
  16201. cameraPX.up.set( 0, 1, 0 );
  16202. cameraPX.lookAt( 1, 0, 0 );
  16203. cameraNX.up.set( 0, 1, 0 );
  16204. cameraNX.lookAt( -1, 0, 0 );
  16205. cameraPY.up.set( 0, 0, -1 );
  16206. cameraPY.lookAt( 0, 1, 0 );
  16207. cameraNY.up.set( 0, 0, 1 );
  16208. cameraNY.lookAt( 0, -1, 0 );
  16209. cameraPZ.up.set( 0, 1, 0 );
  16210. cameraPZ.lookAt( 0, 0, 1 );
  16211. cameraNZ.up.set( 0, 1, 0 );
  16212. cameraNZ.lookAt( 0, 0, -1 );
  16213. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  16214. cameraPX.up.set( 0, -1, 0 );
  16215. cameraPX.lookAt( -1, 0, 0 );
  16216. cameraNX.up.set( 0, -1, 0 );
  16217. cameraNX.lookAt( 1, 0, 0 );
  16218. cameraPY.up.set( 0, 0, 1 );
  16219. cameraPY.lookAt( 0, 1, 0 );
  16220. cameraNY.up.set( 0, 0, -1 );
  16221. cameraNY.lookAt( 0, -1, 0 );
  16222. cameraPZ.up.set( 0, -1, 0 );
  16223. cameraPZ.lookAt( 0, 0, 1 );
  16224. cameraNZ.up.set( 0, -1, 0 );
  16225. cameraNZ.lookAt( 0, 0, -1 );
  16226. } else {
  16227. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  16228. }
  16229. for ( const camera of cameras ) {
  16230. this.add( camera );
  16231. camera.updateMatrixWorld();
  16232. }
  16233. }
  16234. /**
  16235. * Calling this method will render the given scene with the given renderer
  16236. * into the cube render target of the camera.
  16237. *
  16238. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  16239. * @param {Scene} scene - The scene to render.
  16240. */
  16241. update( renderer, scene ) {
  16242. if ( this.parent === null ) this.updateMatrixWorld();
  16243. const { renderTarget, activeMipmapLevel } = this;
  16244. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  16245. this.coordinateSystem = renderer.coordinateSystem;
  16246. this.updateCoordinateSystem();
  16247. }
  16248. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  16249. const currentRenderTarget = renderer.getRenderTarget();
  16250. const currentActiveCubeFace = renderer.getActiveCubeFace();
  16251. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  16252. const currentXrEnabled = renderer.xr.enabled;
  16253. renderer.xr.enabled = false;
  16254. const generateMipmaps = renderTarget.texture.generateMipmaps;
  16255. renderTarget.texture.generateMipmaps = false;
  16256. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  16257. renderer.render( scene, cameraPX );
  16258. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  16259. renderer.render( scene, cameraNX );
  16260. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  16261. renderer.render( scene, cameraPY );
  16262. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  16263. renderer.render( scene, cameraNY );
  16264. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  16265. renderer.render( scene, cameraPZ );
  16266. // mipmaps are generated during the last call of render()
  16267. // at this point, all sides of the cube render target are defined
  16268. renderTarget.texture.generateMipmaps = generateMipmaps;
  16269. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  16270. renderer.render( scene, cameraNZ );
  16271. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  16272. renderer.xr.enabled = currentXrEnabled;
  16273. renderTarget.texture.needsPMREMUpdate = true;
  16274. }
  16275. }
  16276. /**
  16277. * Creates a cube texture made up of six images.
  16278. *
  16279. * ```js
  16280. * const loader = new THREE.CubeTextureLoader();
  16281. * loader.setPath( 'textures/cube/pisa/' );
  16282. *
  16283. * const textureCube = loader.load( [
  16284. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  16285. * ] );
  16286. *
  16287. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  16288. * ```
  16289. *
  16290. * @augments Texture
  16291. */
  16292. class CubeTexture extends Texture {
  16293. /**
  16294. * Constructs a new cube texture.
  16295. *
  16296. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  16297. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  16298. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  16299. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  16300. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  16301. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  16302. * @param {number} [format=RGBAFormat] - The texture format.
  16303. * @param {number} [type=UnsignedByteType] - The texture type.
  16304. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  16305. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  16306. */
  16307. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  16308. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  16309. /**
  16310. * This flag can be used for type testing.
  16311. *
  16312. * @type {boolean}
  16313. * @readonly
  16314. * @default true
  16315. */
  16316. this.isCubeTexture = true;
  16317. /**
  16318. * If set to `true`, the texture is flipped along the vertical axis when
  16319. * uploaded to the GPU.
  16320. *
  16321. * Overwritten and set to `false` by default.
  16322. *
  16323. * @type {boolean}
  16324. * @default false
  16325. */
  16326. this.flipY = false;
  16327. }
  16328. /**
  16329. * Alias for {@link CubeTexture#image}.
  16330. *
  16331. * @type {Array<Image>}
  16332. */
  16333. get images() {
  16334. return this.image;
  16335. }
  16336. set images( value ) {
  16337. this.image = value;
  16338. }
  16339. }
  16340. /**
  16341. * A cube render target used in context of {@link WebGLRenderer}.
  16342. *
  16343. * @augments WebGLRenderTarget
  16344. */
  16345. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  16346. /**
  16347. * Constructs a new cube render target.
  16348. *
  16349. * @param {number} [size=1] - The size of the render target.
  16350. * @param {RenderTarget~Options} [options] - The configuration object.
  16351. */
  16352. constructor( size = 1, options = {} ) {
  16353. super( size, size, options );
  16354. /**
  16355. * This flag can be used for type testing.
  16356. *
  16357. * @type {boolean}
  16358. * @readonly
  16359. * @default true
  16360. */
  16361. this.isWebGLCubeRenderTarget = true;
  16362. const image = { width: size, height: size, depth: 1 };
  16363. const images = [ image, image, image, image, image, image ];
  16364. /**
  16365. * Overwritten with a different texture type.
  16366. *
  16367. * @type {DataArrayTexture}
  16368. */
  16369. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  16370. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16371. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16372. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16373. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16374. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16375. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16376. this.texture.isRenderTargetTexture = true;
  16377. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  16378. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  16379. }
  16380. /**
  16381. * Converts the given equirectangular texture to a cube map.
  16382. *
  16383. * @param {WebGLRenderer} renderer - The renderer.
  16384. * @param {Texture} texture - The equirectangular texture.
  16385. * @return {WebGLCubeRenderTarget} A reference to this cube render target.
  16386. */
  16387. fromEquirectangularTexture( renderer, texture ) {
  16388. this.texture.type = texture.type;
  16389. this.texture.colorSpace = texture.colorSpace;
  16390. this.texture.generateMipmaps = texture.generateMipmaps;
  16391. this.texture.minFilter = texture.minFilter;
  16392. this.texture.magFilter = texture.magFilter;
  16393. const shader = {
  16394. uniforms: {
  16395. tEquirect: { value: null },
  16396. },
  16397. vertexShader: /* glsl */`
  16398. varying vec3 vWorldDirection;
  16399. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  16400. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  16401. }
  16402. void main() {
  16403. vWorldDirection = transformDirection( position, modelMatrix );
  16404. #include <begin_vertex>
  16405. #include <project_vertex>
  16406. }
  16407. `,
  16408. fragmentShader: /* glsl */`
  16409. uniform sampler2D tEquirect;
  16410. varying vec3 vWorldDirection;
  16411. #include <common>
  16412. void main() {
  16413. vec3 direction = normalize( vWorldDirection );
  16414. vec2 sampleUV = equirectUv( direction );
  16415. gl_FragColor = texture2D( tEquirect, sampleUV );
  16416. }
  16417. `
  16418. };
  16419. const geometry = new BoxGeometry( 5, 5, 5 );
  16420. const material = new ShaderMaterial( {
  16421. name: 'CubemapFromEquirect',
  16422. uniforms: cloneUniforms( shader.uniforms ),
  16423. vertexShader: shader.vertexShader,
  16424. fragmentShader: shader.fragmentShader,
  16425. side: BackSide,
  16426. blending: NoBlending
  16427. } );
  16428. material.uniforms.tEquirect.value = texture;
  16429. const mesh = new Mesh( geometry, material );
  16430. const currentMinFilter = texture.minFilter;
  16431. // Avoid blurred poles
  16432. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  16433. const camera = new CubeCamera( 1, 10, this );
  16434. camera.update( renderer, mesh );
  16435. texture.minFilter = currentMinFilter;
  16436. mesh.geometry.dispose();
  16437. mesh.material.dispose();
  16438. return this;
  16439. }
  16440. /**
  16441. * Clears this cube render target.
  16442. *
  16443. * @param {WebGLRenderer} renderer - The renderer.
  16444. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16445. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16446. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16447. */
  16448. clear( renderer, color = true, depth = true, stencil = true ) {
  16449. const currentRenderTarget = renderer.getRenderTarget();
  16450. for ( let i = 0; i < 6; i ++ ) {
  16451. renderer.setRenderTarget( this, i );
  16452. renderer.clear( color, depth, stencil );
  16453. }
  16454. renderer.setRenderTarget( currentRenderTarget );
  16455. }
  16456. }
  16457. /**
  16458. * This is almost identical to an {@link Object3D}. Its purpose is to
  16459. * make working with groups of objects syntactically clearer.
  16460. *
  16461. * ```js
  16462. * // Create a group and add the two cubes.
  16463. * // These cubes can now be rotated / scaled etc as a group.
  16464. * const group = new THREE.Group();
  16465. *
  16466. * group.add( meshA );
  16467. * group.add( meshB );
  16468. *
  16469. * scene.add( group );
  16470. * ```
  16471. *
  16472. * @augments Object3D
  16473. */
  16474. class Group extends Object3D {
  16475. constructor() {
  16476. super();
  16477. /**
  16478. * This flag can be used for type testing.
  16479. *
  16480. * @type {boolean}
  16481. * @readonly
  16482. * @default true
  16483. */
  16484. this.isGroup = true;
  16485. this.type = 'Group';
  16486. }
  16487. }
  16488. const _moveEvent = { type: 'move' };
  16489. /**
  16490. * Class for representing a XR controller with its
  16491. * different coordinate systems.
  16492. *
  16493. * @private
  16494. */
  16495. class WebXRController {
  16496. /**
  16497. * Constructs a new XR controller.
  16498. */
  16499. constructor() {
  16500. /**
  16501. * A group representing the target ray space
  16502. * of the XR controller.
  16503. *
  16504. * @private
  16505. * @type {?Group}
  16506. * @default null
  16507. */
  16508. this._targetRay = null;
  16509. /**
  16510. * A group representing the grip space
  16511. * of the XR controller.
  16512. *
  16513. * @private
  16514. * @type {?Group}
  16515. * @default null
  16516. */
  16517. this._grip = null;
  16518. /**
  16519. * A group representing the hand space
  16520. * of the XR controller.
  16521. *
  16522. * @private
  16523. * @type {?Group}
  16524. * @default null
  16525. */
  16526. this._hand = null;
  16527. }
  16528. /**
  16529. * Returns a group representing the hand space of the XR controller.
  16530. *
  16531. * @return {Group} A group representing the hand space of the XR controller.
  16532. */
  16533. getHandSpace() {
  16534. if ( this._hand === null ) {
  16535. this._hand = new Group();
  16536. this._hand.matrixAutoUpdate = false;
  16537. this._hand.visible = false;
  16538. this._hand.joints = {};
  16539. this._hand.inputState = { pinching: false };
  16540. }
  16541. return this._hand;
  16542. }
  16543. /**
  16544. * Returns a group representing the target ray space of the XR controller.
  16545. *
  16546. * @return {Group} A group representing the target ray space of the XR controller.
  16547. */
  16548. getTargetRaySpace() {
  16549. if ( this._targetRay === null ) {
  16550. this._targetRay = new Group();
  16551. this._targetRay.matrixAutoUpdate = false;
  16552. this._targetRay.visible = false;
  16553. this._targetRay.hasLinearVelocity = false;
  16554. this._targetRay.linearVelocity = new Vector3();
  16555. this._targetRay.hasAngularVelocity = false;
  16556. this._targetRay.angularVelocity = new Vector3();
  16557. }
  16558. return this._targetRay;
  16559. }
  16560. /**
  16561. * Returns a group representing the grip space of the XR controller.
  16562. *
  16563. * @return {Group} A group representing the grip space of the XR controller.
  16564. */
  16565. getGripSpace() {
  16566. if ( this._grip === null ) {
  16567. this._grip = new Group();
  16568. this._grip.matrixAutoUpdate = false;
  16569. this._grip.visible = false;
  16570. this._grip.hasLinearVelocity = false;
  16571. this._grip.linearVelocity = new Vector3();
  16572. this._grip.hasAngularVelocity = false;
  16573. this._grip.angularVelocity = new Vector3();
  16574. }
  16575. return this._grip;
  16576. }
  16577. /**
  16578. * Dispatches the given event to the groups representing
  16579. * the different coordinate spaces of the XR controller.
  16580. *
  16581. * @param {Object} event - The event to dispatch.
  16582. * @return {WebXRController} A reference to this instance.
  16583. */
  16584. dispatchEvent( event ) {
  16585. if ( this._targetRay !== null ) {
  16586. this._targetRay.dispatchEvent( event );
  16587. }
  16588. if ( this._grip !== null ) {
  16589. this._grip.dispatchEvent( event );
  16590. }
  16591. if ( this._hand !== null ) {
  16592. this._hand.dispatchEvent( event );
  16593. }
  16594. return this;
  16595. }
  16596. /**
  16597. * Connects the controller with the given XR input source.
  16598. *
  16599. * @param {XRInputSource} inputSource - The input source.
  16600. * @return {WebXRController} A reference to this instance.
  16601. */
  16602. connect( inputSource ) {
  16603. if ( inputSource && inputSource.hand ) {
  16604. const hand = this._hand;
  16605. if ( hand ) {
  16606. for ( const inputjoint of inputSource.hand.values() ) {
  16607. // Initialize hand with joints when connected
  16608. this._getHandJoint( hand, inputjoint );
  16609. }
  16610. }
  16611. }
  16612. this.dispatchEvent( { type: 'connected', data: inputSource } );
  16613. return this;
  16614. }
  16615. /**
  16616. * Disconnects the controller from the given XR input source.
  16617. *
  16618. * @param {XRInputSource} inputSource - The input source.
  16619. * @return {WebXRController} A reference to this instance.
  16620. */
  16621. disconnect( inputSource ) {
  16622. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  16623. if ( this._targetRay !== null ) {
  16624. this._targetRay.visible = false;
  16625. }
  16626. if ( this._grip !== null ) {
  16627. this._grip.visible = false;
  16628. }
  16629. if ( this._hand !== null ) {
  16630. this._hand.visible = false;
  16631. }
  16632. return this;
  16633. }
  16634. /**
  16635. * Updates the controller with the given input source, XR frame and reference space.
  16636. * This updates the transformations of the groups that represent the different
  16637. * coordinate systems of the controller.
  16638. *
  16639. * @param {XRInputSource} inputSource - The input source.
  16640. * @param {XRFrame} frame - The XR frame.
  16641. * @param {XRReferenceSpace} referenceSpace - The reference space.
  16642. * @return {WebXRController} A reference to this instance.
  16643. */
  16644. update( inputSource, frame, referenceSpace ) {
  16645. let inputPose = null;
  16646. let gripPose = null;
  16647. let handPose = null;
  16648. const targetRay = this._targetRay;
  16649. const grip = this._grip;
  16650. const hand = this._hand;
  16651. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  16652. if ( hand && inputSource.hand ) {
  16653. handPose = true;
  16654. for ( const inputjoint of inputSource.hand.values() ) {
  16655. // Update the joints groups with the XRJoint poses
  16656. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  16657. // The transform of this joint will be updated with the joint pose on each frame
  16658. const joint = this._getHandJoint( hand, inputjoint );
  16659. if ( jointPose !== null ) {
  16660. joint.matrix.fromArray( jointPose.transform.matrix );
  16661. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  16662. joint.matrixWorldNeedsUpdate = true;
  16663. joint.jointRadius = jointPose.radius;
  16664. }
  16665. joint.visible = jointPose !== null;
  16666. }
  16667. // Custom events
  16668. // Check pinchz
  16669. const indexTip = hand.joints[ 'index-finger-tip' ];
  16670. const thumbTip = hand.joints[ 'thumb-tip' ];
  16671. const distance = indexTip.position.distanceTo( thumbTip.position );
  16672. const distanceToPinch = 0.02;
  16673. const threshold = 0.005;
  16674. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  16675. hand.inputState.pinching = false;
  16676. this.dispatchEvent( {
  16677. type: 'pinchend',
  16678. handedness: inputSource.handedness,
  16679. target: this
  16680. } );
  16681. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  16682. hand.inputState.pinching = true;
  16683. this.dispatchEvent( {
  16684. type: 'pinchstart',
  16685. handedness: inputSource.handedness,
  16686. target: this
  16687. } );
  16688. }
  16689. } else {
  16690. if ( grip !== null && inputSource.gripSpace ) {
  16691. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  16692. if ( gripPose !== null ) {
  16693. grip.matrix.fromArray( gripPose.transform.matrix );
  16694. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  16695. grip.matrixWorldNeedsUpdate = true;
  16696. if ( gripPose.linearVelocity ) {
  16697. grip.hasLinearVelocity = true;
  16698. grip.linearVelocity.copy( gripPose.linearVelocity );
  16699. } else {
  16700. grip.hasLinearVelocity = false;
  16701. }
  16702. if ( gripPose.angularVelocity ) {
  16703. grip.hasAngularVelocity = true;
  16704. grip.angularVelocity.copy( gripPose.angularVelocity );
  16705. } else {
  16706. grip.hasAngularVelocity = false;
  16707. }
  16708. }
  16709. }
  16710. }
  16711. if ( targetRay !== null ) {
  16712. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  16713. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  16714. if ( inputPose === null && gripPose !== null ) {
  16715. inputPose = gripPose;
  16716. }
  16717. if ( inputPose !== null ) {
  16718. targetRay.matrix.fromArray( inputPose.transform.matrix );
  16719. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  16720. targetRay.matrixWorldNeedsUpdate = true;
  16721. if ( inputPose.linearVelocity ) {
  16722. targetRay.hasLinearVelocity = true;
  16723. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  16724. } else {
  16725. targetRay.hasLinearVelocity = false;
  16726. }
  16727. if ( inputPose.angularVelocity ) {
  16728. targetRay.hasAngularVelocity = true;
  16729. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  16730. } else {
  16731. targetRay.hasAngularVelocity = false;
  16732. }
  16733. this.dispatchEvent( _moveEvent );
  16734. }
  16735. }
  16736. }
  16737. if ( targetRay !== null ) {
  16738. targetRay.visible = ( inputPose !== null );
  16739. }
  16740. if ( grip !== null ) {
  16741. grip.visible = ( gripPose !== null );
  16742. }
  16743. if ( hand !== null ) {
  16744. hand.visible = ( handPose !== null );
  16745. }
  16746. return this;
  16747. }
  16748. /**
  16749. * Returns a group representing the hand joint for the given input joint.
  16750. *
  16751. * @private
  16752. * @param {Group} hand - The group representing the hand space.
  16753. * @param {XRJointSpace} inputjoint - The hand joint data.
  16754. * @return {Group} A group representing the hand joint for the given input joint.
  16755. */
  16756. _getHandJoint( hand, inputjoint ) {
  16757. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  16758. const joint = new Group();
  16759. joint.matrixAutoUpdate = false;
  16760. joint.visible = false;
  16761. hand.joints[ inputjoint.jointName ] = joint;
  16762. hand.add( joint );
  16763. }
  16764. return hand.joints[ inputjoint.jointName ];
  16765. }
  16766. }
  16767. /**
  16768. * This class can be used to define an exponential squared fog,
  16769. * which gives a clear view near the camera and a faster than exponentially
  16770. * densening fog farther from the camera.
  16771. *
  16772. * ```js
  16773. * const scene = new THREE.Scene();
  16774. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  16775. * ```
  16776. */
  16777. class FogExp2 {
  16778. /**
  16779. * Constructs a new fog.
  16780. *
  16781. * @param {number|Color} color - The fog's color.
  16782. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  16783. */
  16784. constructor( color, density = 0.00025 ) {
  16785. /**
  16786. * This flag can be used for type testing.
  16787. *
  16788. * @type {boolean}
  16789. * @readonly
  16790. * @default true
  16791. */
  16792. this.isFogExp2 = true;
  16793. /**
  16794. * The name of the fog.
  16795. *
  16796. * @type {string}
  16797. */
  16798. this.name = '';
  16799. /**
  16800. * The fog's color.
  16801. *
  16802. * @type {Color}
  16803. */
  16804. this.color = new Color( color );
  16805. /**
  16806. * Defines how fast the fog will grow dense.
  16807. *
  16808. * @type {number}
  16809. * @default 0.00025
  16810. */
  16811. this.density = density;
  16812. }
  16813. /**
  16814. * Returns a new fog with copied values from this instance.
  16815. *
  16816. * @return {FogExp2} A clone of this instance.
  16817. */
  16818. clone() {
  16819. return new FogExp2( this.color, this.density );
  16820. }
  16821. /**
  16822. * Serializes the fog into JSON.
  16823. *
  16824. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  16825. * @return {Object} A JSON object representing the serialized fog
  16826. */
  16827. toJSON( /* meta */ ) {
  16828. return {
  16829. type: 'FogExp2',
  16830. name: this.name,
  16831. color: this.color.getHex(),
  16832. density: this.density
  16833. };
  16834. }
  16835. }
  16836. /**
  16837. * This class can be used to define a linear fog that grows linearly denser
  16838. * with the distance.
  16839. *
  16840. * ```js
  16841. * const scene = new THREE.Scene();
  16842. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  16843. * ```
  16844. */
  16845. class Fog {
  16846. /**
  16847. * Constructs a new fog.
  16848. *
  16849. * @param {number|Color} color - The fog's color.
  16850. * @param {number} [near=1] - The minimum distance to start applying fog.
  16851. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  16852. */
  16853. constructor( color, near = 1, far = 1000 ) {
  16854. /**
  16855. * This flag can be used for type testing.
  16856. *
  16857. * @type {boolean}
  16858. * @readonly
  16859. * @default true
  16860. */
  16861. this.isFog = true;
  16862. /**
  16863. * The name of the fog.
  16864. *
  16865. * @type {string}
  16866. */
  16867. this.name = '';
  16868. /**
  16869. * The fog's color.
  16870. *
  16871. * @type {Color}
  16872. */
  16873. this.color = new Color( color );
  16874. /**
  16875. * The minimum distance to start applying fog. Objects that are less than
  16876. * `near` units from the active camera won't be affected by fog.
  16877. *
  16878. * @type {number}
  16879. * @default 1
  16880. */
  16881. this.near = near;
  16882. /**
  16883. * The maximum distance at which fog stops being calculated and applied.
  16884. * Objects that are more than `far` units away from the active camera won't
  16885. * be affected by fog.
  16886. *
  16887. * @type {number}
  16888. * @default 1000
  16889. */
  16890. this.far = far;
  16891. }
  16892. /**
  16893. * Returns a new fog with copied values from this instance.
  16894. *
  16895. * @return {Fog} A clone of this instance.
  16896. */
  16897. clone() {
  16898. return new Fog( this.color, this.near, this.far );
  16899. }
  16900. /**
  16901. * Serializes the fog into JSON.
  16902. *
  16903. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  16904. * @return {Object} A JSON object representing the serialized fog
  16905. */
  16906. toJSON( /* meta */ ) {
  16907. return {
  16908. type: 'Fog',
  16909. name: this.name,
  16910. color: this.color.getHex(),
  16911. near: this.near,
  16912. far: this.far
  16913. };
  16914. }
  16915. }
  16916. /**
  16917. * Scenes allow you to set up what is to be rendered and where by three.js.
  16918. * This is where you place 3D objects like meshes, lines or lights.
  16919. *
  16920. * @augments Object3D
  16921. */
  16922. class Scene extends Object3D {
  16923. /**
  16924. * Constructs a new scene.
  16925. */
  16926. constructor() {
  16927. super();
  16928. /**
  16929. * This flag can be used for type testing.
  16930. *
  16931. * @type {boolean}
  16932. * @readonly
  16933. * @default true
  16934. */
  16935. this.isScene = true;
  16936. this.type = 'Scene';
  16937. /**
  16938. * Defines the background of the scene. Valid inputs are:
  16939. *
  16940. * - A color for defining a uniform colored background.
  16941. * - A texture for defining a (flat) textured background.
  16942. * - Cube textures or equirectangular textures for defining a skybox.
  16943. *
  16944. * @type {?(Color|Texture)}
  16945. * @default null
  16946. */
  16947. this.background = null;
  16948. /**
  16949. * Sets the environment map for all physical materials in the scene. However,
  16950. * it's not possible to overwrite an existing texture assigned to the `envMap`
  16951. * material property.
  16952. *
  16953. * @type {?Texture}
  16954. * @default null
  16955. */
  16956. this.environment = null;
  16957. /**
  16958. * A fog instance defining the type of fog that affects everything
  16959. * rendered in the scene.
  16960. *
  16961. * @type {?(Fog|FogExp2)}
  16962. * @default null
  16963. */
  16964. this.fog = null;
  16965. /**
  16966. * Sets the blurriness of the background. Only influences environment maps
  16967. * assigned to {@link Scene#background}. Valid input is a float between `0`
  16968. * and `1`.
  16969. *
  16970. * @type {number}
  16971. * @default 0
  16972. */
  16973. this.backgroundBlurriness = 0;
  16974. /**
  16975. * Attenuates the color of the background. Only applies to background textures.
  16976. *
  16977. * @type {number}
  16978. * @default 1
  16979. */
  16980. this.backgroundIntensity = 1;
  16981. /**
  16982. * The rotation of the background in radians. Only influences environment maps
  16983. * assigned to {@link Scene#background}.
  16984. *
  16985. * @type {Euler}
  16986. * @default (0,0,0)
  16987. */
  16988. this.backgroundRotation = new Euler();
  16989. /**
  16990. * Attenuates the color of the environment. Only influences environment maps
  16991. * assigned to {@link Scene#environment}.
  16992. *
  16993. * @type {number}
  16994. * @default 1
  16995. */
  16996. this.environmentIntensity = 1;
  16997. /**
  16998. * The rotation of the environment map in radians. Only influences physical materials
  16999. * in the scene when {@link Scene#environment} is used.
  17000. *
  17001. * @type {Euler}
  17002. * @default (0,0,0)
  17003. */
  17004. this.environmentRotation = new Euler();
  17005. /**
  17006. * Forces everything in the scene to be rendered with the defined material. It is possible
  17007. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  17008. *
  17009. * @type {?Material}
  17010. * @default null
  17011. */
  17012. this.overrideMaterial = null;
  17013. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17014. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17015. }
  17016. }
  17017. copy( source, recursive ) {
  17018. super.copy( source, recursive );
  17019. if ( source.background !== null ) this.background = source.background.clone();
  17020. if ( source.environment !== null ) this.environment = source.environment.clone();
  17021. if ( source.fog !== null ) this.fog = source.fog.clone();
  17022. this.backgroundBlurriness = source.backgroundBlurriness;
  17023. this.backgroundIntensity = source.backgroundIntensity;
  17024. this.backgroundRotation.copy( source.backgroundRotation );
  17025. this.environmentIntensity = source.environmentIntensity;
  17026. this.environmentRotation.copy( source.environmentRotation );
  17027. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17028. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17029. return this;
  17030. }
  17031. toJSON( meta ) {
  17032. const data = super.toJSON( meta );
  17033. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17034. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17035. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17036. data.object.backgroundRotation = this.backgroundRotation.toArray();
  17037. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  17038. data.object.environmentRotation = this.environmentRotation.toArray();
  17039. return data;
  17040. }
  17041. }
  17042. /**
  17043. * "Interleaved" means that multiple attributes, possibly of different types,
  17044. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  17045. *
  17046. * An introduction into interleaved arrays can be found here: [Interleaved array basics]{@link https://blog.tojicode.com/2011/05/interleaved-array-basics.html}
  17047. */
  17048. class InterleavedBuffer {
  17049. /**
  17050. * Constructs a new interleaved buffer.
  17051. *
  17052. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  17053. * @param {number} stride - The number of typed-array elements per vertex.
  17054. */
  17055. constructor( array, stride ) {
  17056. /**
  17057. * This flag can be used for type testing.
  17058. *
  17059. * @type {boolean}
  17060. * @readonly
  17061. * @default true
  17062. */
  17063. this.isInterleavedBuffer = true;
  17064. /**
  17065. * A typed array with a shared buffer storing attribute data.
  17066. *
  17067. * @type {TypedArray}
  17068. */
  17069. this.array = array;
  17070. /**
  17071. * The number of typed-array elements per vertex.
  17072. *
  17073. * @type {number}
  17074. */
  17075. this.stride = stride;
  17076. /**
  17077. * The total number of elements in the array
  17078. *
  17079. * @type {number}
  17080. * @readonly
  17081. */
  17082. this.count = array !== undefined ? array.length / stride : 0;
  17083. /**
  17084. * Defines the intended usage pattern of the data store for optimization purposes.
  17085. *
  17086. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  17087. * instantiate a new one and set the desired usage before the next render.
  17088. *
  17089. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  17090. * @default StaticDrawUsage
  17091. */
  17092. this.usage = StaticDrawUsage;
  17093. /**
  17094. * This can be used to only update some components of stored vectors (for example, just the
  17095. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  17096. *
  17097. * @type {Array<Object>}
  17098. */
  17099. this.updateRanges = [];
  17100. /**
  17101. * A version number, incremented every time the `needsUpdate` is set to `true`.
  17102. *
  17103. * @type {number}
  17104. */
  17105. this.version = 0;
  17106. /**
  17107. * The UUID of the interleaved buffer.
  17108. *
  17109. * @type {string}
  17110. * @readonly
  17111. */
  17112. this.uuid = generateUUID();
  17113. }
  17114. /**
  17115. * A callback function that is executed after the renderer has transferred the attribute array
  17116. * data to the GPU.
  17117. */
  17118. onUploadCallback() {}
  17119. /**
  17120. * Flag to indicate that this attribute has changed and should be re-sent to
  17121. * the GPU. Set this to `true` when you modify the value of the array.
  17122. *
  17123. * @type {number}
  17124. * @default false
  17125. * @param {boolean} value
  17126. */
  17127. set needsUpdate( value ) {
  17128. if ( value === true ) this.version ++;
  17129. }
  17130. /**
  17131. * Sets the usage of this interleaved buffer.
  17132. *
  17133. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  17134. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  17135. */
  17136. setUsage( value ) {
  17137. this.usage = value;
  17138. return this;
  17139. }
  17140. /**
  17141. * Adds a range of data in the data array to be updated on the GPU.
  17142. *
  17143. * @param {number} start - Position at which to start update.
  17144. * @param {number} count - The number of components to update.
  17145. */
  17146. addUpdateRange( start, count ) {
  17147. this.updateRanges.push( { start, count } );
  17148. }
  17149. /**
  17150. * Clears the update ranges.
  17151. */
  17152. clearUpdateRanges() {
  17153. this.updateRanges.length = 0;
  17154. }
  17155. /**
  17156. * Copies the values of the given interleaved buffer to this instance.
  17157. *
  17158. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  17159. * @return {InterleavedBuffer} A reference to this instance.
  17160. */
  17161. copy( source ) {
  17162. this.array = new source.array.constructor( source.array );
  17163. this.count = source.count;
  17164. this.stride = source.stride;
  17165. this.usage = source.usage;
  17166. return this;
  17167. }
  17168. /**
  17169. * Copies a vector from the given interleaved buffer to this one. The start
  17170. * and destination position in the attribute buffers are represented by the
  17171. * given indices.
  17172. *
  17173. * @param {number} index1 - The destination index into this interleaved buffer.
  17174. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  17175. * @param {number} index2 - The source index into the given interleaved buffer.
  17176. * @return {InterleavedBuffer} A reference to this instance.
  17177. */
  17178. copyAt( index1, interleavedBuffer, index2 ) {
  17179. index1 *= this.stride;
  17180. index2 *= interleavedBuffer.stride;
  17181. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17182. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  17183. }
  17184. return this;
  17185. }
  17186. /**
  17187. * Sets the given array data in the interleaved buffer.
  17188. *
  17189. * @param {(TypedArray|Array)} value - The array data to set.
  17190. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  17191. * @return {InterleavedBuffer} A reference to this instance.
  17192. */
  17193. set( value, offset = 0 ) {
  17194. this.array.set( value, offset );
  17195. return this;
  17196. }
  17197. /**
  17198. * Returns a new interleaved buffer with copied values from this instance.
  17199. *
  17200. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  17201. * @return {InterleavedBuffer} A clone of this instance.
  17202. */
  17203. clone( data ) {
  17204. if ( data.arrayBuffers === undefined ) {
  17205. data.arrayBuffers = {};
  17206. }
  17207. if ( this.array.buffer._uuid === undefined ) {
  17208. this.array.buffer._uuid = generateUUID();
  17209. }
  17210. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17211. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17212. }
  17213. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17214. const ib = new this.constructor( array, this.stride );
  17215. ib.setUsage( this.usage );
  17216. return ib;
  17217. }
  17218. /**
  17219. * Sets the given callback function that is executed after the Renderer has transferred
  17220. * the array data to the GPU. Can be used to perform clean-up operations after
  17221. * the upload when data are not needed anymore on the CPU side.
  17222. *
  17223. * @param {Function} callback - The `onUpload()` callback.
  17224. * @return {InterleavedBuffer} A reference to this instance.
  17225. */
  17226. onUpload( callback ) {
  17227. this.onUploadCallback = callback;
  17228. return this;
  17229. }
  17230. /**
  17231. * Serializes the interleaved buffer into JSON.
  17232. *
  17233. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17234. * @return {Object} A JSON object representing the serialized interleaved buffer.
  17235. */
  17236. toJSON( data ) {
  17237. if ( data.arrayBuffers === undefined ) {
  17238. data.arrayBuffers = {};
  17239. }
  17240. // generate UUID for array buffer if necessary
  17241. if ( this.array.buffer._uuid === undefined ) {
  17242. this.array.buffer._uuid = generateUUID();
  17243. }
  17244. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17245. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17246. }
  17247. //
  17248. return {
  17249. uuid: this.uuid,
  17250. buffer: this.array.buffer._uuid,
  17251. type: this.array.constructor.name,
  17252. stride: this.stride
  17253. };
  17254. }
  17255. }
  17256. const _vector$7 = /*@__PURE__*/ new Vector3();
  17257. /**
  17258. * An alternative version of a buffer attribute with interleaved data. Interleaved
  17259. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  17260. * different offsets into the buffer.
  17261. */
  17262. class InterleavedBufferAttribute {
  17263. /**
  17264. * Constructs a new interleaved buffer attribute.
  17265. *
  17266. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  17267. * @param {number} itemSize - The item size.
  17268. * @param {number} offset - The attribute offset into the buffer.
  17269. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  17270. */
  17271. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17272. /**
  17273. * This flag can be used for type testing.
  17274. *
  17275. * @type {boolean}
  17276. * @readonly
  17277. * @default true
  17278. */
  17279. this.isInterleavedBufferAttribute = true;
  17280. /**
  17281. * The name of the buffer attribute.
  17282. *
  17283. * @type {string}
  17284. */
  17285. this.name = '';
  17286. /**
  17287. * The buffer holding the interleaved data.
  17288. *
  17289. * @type {InterleavedBuffer}
  17290. */
  17291. this.data = interleavedBuffer;
  17292. /**
  17293. * The item size, see {@link BufferAttribute#itemSize}.
  17294. *
  17295. * @type {number}
  17296. */
  17297. this.itemSize = itemSize;
  17298. /**
  17299. * The attribute offset into the buffer.
  17300. *
  17301. * @type {number}
  17302. */
  17303. this.offset = offset;
  17304. /**
  17305. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  17306. *
  17307. * @type {InterleavedBuffer}
  17308. */
  17309. this.normalized = normalized;
  17310. }
  17311. /**
  17312. * The item count of this buffer attribute.
  17313. *
  17314. * @type {number}
  17315. * @readonly
  17316. */
  17317. get count() {
  17318. return this.data.count;
  17319. }
  17320. /**
  17321. * The array holding the interleaved buffer attribute data.
  17322. *
  17323. * @type {TypedArray}
  17324. */
  17325. get array() {
  17326. return this.data.array;
  17327. }
  17328. /**
  17329. * Flag to indicate that this attribute has changed and should be re-sent to
  17330. * the GPU. Set this to `true` when you modify the value of the array.
  17331. *
  17332. * @type {number}
  17333. * @default false
  17334. * @param {boolean} value
  17335. */
  17336. set needsUpdate( value ) {
  17337. this.data.needsUpdate = value;
  17338. }
  17339. /**
  17340. * Applies the given 4x4 matrix to the given attribute. Only works with
  17341. * item size `3`.
  17342. *
  17343. * @param {Matrix4} m - The matrix to apply.
  17344. * @return {InterleavedBufferAttribute} A reference to this instance.
  17345. */
  17346. applyMatrix4( m ) {
  17347. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17348. _vector$7.fromBufferAttribute( this, i );
  17349. _vector$7.applyMatrix4( m );
  17350. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17351. }
  17352. return this;
  17353. }
  17354. /**
  17355. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  17356. * item size `3`.
  17357. *
  17358. * @param {Matrix3} m - The normal matrix to apply.
  17359. * @return {InterleavedBufferAttribute} A reference to this instance.
  17360. */
  17361. applyNormalMatrix( m ) {
  17362. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17363. _vector$7.fromBufferAttribute( this, i );
  17364. _vector$7.applyNormalMatrix( m );
  17365. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17366. }
  17367. return this;
  17368. }
  17369. /**
  17370. * Applies the given 4x4 matrix to the given attribute. Only works with
  17371. * item size `3` and with direction vectors.
  17372. *
  17373. * @param {Matrix4} m - The matrix to apply.
  17374. * @return {InterleavedBufferAttribute} A reference to this instance.
  17375. */
  17376. transformDirection( m ) {
  17377. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17378. _vector$7.fromBufferAttribute( this, i );
  17379. _vector$7.transformDirection( m );
  17380. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17381. }
  17382. return this;
  17383. }
  17384. /**
  17385. * Returns the given component of the vector at the given index.
  17386. *
  17387. * @param {number} index - The index into the buffer attribute.
  17388. * @param {number} component - The component index.
  17389. * @return {number} The returned value.
  17390. */
  17391. getComponent( index, component ) {
  17392. let value = this.array[ index * this.data.stride + this.offset + component ];
  17393. if ( this.normalized ) value = denormalize( value, this.array );
  17394. return value;
  17395. }
  17396. /**
  17397. * Sets the given value to the given component of the vector at the given index.
  17398. *
  17399. * @param {number} index - The index into the buffer attribute.
  17400. * @param {number} component - The component index.
  17401. * @param {number} value - The value to set.
  17402. * @return {InterleavedBufferAttribute} A reference to this instance.
  17403. */
  17404. setComponent( index, component, value ) {
  17405. if ( this.normalized ) value = normalize( value, this.array );
  17406. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  17407. return this;
  17408. }
  17409. /**
  17410. * Sets the x component of the vector at the given index.
  17411. *
  17412. * @param {number} index - The index into the buffer attribute.
  17413. * @param {number} x - The value to set.
  17414. * @return {InterleavedBufferAttribute} A reference to this instance.
  17415. */
  17416. setX( index, x ) {
  17417. if ( this.normalized ) x = normalize( x, this.array );
  17418. this.data.array[ index * this.data.stride + this.offset ] = x;
  17419. return this;
  17420. }
  17421. /**
  17422. * Sets the y component of the vector at the given index.
  17423. *
  17424. * @param {number} index - The index into the buffer attribute.
  17425. * @param {number} y - The value to set.
  17426. * @return {InterleavedBufferAttribute} A reference to this instance.
  17427. */
  17428. setY( index, y ) {
  17429. if ( this.normalized ) y = normalize( y, this.array );
  17430. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17431. return this;
  17432. }
  17433. /**
  17434. * Sets the z component of the vector at the given index.
  17435. *
  17436. * @param {number} index - The index into the buffer attribute.
  17437. * @param {number} z - The value to set.
  17438. * @return {InterleavedBufferAttribute} A reference to this instance.
  17439. */
  17440. setZ( index, z ) {
  17441. if ( this.normalized ) z = normalize( z, this.array );
  17442. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17443. return this;
  17444. }
  17445. /**
  17446. * Sets the w component of the vector at the given index.
  17447. *
  17448. * @param {number} index - The index into the buffer attribute.
  17449. * @param {number} w - The value to set.
  17450. * @return {InterleavedBufferAttribute} A reference to this instance.
  17451. */
  17452. setW( index, w ) {
  17453. if ( this.normalized ) w = normalize( w, this.array );
  17454. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17455. return this;
  17456. }
  17457. /**
  17458. * Returns the x component of the vector at the given index.
  17459. *
  17460. * @param {number} index - The index into the buffer attribute.
  17461. * @return {number} The x component.
  17462. */
  17463. getX( index ) {
  17464. let x = this.data.array[ index * this.data.stride + this.offset ];
  17465. if ( this.normalized ) x = denormalize( x, this.array );
  17466. return x;
  17467. }
  17468. /**
  17469. * Returns the y component of the vector at the given index.
  17470. *
  17471. * @param {number} index - The index into the buffer attribute.
  17472. * @return {number} The y component.
  17473. */
  17474. getY( index ) {
  17475. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17476. if ( this.normalized ) y = denormalize( y, this.array );
  17477. return y;
  17478. }
  17479. /**
  17480. * Returns the z component of the vector at the given index.
  17481. *
  17482. * @param {number} index - The index into the buffer attribute.
  17483. * @return {number} The z component.
  17484. */
  17485. getZ( index ) {
  17486. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17487. if ( this.normalized ) z = denormalize( z, this.array );
  17488. return z;
  17489. }
  17490. /**
  17491. * Returns the w component of the vector at the given index.
  17492. *
  17493. * @param {number} index - The index into the buffer attribute.
  17494. * @return {number} The w component.
  17495. */
  17496. getW( index ) {
  17497. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17498. if ( this.normalized ) w = denormalize( w, this.array );
  17499. return w;
  17500. }
  17501. /**
  17502. * Sets the x and y component of the vector at the given index.
  17503. *
  17504. * @param {number} index - The index into the buffer attribute.
  17505. * @param {number} x - The value for the x component to set.
  17506. * @param {number} y - The value for the y component to set.
  17507. * @return {InterleavedBufferAttribute} A reference to this instance.
  17508. */
  17509. setXY( index, x, y ) {
  17510. index = index * this.data.stride + this.offset;
  17511. if ( this.normalized ) {
  17512. x = normalize( x, this.array );
  17513. y = normalize( y, this.array );
  17514. }
  17515. this.data.array[ index + 0 ] = x;
  17516. this.data.array[ index + 1 ] = y;
  17517. return this;
  17518. }
  17519. /**
  17520. * Sets the x, y and z component of the vector at the given index.
  17521. *
  17522. * @param {number} index - The index into the buffer attribute.
  17523. * @param {number} x - The value for the x component to set.
  17524. * @param {number} y - The value for the y component to set.
  17525. * @param {number} z - The value for the z component to set.
  17526. * @return {InterleavedBufferAttribute} A reference to this instance.
  17527. */
  17528. setXYZ( index, x, y, z ) {
  17529. index = index * this.data.stride + this.offset;
  17530. if ( this.normalized ) {
  17531. x = normalize( x, this.array );
  17532. y = normalize( y, this.array );
  17533. z = normalize( z, this.array );
  17534. }
  17535. this.data.array[ index + 0 ] = x;
  17536. this.data.array[ index + 1 ] = y;
  17537. this.data.array[ index + 2 ] = z;
  17538. return this;
  17539. }
  17540. /**
  17541. * Sets the x, y, z and w component of the vector at the given index.
  17542. *
  17543. * @param {number} index - The index into the buffer attribute.
  17544. * @param {number} x - The value for the x component to set.
  17545. * @param {number} y - The value for the y component to set.
  17546. * @param {number} z - The value for the z component to set.
  17547. * @param {number} w - The value for the w component to set.
  17548. * @return {InterleavedBufferAttribute} A reference to this instance.
  17549. */
  17550. setXYZW( index, x, y, z, w ) {
  17551. index = index * this.data.stride + this.offset;
  17552. if ( this.normalized ) {
  17553. x = normalize( x, this.array );
  17554. y = normalize( y, this.array );
  17555. z = normalize( z, this.array );
  17556. w = normalize( w, this.array );
  17557. }
  17558. this.data.array[ index + 0 ] = x;
  17559. this.data.array[ index + 1 ] = y;
  17560. this.data.array[ index + 2 ] = z;
  17561. this.data.array[ index + 3 ] = w;
  17562. return this;
  17563. }
  17564. /**
  17565. * Returns a new buffer attribute with copied values from this instance.
  17566. *
  17567. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17568. *
  17569. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  17570. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  17571. */
  17572. clone( data ) {
  17573. if ( data === undefined ) {
  17574. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17575. const array = [];
  17576. for ( let i = 0; i < this.count; i ++ ) {
  17577. const index = i * this.data.stride + this.offset;
  17578. for ( let j = 0; j < this.itemSize; j ++ ) {
  17579. array.push( this.data.array[ index + j ] );
  17580. }
  17581. }
  17582. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17583. } else {
  17584. if ( data.interleavedBuffers === undefined ) {
  17585. data.interleavedBuffers = {};
  17586. }
  17587. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17588. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17589. }
  17590. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17591. }
  17592. }
  17593. /**
  17594. * Serializes the buffer attribute into JSON.
  17595. *
  17596. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17597. *
  17598. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17599. * @return {Object} A JSON object representing the serialized buffer attribute.
  17600. */
  17601. toJSON( data ) {
  17602. if ( data === undefined ) {
  17603. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17604. const array = [];
  17605. for ( let i = 0; i < this.count; i ++ ) {
  17606. const index = i * this.data.stride + this.offset;
  17607. for ( let j = 0; j < this.itemSize; j ++ ) {
  17608. array.push( this.data.array[ index + j ] );
  17609. }
  17610. }
  17611. // de-interleave data and save it as an ordinary buffer attribute for now
  17612. return {
  17613. itemSize: this.itemSize,
  17614. type: this.array.constructor.name,
  17615. array: array,
  17616. normalized: this.normalized
  17617. };
  17618. } else {
  17619. // save as true interleaved attribute
  17620. if ( data.interleavedBuffers === undefined ) {
  17621. data.interleavedBuffers = {};
  17622. }
  17623. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17624. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17625. }
  17626. return {
  17627. isInterleavedBufferAttribute: true,
  17628. itemSize: this.itemSize,
  17629. data: this.data.uuid,
  17630. offset: this.offset,
  17631. normalized: this.normalized
  17632. };
  17633. }
  17634. }
  17635. }
  17636. /**
  17637. * A material for rendering instances of {@link Sprite}.
  17638. *
  17639. * ```js
  17640. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  17641. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  17642. *
  17643. * const sprite = new THREE.Sprite( material );
  17644. * sprite.scale.set(200, 200, 1)
  17645. * scene.add( sprite );
  17646. * ```
  17647. *
  17648. * @augments Material
  17649. */
  17650. class SpriteMaterial extends Material {
  17651. /**
  17652. * Constructs a new sprite material.
  17653. *
  17654. * @param {Object} [parameters] - An object with one or more properties
  17655. * defining the material's appearance. Any property of the material
  17656. * (including any property from inherited materials) can be passed
  17657. * in here. Color values can be passed any type of value accepted
  17658. * by {@link Color#set}.
  17659. */
  17660. constructor( parameters ) {
  17661. super();
  17662. /**
  17663. * This flag can be used for type testing.
  17664. *
  17665. * @type {boolean}
  17666. * @readonly
  17667. * @default true
  17668. */
  17669. this.isSpriteMaterial = true;
  17670. this.type = 'SpriteMaterial';
  17671. /**
  17672. * Color of the material.
  17673. *
  17674. * @type {Color}
  17675. * @default (1,1,1)
  17676. */
  17677. this.color = new Color( 0xffffff );
  17678. /**
  17679. * The color map. May optionally include an alpha channel, typically combined
  17680. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  17681. * color is modulated by the diffuse `color`.
  17682. *
  17683. * @type {?Texture}
  17684. * @default null
  17685. */
  17686. this.map = null;
  17687. /**
  17688. * The alpha map is a grayscale texture that controls the opacity across the
  17689. * surface (black: fully transparent; white: fully opaque).
  17690. *
  17691. * Only the color of the texture is used, ignoring the alpha channel if one
  17692. * exists. For RGB and RGBA textures, the renderer will use the green channel
  17693. * when sampling this texture due to the extra bit of precision provided for
  17694. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  17695. * luminance/alpha textures will also still work as expected.
  17696. *
  17697. * @type {?Texture}
  17698. * @default null
  17699. */
  17700. this.alphaMap = null;
  17701. /**
  17702. * The rotation of the sprite in radians.
  17703. *
  17704. * @type {number}
  17705. * @default 0
  17706. */
  17707. this.rotation = 0;
  17708. /**
  17709. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  17710. *
  17711. * @type {boolean}
  17712. * @default true
  17713. */
  17714. this.sizeAttenuation = true;
  17715. /**
  17716. * Overwritten since sprite materials are transparent
  17717. * by default.
  17718. *
  17719. * @type {boolean}
  17720. * @default true
  17721. */
  17722. this.transparent = true;
  17723. /**
  17724. * Whether the material is affected by fog or not.
  17725. *
  17726. * @type {boolean}
  17727. * @default true
  17728. */
  17729. this.fog = true;
  17730. this.setValues( parameters );
  17731. }
  17732. copy( source ) {
  17733. super.copy( source );
  17734. this.color.copy( source.color );
  17735. this.map = source.map;
  17736. this.alphaMap = source.alphaMap;
  17737. this.rotation = source.rotation;
  17738. this.sizeAttenuation = source.sizeAttenuation;
  17739. this.fog = source.fog;
  17740. return this;
  17741. }
  17742. }
  17743. let _geometry;
  17744. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17745. const _worldScale = /*@__PURE__*/ new Vector3();
  17746. const _mvPosition = /*@__PURE__*/ new Vector3();
  17747. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17748. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17749. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17750. const _vA = /*@__PURE__*/ new Vector3();
  17751. const _vB = /*@__PURE__*/ new Vector3();
  17752. const _vC = /*@__PURE__*/ new Vector3();
  17753. const _uvA = /*@__PURE__*/ new Vector2();
  17754. const _uvB = /*@__PURE__*/ new Vector2();
  17755. const _uvC = /*@__PURE__*/ new Vector2();
  17756. /**
  17757. * A sprite is a plane that always faces towards the camera, generally with a
  17758. * partially transparent texture applied.
  17759. *
  17760. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  17761. * have no effect.
  17762. *
  17763. * ```js
  17764. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  17765. * const material = new THREE.SpriteMaterial( { map: map } );
  17766. *
  17767. * const sprite = new THREE.Sprite( material );
  17768. * scene.add( sprite );
  17769. * ```
  17770. *
  17771. * @augments Object3D
  17772. */
  17773. class Sprite extends Object3D {
  17774. /**
  17775. * Constructs a new sprite.
  17776. *
  17777. * @param {SpriteMaterial} [material] - The sprite material.
  17778. */
  17779. constructor( material = new SpriteMaterial() ) {
  17780. super();
  17781. /**
  17782. * This flag can be used for type testing.
  17783. *
  17784. * @type {boolean}
  17785. * @readonly
  17786. * @default true
  17787. */
  17788. this.isSprite = true;
  17789. this.type = 'Sprite';
  17790. if ( _geometry === undefined ) {
  17791. _geometry = new BufferGeometry();
  17792. const float32Array = new Float32Array( [
  17793. -0.5, -0.5, 0, 0, 0,
  17794. 0.5, -0.5, 0, 1, 0,
  17795. 0.5, 0.5, 0, 1, 1,
  17796. -0.5, 0.5, 0, 0, 1
  17797. ] );
  17798. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  17799. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  17800. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  17801. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  17802. }
  17803. /**
  17804. * The sprite geometry.
  17805. *
  17806. * @type {BufferGeometry}
  17807. */
  17808. this.geometry = _geometry;
  17809. /**
  17810. * The sprite material.
  17811. *
  17812. * @type {SpriteMaterial}
  17813. */
  17814. this.material = material;
  17815. /**
  17816. * The sprite's anchor point, and the point around which the sprite rotates.
  17817. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  17818. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  17819. *
  17820. * @type {Vector2}
  17821. * @default (0.5,0.5)
  17822. */
  17823. this.center = new Vector2( 0.5, 0.5 );
  17824. }
  17825. /**
  17826. * Computes intersection points between a casted ray and this sprite.
  17827. *
  17828. * @param {Raycaster} raycaster - The raycaster.
  17829. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  17830. */
  17831. raycast( raycaster, intersects ) {
  17832. if ( raycaster.camera === null ) {
  17833. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  17834. }
  17835. _worldScale.setFromMatrixScale( this.matrixWorld );
  17836. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  17837. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  17838. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  17839. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  17840. _worldScale.multiplyScalar( - _mvPosition.z );
  17841. }
  17842. const rotation = this.material.rotation;
  17843. let sin, cos;
  17844. if ( rotation !== 0 ) {
  17845. cos = Math.cos( rotation );
  17846. sin = Math.sin( rotation );
  17847. }
  17848. const center = this.center;
  17849. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17850. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17851. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17852. _uvA.set( 0, 0 );
  17853. _uvB.set( 1, 0 );
  17854. _uvC.set( 1, 1 );
  17855. // check first triangle
  17856. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  17857. if ( intersect === null ) {
  17858. // check second triangle
  17859. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17860. _uvB.set( 0, 1 );
  17861. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  17862. if ( intersect === null ) {
  17863. return;
  17864. }
  17865. }
  17866. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  17867. if ( distance < raycaster.near || distance > raycaster.far ) return;
  17868. intersects.push( {
  17869. distance: distance,
  17870. point: _intersectPoint.clone(),
  17871. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  17872. face: null,
  17873. object: this
  17874. } );
  17875. }
  17876. copy( source, recursive ) {
  17877. super.copy( source, recursive );
  17878. if ( source.center !== undefined ) this.center.copy( source.center );
  17879. this.material = source.material;
  17880. return this;
  17881. }
  17882. }
  17883. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  17884. // compute position in camera space
  17885. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  17886. // to check if rotation is not zero
  17887. if ( sin !== undefined ) {
  17888. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  17889. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  17890. } else {
  17891. _rotatedPosition.copy( _alignedPosition );
  17892. }
  17893. vertexPosition.copy( mvPosition );
  17894. vertexPosition.x += _rotatedPosition.x;
  17895. vertexPosition.y += _rotatedPosition.y;
  17896. // transform to world space
  17897. vertexPosition.applyMatrix4( _viewWorldMatrix );
  17898. }
  17899. const _v1$2 = /*@__PURE__*/ new Vector3();
  17900. const _v2$1 = /*@__PURE__*/ new Vector3();
  17901. /**
  17902. * A component for providing a basic Level of Detail (LOD) mechanism.
  17903. *
  17904. * Every LOD level is associated with an object, and rendering can be switched
  17905. * between them at the distances specified. Typically you would create, say,
  17906. * three meshes, one for far away (low detail), one for mid range (medium
  17907. * detail) and one for close up (high detail).
  17908. *
  17909. * ```js
  17910. * const lod = new THREE.LOD();
  17911. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  17912. *
  17913. * //Create spheres with 3 levels of detail and create new LOD levels for them
  17914. * for( let i = 0; i < 3; i++ ) {
  17915. *
  17916. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  17917. * const mesh = new THREE.Mesh( geometry, material );
  17918. * lod.addLevel( mesh, i * 75 );
  17919. *
  17920. * }
  17921. *
  17922. * scene.add( lod );
  17923. * ```
  17924. *
  17925. * @augments Object3D
  17926. */
  17927. class LOD extends Object3D {
  17928. /**
  17929. * Constructs a new LOD.
  17930. */
  17931. constructor() {
  17932. super();
  17933. /**
  17934. * This flag can be used for type testing.
  17935. *
  17936. * @type {boolean}
  17937. * @readonly
  17938. * @default true
  17939. */
  17940. this.isLOD = true;
  17941. /**
  17942. * The current LOD index.
  17943. *
  17944. * @private
  17945. * @type {number}
  17946. * @default 0
  17947. */
  17948. this._currentLevel = 0;
  17949. this.type = 'LOD';
  17950. Object.defineProperties( this, {
  17951. /**
  17952. * This array holds the LOD levels.
  17953. *
  17954. * @name LOD#levels
  17955. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  17956. */
  17957. levels: {
  17958. enumerable: true,
  17959. value: []
  17960. }
  17961. } );
  17962. /**
  17963. * Whether the LOD object is updated automatically by the renderer per frame
  17964. * or not. If set to `false`, you have to call {@link LOD#update} in the
  17965. * render loop by yourself.
  17966. *
  17967. * @type {boolean}
  17968. * @default true
  17969. */
  17970. this.autoUpdate = true;
  17971. }
  17972. copy( source ) {
  17973. super.copy( source, false );
  17974. const levels = source.levels;
  17975. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17976. const level = levels[ i ];
  17977. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  17978. }
  17979. this.autoUpdate = source.autoUpdate;
  17980. return this;
  17981. }
  17982. /**
  17983. * Adds a mesh that will display at a certain distance and greater. Typically
  17984. * the further away the distance, the lower the detail on the mesh.
  17985. *
  17986. * @param {Object3D} object - The 3D object to display at this level.
  17987. * @param {number} [distance=0] - The distance at which to display this level of detail.
  17988. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  17989. * @return {LOD} A reference to this instance.
  17990. */
  17991. addLevel( object, distance = 0, hysteresis = 0 ) {
  17992. distance = Math.abs( distance );
  17993. const levels = this.levels;
  17994. let l;
  17995. for ( l = 0; l < levels.length; l ++ ) {
  17996. if ( distance < levels[ l ].distance ) {
  17997. break;
  17998. }
  17999. }
  18000. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18001. this.add( object );
  18002. return this;
  18003. }
  18004. /**
  18005. * Removes an existing level, based on the distance from the camera.
  18006. * Returns `true` when the level has been removed. Otherwise `false`.
  18007. *
  18008. * @param {number} distance - Distance of the level to remove.
  18009. * @return {boolean} Whether the level has been removed or not.
  18010. */
  18011. removeLevel( distance ) {
  18012. const levels = this.levels;
  18013. for ( let i = 0; i < levels.length; i ++ ) {
  18014. if ( levels[ i ].distance === distance ) {
  18015. const removedElements = levels.splice( i, 1 );
  18016. this.remove( removedElements[ 0 ].object );
  18017. return true;
  18018. }
  18019. }
  18020. return false;
  18021. }
  18022. /**
  18023. * Returns the currently active LOD level index.
  18024. *
  18025. * @return {number} The current active LOD level index.
  18026. */
  18027. getCurrentLevel() {
  18028. return this._currentLevel;
  18029. }
  18030. /**
  18031. * Returns a reference to the first 3D object that is greater than
  18032. * the given distance.
  18033. *
  18034. * @param {number} distance - The LOD distance.
  18035. * @return {Object3D|null} The found 3D object. `null` if no 3D object has been found.
  18036. */
  18037. getObjectForDistance( distance ) {
  18038. const levels = this.levels;
  18039. if ( levels.length > 0 ) {
  18040. let i, l;
  18041. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18042. let levelDistance = levels[ i ].distance;
  18043. if ( levels[ i ].object.visible ) {
  18044. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18045. }
  18046. if ( distance < levelDistance ) {
  18047. break;
  18048. }
  18049. }
  18050. return levels[ i - 1 ].object;
  18051. }
  18052. return null;
  18053. }
  18054. /**
  18055. * Computes intersection points between a casted ray and this LOD.
  18056. *
  18057. * @param {Raycaster} raycaster - The raycaster.
  18058. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18059. */
  18060. raycast( raycaster, intersects ) {
  18061. const levels = this.levels;
  18062. if ( levels.length > 0 ) {
  18063. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18064. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18065. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18066. }
  18067. }
  18068. /**
  18069. * Updates the LOD by computing which LOD level should be visible according
  18070. * to the current distance of the given camera.
  18071. *
  18072. * @param {Camera} camera - The camera the scene is rendered with.
  18073. */
  18074. update( camera ) {
  18075. const levels = this.levels;
  18076. if ( levels.length > 1 ) {
  18077. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18078. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18079. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18080. levels[ 0 ].object.visible = true;
  18081. let i, l;
  18082. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18083. let levelDistance = levels[ i ].distance;
  18084. if ( levels[ i ].object.visible ) {
  18085. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18086. }
  18087. if ( distance >= levelDistance ) {
  18088. levels[ i - 1 ].object.visible = false;
  18089. levels[ i ].object.visible = true;
  18090. } else {
  18091. break;
  18092. }
  18093. }
  18094. this._currentLevel = i - 1;
  18095. for ( ; i < l; i ++ ) {
  18096. levels[ i ].object.visible = false;
  18097. }
  18098. }
  18099. }
  18100. toJSON( meta ) {
  18101. const data = super.toJSON( meta );
  18102. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18103. data.object.levels = [];
  18104. const levels = this.levels;
  18105. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18106. const level = levels[ i ];
  18107. data.object.levels.push( {
  18108. object: level.object.uuid,
  18109. distance: level.distance,
  18110. hysteresis: level.hysteresis
  18111. } );
  18112. }
  18113. return data;
  18114. }
  18115. }
  18116. const _basePosition = /*@__PURE__*/ new Vector3();
  18117. const _skinIndex = /*@__PURE__*/ new Vector4();
  18118. const _skinWeight = /*@__PURE__*/ new Vector4();
  18119. const _vector3 = /*@__PURE__*/ new Vector3();
  18120. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18121. const _vertex = /*@__PURE__*/ new Vector3();
  18122. const _sphere$5 = /*@__PURE__*/ new Sphere();
  18123. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18124. const _ray$2 = /*@__PURE__*/ new Ray();
  18125. /**
  18126. * A mesh that has a {@link Skeleton} that can then be used to animate the
  18127. * vertices of the geometry with skinning/skeleton animation.
  18128. *
  18129. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  18130. * as buffer attributes in its geometry. These attribute define which bones affect a single
  18131. * vertex to a certain extend.
  18132. *
  18133. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  18134. * or {@link FBXLoader } import respective models.
  18135. *
  18136. * @augments Mesh
  18137. */
  18138. class SkinnedMesh extends Mesh {
  18139. /**
  18140. * Constructs a new skinned mesh.
  18141. *
  18142. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18143. * @param {Material|Array<Material>} [material] - The mesh material.
  18144. */
  18145. constructor( geometry, material ) {
  18146. super( geometry, material );
  18147. /**
  18148. * This flag can be used for type testing.
  18149. *
  18150. * @type {boolean}
  18151. * @readonly
  18152. * @default true
  18153. */
  18154. this.isSkinnedMesh = true;
  18155. this.type = 'SkinnedMesh';
  18156. /**
  18157. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  18158. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  18159. * across multiple skinned meshes.
  18160. *
  18161. * @type {(AttachedBindMode|DetachedBindMode)}
  18162. * @default AttachedBindMode
  18163. */
  18164. this.bindMode = AttachedBindMode;
  18165. /**
  18166. * The base matrix that is used for the bound bone transforms.
  18167. *
  18168. * @type {Matrix4}
  18169. */
  18170. this.bindMatrix = new Matrix4();
  18171. /**
  18172. * The base matrix that is used for resetting the bound bone transforms.
  18173. *
  18174. * @type {Matrix4}
  18175. */
  18176. this.bindMatrixInverse = new Matrix4();
  18177. /**
  18178. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  18179. *
  18180. * @type {?Box3}
  18181. * @default null
  18182. */
  18183. this.boundingBox = null;
  18184. /**
  18185. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  18186. *
  18187. * @type {?Sphere}
  18188. * @default null
  18189. */
  18190. this.boundingSphere = null;
  18191. }
  18192. /**
  18193. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  18194. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18195. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  18196. * the current animation state.
  18197. */
  18198. computeBoundingBox() {
  18199. const geometry = this.geometry;
  18200. if ( this.boundingBox === null ) {
  18201. this.boundingBox = new Box3();
  18202. }
  18203. this.boundingBox.makeEmpty();
  18204. const positionAttribute = geometry.getAttribute( 'position' );
  18205. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18206. this.getVertexPosition( i, _vertex );
  18207. this.boundingBox.expandByPoint( _vertex );
  18208. }
  18209. }
  18210. /**
  18211. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  18212. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  18213. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  18214. * per frame in order to reflect the current animation state.
  18215. */
  18216. computeBoundingSphere() {
  18217. const geometry = this.geometry;
  18218. if ( this.boundingSphere === null ) {
  18219. this.boundingSphere = new Sphere();
  18220. }
  18221. this.boundingSphere.makeEmpty();
  18222. const positionAttribute = geometry.getAttribute( 'position' );
  18223. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18224. this.getVertexPosition( i, _vertex );
  18225. this.boundingSphere.expandByPoint( _vertex );
  18226. }
  18227. }
  18228. copy( source, recursive ) {
  18229. super.copy( source, recursive );
  18230. this.bindMode = source.bindMode;
  18231. this.bindMatrix.copy( source.bindMatrix );
  18232. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18233. this.skeleton = source.skeleton;
  18234. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18235. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18236. return this;
  18237. }
  18238. raycast( raycaster, intersects ) {
  18239. const material = this.material;
  18240. const matrixWorld = this.matrixWorld;
  18241. if ( material === undefined ) return;
  18242. // test with bounding sphere in world space
  18243. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18244. _sphere$5.copy( this.boundingSphere );
  18245. _sphere$5.applyMatrix4( matrixWorld );
  18246. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  18247. // convert ray to local space of skinned mesh
  18248. _inverseMatrix$2.copy( matrixWorld ).invert();
  18249. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18250. // test with bounding box in local space
  18251. if ( this.boundingBox !== null ) {
  18252. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18253. }
  18254. // test for intersections with geometry
  18255. this._computeIntersections( raycaster, intersects, _ray$2 );
  18256. }
  18257. getVertexPosition( index, target ) {
  18258. super.getVertexPosition( index, target );
  18259. this.applyBoneTransform( index, target );
  18260. return target;
  18261. }
  18262. /**
  18263. * Binds the given skeleton to the skinned mesh.
  18264. *
  18265. * @param {Skeleton} skeleton - The skeleton to bind.
  18266. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  18267. * the skinned mesh's world matrix will be used instead.
  18268. */
  18269. bind( skeleton, bindMatrix ) {
  18270. this.skeleton = skeleton;
  18271. if ( bindMatrix === undefined ) {
  18272. this.updateMatrixWorld( true );
  18273. this.skeleton.calculateInverses();
  18274. bindMatrix = this.matrixWorld;
  18275. }
  18276. this.bindMatrix.copy( bindMatrix );
  18277. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18278. }
  18279. /**
  18280. * This method sets the skinned mesh in the rest pose).
  18281. */
  18282. pose() {
  18283. this.skeleton.pose();
  18284. }
  18285. /**
  18286. * Normalizes the skin weights which are defined as a buffer attribute
  18287. * in the skinned mesh's geometry.
  18288. */
  18289. normalizeSkinWeights() {
  18290. const vector = new Vector4();
  18291. const skinWeight = this.geometry.attributes.skinWeight;
  18292. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18293. vector.fromBufferAttribute( skinWeight, i );
  18294. const scale = 1.0 / vector.manhattanLength();
  18295. if ( scale !== Infinity ) {
  18296. vector.multiplyScalar( scale );
  18297. } else {
  18298. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18299. }
  18300. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18301. }
  18302. }
  18303. updateMatrixWorld( force ) {
  18304. super.updateMatrixWorld( force );
  18305. if ( this.bindMode === AttachedBindMode ) {
  18306. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18307. } else if ( this.bindMode === DetachedBindMode ) {
  18308. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18309. } else {
  18310. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18311. }
  18312. }
  18313. /**
  18314. * Applies the bone transform associated with the given index to the given
  18315. * vertex position. Returns the updated vector.
  18316. *
  18317. * @param {number} index - The vertex index.
  18318. * @param {Vector3} target - The target object that is used to store the method's result.
  18319. * the skinned mesh's world matrix will be used instead.
  18320. * @return {Vector3} The updated vertex position.
  18321. */
  18322. applyBoneTransform( index, target ) {
  18323. const skeleton = this.skeleton;
  18324. const geometry = this.geometry;
  18325. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18326. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18327. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18328. target.set( 0, 0, 0 );
  18329. for ( let i = 0; i < 4; i ++ ) {
  18330. const weight = _skinWeight.getComponent( i );
  18331. if ( weight !== 0 ) {
  18332. const boneIndex = _skinIndex.getComponent( i );
  18333. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18334. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18335. }
  18336. }
  18337. return target.applyMatrix4( this.bindMatrixInverse );
  18338. }
  18339. }
  18340. /**
  18341. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  18342. * the {@link SkinnedMesh}.
  18343. *
  18344. * ```js
  18345. * const root = new THREE.Bone();
  18346. * const child = new THREE.Bone();
  18347. *
  18348. * root.add( child );
  18349. * child.position.y = 5;
  18350. * ```
  18351. *
  18352. * @augments Object3D
  18353. */
  18354. class Bone extends Object3D {
  18355. /**
  18356. * Constructs a new bone.
  18357. */
  18358. constructor() {
  18359. super();
  18360. /**
  18361. * This flag can be used for type testing.
  18362. *
  18363. * @type {boolean}
  18364. * @readonly
  18365. * @default true
  18366. */
  18367. this.isBone = true;
  18368. this.type = 'Bone';
  18369. }
  18370. }
  18371. /**
  18372. * Creates a texture directly from raw buffer data.
  18373. *
  18374. * The interpretation of the data depends on type and format: If the type is
  18375. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  18376. * texel data. If the format is `RGBAFormat`, data needs four values for
  18377. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  18378. *
  18379. * @augments Texture
  18380. */
  18381. class DataTexture extends Texture {
  18382. /**
  18383. * Constructs a new data texture.
  18384. *
  18385. * @param {?TypedArray} [data=null] - The buffer data.
  18386. * @param {number} [width=1] - The width of the texture.
  18387. * @param {number} [height=1] - The height of the texture.
  18388. * @param {number} [format=RGBAFormat] - The texture format.
  18389. * @param {number} [type=UnsignedByteType] - The texture type.
  18390. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  18391. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  18392. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  18393. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  18394. * @param {number} [minFilter=NearestFilter] - The min filter value.
  18395. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  18396. * @param {string} [colorSpace=NoColorSpace] - The color space.
  18397. */
  18398. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18399. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18400. /**
  18401. * This flag can be used for type testing.
  18402. *
  18403. * @type {boolean}
  18404. * @readonly
  18405. * @default true
  18406. */
  18407. this.isDataTexture = true;
  18408. /**
  18409. * The image definition of a data texture.
  18410. *
  18411. * @type {{data:TypedArray,width:number,height:number}}
  18412. */
  18413. this.image = { data: data, width: width, height: height };
  18414. /**
  18415. * Whether to generate mipmaps (if possible) for a texture.
  18416. *
  18417. * Overwritten and set to `false` by default.
  18418. *
  18419. * @type {boolean}
  18420. * @default false
  18421. */
  18422. this.generateMipmaps = false;
  18423. /**
  18424. * If set to `true`, the texture is flipped along the vertical axis when
  18425. * uploaded to the GPU.
  18426. *
  18427. * Overwritten and set to `false` by default.
  18428. *
  18429. * @type {boolean}
  18430. * @default false
  18431. */
  18432. this.flipY = false;
  18433. /**
  18434. * Specifies the alignment requirements for the start of each pixel row in memory.
  18435. *
  18436. * Overwritten and set to `1` by default.
  18437. *
  18438. * @type {boolean}
  18439. * @default 1
  18440. */
  18441. this.unpackAlignment = 1;
  18442. }
  18443. }
  18444. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18445. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18446. /**
  18447. * Class for representing the armatures in `three.js`. The skeleton
  18448. * is defined by a hierarchy of bones.
  18449. *
  18450. * ```js
  18451. * const bones = [];
  18452. *
  18453. * const shoulder = new THREE.Bone();
  18454. * const elbow = new THREE.Bone();
  18455. * const hand = new THREE.Bone();
  18456. *
  18457. * shoulder.add( elbow );
  18458. * elbow.add( hand );
  18459. *
  18460. * bones.push( shoulder , elbow, hand);
  18461. *
  18462. * shoulder.position.y = -5;
  18463. * elbow.position.y = 0;
  18464. * hand.position.y = 5;
  18465. *
  18466. * const armSkeleton = new THREE.Skeleton( bones );
  18467. * ```
  18468. */
  18469. class Skeleton {
  18470. /**
  18471. * Constructs a new skeleton.
  18472. *
  18473. * @param {Array<Bone>} [bones] - An array of bones.
  18474. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  18475. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  18476. */
  18477. constructor( bones = [], boneInverses = [] ) {
  18478. this.uuid = generateUUID();
  18479. /**
  18480. * An array of bones defining the skeleton.
  18481. *
  18482. * @type {Array<Bone>}
  18483. */
  18484. this.bones = bones.slice( 0 );
  18485. /**
  18486. * An array of bone inverse matrices.
  18487. *
  18488. * @type {Array<Matrix4>}
  18489. */
  18490. this.boneInverses = boneInverses;
  18491. /**
  18492. * An array buffer holding the bone data.
  18493. * Input data for {@link Skeleton#boneTexture}.
  18494. *
  18495. * @type {?Float32Array}
  18496. * @default null
  18497. */
  18498. this.boneMatrices = null;
  18499. /**
  18500. * A texture holding the bone data for use
  18501. * in the vertex shader.
  18502. *
  18503. * @type {?DataTexture}
  18504. * @default null
  18505. */
  18506. this.boneTexture = null;
  18507. this.init();
  18508. }
  18509. /**
  18510. * Initializes the skeleton. This method gets automatically called by the constructor
  18511. * but depending on how the skeleton is created it might be necessary to call this method
  18512. * manually.
  18513. */
  18514. init() {
  18515. const bones = this.bones;
  18516. const boneInverses = this.boneInverses;
  18517. this.boneMatrices = new Float32Array( bones.length * 16 );
  18518. // calculate inverse bone matrices if necessary
  18519. if ( boneInverses.length === 0 ) {
  18520. this.calculateInverses();
  18521. } else {
  18522. // handle special case
  18523. if ( bones.length !== boneInverses.length ) {
  18524. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18525. this.boneInverses = [];
  18526. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18527. this.boneInverses.push( new Matrix4() );
  18528. }
  18529. }
  18530. }
  18531. }
  18532. /**
  18533. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  18534. * and fills it with new matrices.
  18535. */
  18536. calculateInverses() {
  18537. this.boneInverses.length = 0;
  18538. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18539. const inverse = new Matrix4();
  18540. if ( this.bones[ i ] ) {
  18541. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18542. }
  18543. this.boneInverses.push( inverse );
  18544. }
  18545. }
  18546. /**
  18547. * Resets the skeleton to the base pose.
  18548. */
  18549. pose() {
  18550. // recover the bind-time world matrices
  18551. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18552. const bone = this.bones[ i ];
  18553. if ( bone ) {
  18554. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18555. }
  18556. }
  18557. // compute the local matrices, positions, rotations and scales
  18558. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18559. const bone = this.bones[ i ];
  18560. if ( bone ) {
  18561. if ( bone.parent && bone.parent.isBone ) {
  18562. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18563. bone.matrix.multiply( bone.matrixWorld );
  18564. } else {
  18565. bone.matrix.copy( bone.matrixWorld );
  18566. }
  18567. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18568. }
  18569. }
  18570. }
  18571. /**
  18572. * Resets the skeleton to the base pose.
  18573. */
  18574. update() {
  18575. const bones = this.bones;
  18576. const boneInverses = this.boneInverses;
  18577. const boneMatrices = this.boneMatrices;
  18578. const boneTexture = this.boneTexture;
  18579. // flatten bone matrices to array
  18580. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18581. // compute the offset between the current and the original transform
  18582. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18583. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18584. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18585. }
  18586. if ( boneTexture !== null ) {
  18587. boneTexture.needsUpdate = true;
  18588. }
  18589. }
  18590. /**
  18591. * Returns a new skeleton with copied values from this instance.
  18592. *
  18593. * @return {Skeleton} A clone of this instance.
  18594. */
  18595. clone() {
  18596. return new Skeleton( this.bones, this.boneInverses );
  18597. }
  18598. /**
  18599. * Computes a data texture for passing bone data to the vertex shader.
  18600. *
  18601. * @return {Skeleton} A reference of this instance.
  18602. */
  18603. computeBoneTexture() {
  18604. // layout (1 matrix = 4 pixels)
  18605. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18606. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18607. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18608. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18609. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18610. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18611. size = Math.ceil( size / 4 ) * 4;
  18612. size = Math.max( size, 4 );
  18613. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18614. boneMatrices.set( this.boneMatrices ); // copy current values
  18615. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18616. boneTexture.needsUpdate = true;
  18617. this.boneMatrices = boneMatrices;
  18618. this.boneTexture = boneTexture;
  18619. return this;
  18620. }
  18621. /**
  18622. * Searches through the skeleton's bone array and returns the first with a
  18623. * matching name.
  18624. *
  18625. * @param {string} name - The name of the bone.
  18626. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  18627. */
  18628. getBoneByName( name ) {
  18629. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18630. const bone = this.bones[ i ];
  18631. if ( bone.name === name ) {
  18632. return bone;
  18633. }
  18634. }
  18635. return undefined;
  18636. }
  18637. /**
  18638. * Frees the GPU-related resources allocated by this instance. Call this
  18639. * method whenever this instance is no longer used in your app.
  18640. */
  18641. dispose( ) {
  18642. if ( this.boneTexture !== null ) {
  18643. this.boneTexture.dispose();
  18644. this.boneTexture = null;
  18645. }
  18646. }
  18647. /**
  18648. * Setups the skeleton by the given JSON and bones.
  18649. *
  18650. * @param {Object} json - The skeleton as serialized JSON.
  18651. * @param {Object<string, Bone>} bones - An array of bones.
  18652. * @return {Skeleton} A reference of this instance.
  18653. */
  18654. fromJSON( json, bones ) {
  18655. this.uuid = json.uuid;
  18656. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18657. const uuid = json.bones[ i ];
  18658. let bone = bones[ uuid ];
  18659. if ( bone === undefined ) {
  18660. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18661. bone = new Bone();
  18662. }
  18663. this.bones.push( bone );
  18664. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18665. }
  18666. this.init();
  18667. return this;
  18668. }
  18669. /**
  18670. * Serializes the skeleton into JSON.
  18671. *
  18672. * @return {Object} A JSON object representing the serialized skeleton.
  18673. * @see {@link ObjectLoader#parse}
  18674. */
  18675. toJSON() {
  18676. const data = {
  18677. metadata: {
  18678. version: 4.6,
  18679. type: 'Skeleton',
  18680. generator: 'Skeleton.toJSON'
  18681. },
  18682. bones: [],
  18683. boneInverses: []
  18684. };
  18685. data.uuid = this.uuid;
  18686. const bones = this.bones;
  18687. const boneInverses = this.boneInverses;
  18688. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18689. const bone = bones[ i ];
  18690. data.bones.push( bone.uuid );
  18691. const boneInverse = boneInverses[ i ];
  18692. data.boneInverses.push( boneInverse.toArray() );
  18693. }
  18694. return data;
  18695. }
  18696. }
  18697. /**
  18698. * An instanced version of a buffer attribute.
  18699. *
  18700. * @augments BufferAttribute
  18701. */
  18702. class InstancedBufferAttribute extends BufferAttribute {
  18703. /**
  18704. * Constructs a new instanced buffer attribute.
  18705. *
  18706. * @param {TypedArray} array - The array holding the attribute data.
  18707. * @param {number} itemSize - The item size.
  18708. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  18709. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  18710. */
  18711. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18712. super( array, itemSize, normalized );
  18713. /**
  18714. * This flag can be used for type testing.
  18715. *
  18716. * @type {boolean}
  18717. * @readonly
  18718. * @default true
  18719. */
  18720. this.isInstancedBufferAttribute = true;
  18721. /**
  18722. * Defines how often a value of this buffer attribute should be repeated. A
  18723. * value of one means that each value of the instanced attribute is used for
  18724. * a single instance. A value of two means that each value is used for two
  18725. * consecutive instances (and so on).
  18726. *
  18727. * @type {number}
  18728. * @default 1
  18729. */
  18730. this.meshPerAttribute = meshPerAttribute;
  18731. }
  18732. copy( source ) {
  18733. super.copy( source );
  18734. this.meshPerAttribute = source.meshPerAttribute;
  18735. return this;
  18736. }
  18737. toJSON() {
  18738. const data = super.toJSON();
  18739. data.meshPerAttribute = this.meshPerAttribute;
  18740. data.isInstancedBufferAttribute = true;
  18741. return data;
  18742. }
  18743. }
  18744. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18745. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18746. const _instanceIntersects = [];
  18747. const _box3 = /*@__PURE__*/ new Box3();
  18748. const _identity = /*@__PURE__*/ new Matrix4();
  18749. const _mesh$1 = /*@__PURE__*/ new Mesh();
  18750. const _sphere$4 = /*@__PURE__*/ new Sphere();
  18751. /**
  18752. * A special version of a mesh with instanced rendering support. Use
  18753. * this class if you have to render a large number of objects with the same
  18754. * geometry and material(s) but with different world transformations. The usage
  18755. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  18756. * improve the overall rendering performance in your application.
  18757. *
  18758. * @augments Mesh
  18759. */
  18760. class InstancedMesh extends Mesh {
  18761. /**
  18762. * Constructs a new instanced mesh.
  18763. *
  18764. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18765. * @param {Material|Array<Material>} [material] - The mesh material.
  18766. * @param {number} count - The number of instances.
  18767. */
  18768. constructor( geometry, material, count ) {
  18769. super( geometry, material );
  18770. /**
  18771. * This flag can be used for type testing.
  18772. *
  18773. * @type {boolean}
  18774. * @readonly
  18775. * @default true
  18776. */
  18777. this.isInstancedMesh = true;
  18778. /**
  18779. * Represents the local transformation of all instances. You have to set its
  18780. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18781. * via {@link InstancedMesh#setMatrixAt}.
  18782. *
  18783. * @type {InstancedBufferAttribute}
  18784. */
  18785. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18786. /**
  18787. * Represents the color of all instances. You have to set its
  18788. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18789. * via {@link InstancedMesh#setColorAt}.
  18790. *
  18791. * @type {?InstancedBufferAttribute}
  18792. * @default null
  18793. */
  18794. this.instanceColor = null;
  18795. /**
  18796. * Represents the morph target weights of all instances. You have to set its
  18797. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  18798. * via {@link InstancedMesh#setMorphAt}.
  18799. *
  18800. * @type {?DataTexture}
  18801. * @default null
  18802. */
  18803. this.morphTexture = null;
  18804. /**
  18805. * The number of instances.
  18806. *
  18807. * @type {number}
  18808. */
  18809. this.count = count;
  18810. /**
  18811. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  18812. *
  18813. * @type {?Box3}
  18814. * @default null
  18815. */
  18816. this.boundingBox = null;
  18817. /**
  18818. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  18819. *
  18820. * @type {?Sphere}
  18821. * @default null
  18822. */
  18823. this.boundingSphere = null;
  18824. for ( let i = 0; i < count; i ++ ) {
  18825. this.setMatrixAt( i, _identity );
  18826. }
  18827. }
  18828. /**
  18829. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  18830. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18831. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  18832. */
  18833. computeBoundingBox() {
  18834. const geometry = this.geometry;
  18835. const count = this.count;
  18836. if ( this.boundingBox === null ) {
  18837. this.boundingBox = new Box3();
  18838. }
  18839. if ( geometry.boundingBox === null ) {
  18840. geometry.computeBoundingBox();
  18841. }
  18842. this.boundingBox.makeEmpty();
  18843. for ( let i = 0; i < count; i ++ ) {
  18844. this.getMatrixAt( i, _instanceLocalMatrix );
  18845. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  18846. this.boundingBox.union( _box3 );
  18847. }
  18848. }
  18849. /**
  18850. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  18851. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  18852. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  18853. */
  18854. computeBoundingSphere() {
  18855. const geometry = this.geometry;
  18856. const count = this.count;
  18857. if ( this.boundingSphere === null ) {
  18858. this.boundingSphere = new Sphere();
  18859. }
  18860. if ( geometry.boundingSphere === null ) {
  18861. geometry.computeBoundingSphere();
  18862. }
  18863. this.boundingSphere.makeEmpty();
  18864. for ( let i = 0; i < count; i ++ ) {
  18865. this.getMatrixAt( i, _instanceLocalMatrix );
  18866. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  18867. this.boundingSphere.union( _sphere$4 );
  18868. }
  18869. }
  18870. copy( source, recursive ) {
  18871. super.copy( source, recursive );
  18872. this.instanceMatrix.copy( source.instanceMatrix );
  18873. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  18874. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18875. this.count = source.count;
  18876. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18877. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18878. return this;
  18879. }
  18880. /**
  18881. * Gets the color of the defined instance.
  18882. *
  18883. * @param {number} index - The instance index.
  18884. * @param {Color} color - The target object that is used to store the method's result.
  18885. */
  18886. getColorAt( index, color ) {
  18887. color.fromArray( this.instanceColor.array, index * 3 );
  18888. }
  18889. /**
  18890. * Gets the local transformation matrix of the defined instance.
  18891. *
  18892. * @param {number} index - The instance index.
  18893. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  18894. */
  18895. getMatrixAt( index, matrix ) {
  18896. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18897. }
  18898. /**
  18899. * Gets the morph target weights of the defined instance.
  18900. *
  18901. * @param {number} index - The instance index.
  18902. * @param {Mesh} object - The target object that is used to store the method's result.
  18903. */
  18904. getMorphAt( index, object ) {
  18905. const objectInfluences = object.morphTargetInfluences;
  18906. const array = this.morphTexture.source.data.data;
  18907. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  18908. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  18909. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  18910. objectInfluences[ i ] = array[ dataIndex + i ];
  18911. }
  18912. }
  18913. raycast( raycaster, intersects ) {
  18914. const matrixWorld = this.matrixWorld;
  18915. const raycastTimes = this.count;
  18916. _mesh$1.geometry = this.geometry;
  18917. _mesh$1.material = this.material;
  18918. if ( _mesh$1.material === undefined ) return;
  18919. // test with bounding sphere first
  18920. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18921. _sphere$4.copy( this.boundingSphere );
  18922. _sphere$4.applyMatrix4( matrixWorld );
  18923. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  18924. // now test each instance
  18925. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18926. // calculate the world matrix for each instance
  18927. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18928. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18929. // the mesh represents this single instance
  18930. _mesh$1.matrixWorld = _instanceWorldMatrix;
  18931. _mesh$1.raycast( raycaster, _instanceIntersects );
  18932. // process the result of raycast
  18933. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18934. const intersect = _instanceIntersects[ i ];
  18935. intersect.instanceId = instanceId;
  18936. intersect.object = this;
  18937. intersects.push( intersect );
  18938. }
  18939. _instanceIntersects.length = 0;
  18940. }
  18941. }
  18942. /**
  18943. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  18944. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  18945. *
  18946. * @param {number} index - The instance index.
  18947. * @param {Color} color - The instance color.
  18948. */
  18949. setColorAt( index, color ) {
  18950. if ( this.instanceColor === null ) {
  18951. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  18952. }
  18953. color.toArray( this.instanceColor.array, index * 3 );
  18954. }
  18955. /**
  18956. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  18957. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  18958. *
  18959. * @param {number} index - The instance index.
  18960. * @param {Matrix4} matrix - The local transformation.
  18961. */
  18962. setMatrixAt( index, matrix ) {
  18963. matrix.toArray( this.instanceMatrix.array, index * 16 );
  18964. }
  18965. /**
  18966. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  18967. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  18968. *
  18969. * @param {number} index - The instance index.
  18970. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  18971. * of a single instance.
  18972. */
  18973. setMorphAt( index, object ) {
  18974. const objectInfluences = object.morphTargetInfluences;
  18975. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  18976. if ( this.morphTexture === null ) {
  18977. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  18978. }
  18979. const array = this.morphTexture.source.data.data;
  18980. let morphInfluencesSum = 0;
  18981. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  18982. morphInfluencesSum += objectInfluences[ i ];
  18983. }
  18984. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  18985. const dataIndex = len * index;
  18986. array[ dataIndex ] = morphBaseInfluence;
  18987. array.set( objectInfluences, dataIndex + 1 );
  18988. }
  18989. updateMorphTargets() {
  18990. }
  18991. /**
  18992. * Frees the GPU-related resources allocated by this instance. Call this
  18993. * method whenever this instance is no longer used in your app.
  18994. */
  18995. dispose() {
  18996. this.dispatchEvent( { type: 'dispose' } );
  18997. if ( this.morphTexture !== null ) {
  18998. this.morphTexture.dispose();
  18999. this.morphTexture = null;
  19000. }
  19001. }
  19002. }
  19003. const _vector1 = /*@__PURE__*/ new Vector3();
  19004. const _vector2 = /*@__PURE__*/ new Vector3();
  19005. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  19006. /**
  19007. * A two dimensional surface that extends infinitely in 3D space, represented
  19008. * in [Hessian normal form]{@link http://mathworld.wolfram.com/HessianNormalForm.html}
  19009. * by a unit length normal vector and a constant.
  19010. */
  19011. class Plane {
  19012. /**
  19013. * Constructs a new plane.
  19014. *
  19015. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  19016. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  19017. */
  19018. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  19019. /**
  19020. * This flag can be used for type testing.
  19021. *
  19022. * @type {boolean}
  19023. * @readonly
  19024. * @default true
  19025. */
  19026. this.isPlane = true;
  19027. /**
  19028. * A unit length vector defining the normal of the plane.
  19029. *
  19030. * @type {Vector3}
  19031. */
  19032. this.normal = normal;
  19033. /**
  19034. * The signed distance from the origin to the plane.
  19035. *
  19036. * @type {number}
  19037. * @default 0
  19038. */
  19039. this.constant = constant;
  19040. }
  19041. /**
  19042. * Sets the plane components by copying the given values.
  19043. *
  19044. * @param {Vector3} normal - The normal.
  19045. * @param {number} constant - The constant.
  19046. * @return {Plane} A reference to this plane.
  19047. */
  19048. set( normal, constant ) {
  19049. this.normal.copy( normal );
  19050. this.constant = constant;
  19051. return this;
  19052. }
  19053. /**
  19054. * Sets the plane components by defining `x`, `y`, `z` as the
  19055. * plane normal and `w` as the constant.
  19056. *
  19057. * @param {number} x - The value for the normal's x component.
  19058. * @param {number} y - The value for the normal's y component.
  19059. * @param {number} z - The value for the normal's z component.
  19060. * @param {number} w - The constant value.
  19061. * @return {Plane} A reference to this plane.
  19062. */
  19063. setComponents( x, y, z, w ) {
  19064. this.normal.set( x, y, z );
  19065. this.constant = w;
  19066. return this;
  19067. }
  19068. /**
  19069. * Sets the plane from the given normal and coplanar point (that is a point
  19070. * that lies onto the plane).
  19071. *
  19072. * @param {Vector3} normal - The normal.
  19073. * @param {Vector3} point - A coplanar point.
  19074. * @return {Plane} A reference to this plane.
  19075. */
  19076. setFromNormalAndCoplanarPoint( normal, point ) {
  19077. this.normal.copy( normal );
  19078. this.constant = - point.dot( this.normal );
  19079. return this;
  19080. }
  19081. /**
  19082. * Sets the plane from three coplanar points. The winding order is
  19083. * assumed to be counter-clockwise, and determines the direction of
  19084. * the plane normal.
  19085. *
  19086. * @param {Vector3} a - The first coplanar point.
  19087. * @param {Vector3} b - The second coplanar point.
  19088. * @param {Vector3} c - The third coplanar point.
  19089. * @return {Plane} A reference to this plane.
  19090. */
  19091. setFromCoplanarPoints( a, b, c ) {
  19092. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  19093. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  19094. this.setFromNormalAndCoplanarPoint( normal, a );
  19095. return this;
  19096. }
  19097. /**
  19098. * Copies the values of the given plane to this instance.
  19099. *
  19100. * @param {Plane} plane - The plane to copy.
  19101. * @return {Plane} A reference to this plane.
  19102. */
  19103. copy( plane ) {
  19104. this.normal.copy( plane.normal );
  19105. this.constant = plane.constant;
  19106. return this;
  19107. }
  19108. /**
  19109. * Normalizes the plane normal and adjusts the constant accordingly.
  19110. *
  19111. * @return {Plane} A reference to this plane.
  19112. */
  19113. normalize() {
  19114. // Note: will lead to a divide by zero if the plane is invalid.
  19115. const inverseNormalLength = 1.0 / this.normal.length();
  19116. this.normal.multiplyScalar( inverseNormalLength );
  19117. this.constant *= inverseNormalLength;
  19118. return this;
  19119. }
  19120. /**
  19121. * Negates both the plane normal and the constant.
  19122. *
  19123. * @return {Plane} A reference to this plane.
  19124. */
  19125. negate() {
  19126. this.constant *= -1;
  19127. this.normal.negate();
  19128. return this;
  19129. }
  19130. /**
  19131. * Returns the signed distance from the given point to this plane.
  19132. *
  19133. * @param {Vector3} point - The point to compute the distance for.
  19134. * @return {number} The signed distance.
  19135. */
  19136. distanceToPoint( point ) {
  19137. return this.normal.dot( point ) + this.constant;
  19138. }
  19139. /**
  19140. * Returns the signed distance from the given sphere to this plane.
  19141. *
  19142. * @param {Sphere} sphere - The sphere to compute the distance for.
  19143. * @return {number} The signed distance.
  19144. */
  19145. distanceToSphere( sphere ) {
  19146. return this.distanceToPoint( sphere.center ) - sphere.radius;
  19147. }
  19148. /**
  19149. * Projects a the given point onto the plane.
  19150. *
  19151. * @param {Vector3} point - The point to project.
  19152. * @param {Vector3} target - The target vector that is used to store the method's result.
  19153. * @return {Vector3} The projected point on the plane.
  19154. */
  19155. projectPoint( point, target ) {
  19156. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  19157. }
  19158. /**
  19159. * Returns the intersection point of the passed line and the plane. Returns
  19160. * `null` if the line does not intersect. Returns the line's starting point if
  19161. * the line is coplanar with the plane.
  19162. *
  19163. * @param {Line3} line - The line to compute the intersection for.
  19164. * @param {Vector3} target - The target vector that is used to store the method's result.
  19165. * @return {?Vector3} The intersection point.
  19166. */
  19167. intersectLine( line, target ) {
  19168. const direction = line.delta( _vector1 );
  19169. const denominator = this.normal.dot( direction );
  19170. if ( denominator === 0 ) {
  19171. // line is coplanar, return origin
  19172. if ( this.distanceToPoint( line.start ) === 0 ) {
  19173. return target.copy( line.start );
  19174. }
  19175. // Unsure if this is the correct method to handle this case.
  19176. return null;
  19177. }
  19178. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  19179. if ( t < 0 || t > 1 ) {
  19180. return null;
  19181. }
  19182. return target.copy( line.start ).addScaledVector( direction, t );
  19183. }
  19184. /**
  19185. * Returns `true` if the given line segment intersects with (passes through) the plane.
  19186. *
  19187. * @param {Line3} line - The line to test.
  19188. * @return {boolean} Whether the given line segment intersects with the plane or not.
  19189. */
  19190. intersectsLine( line ) {
  19191. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  19192. const startSign = this.distanceToPoint( line.start );
  19193. const endSign = this.distanceToPoint( line.end );
  19194. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  19195. }
  19196. /**
  19197. * Returns `true` if the given bounding box intersects with the plane.
  19198. *
  19199. * @param {Box3} box - The bounding box to test.
  19200. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  19201. */
  19202. intersectsBox( box ) {
  19203. return box.intersectsPlane( this );
  19204. }
  19205. /**
  19206. * Returns `true` if the given bounding sphere intersects with the plane.
  19207. *
  19208. * @param {Sphere} sphere - The bounding sphere to test.
  19209. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  19210. */
  19211. intersectsSphere( sphere ) {
  19212. return sphere.intersectsPlane( this );
  19213. }
  19214. /**
  19215. * Returns a coplanar vector to the plane, by calculating the
  19216. * projection of the normal at the origin onto the plane.
  19217. *
  19218. * @param {Vector3} target - The target vector that is used to store the method's result.
  19219. * @return {Vector3} The coplanar point.
  19220. */
  19221. coplanarPoint( target ) {
  19222. return target.copy( this.normal ).multiplyScalar( - this.constant );
  19223. }
  19224. /**
  19225. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  19226. *
  19227. * The optional normal matrix can be pre-computed like so:
  19228. * ```js
  19229. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  19230. * ```
  19231. *
  19232. * @param {Matrix4} matrix - The transformation matrix.
  19233. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  19234. * @return {Plane} A reference to this plane.
  19235. */
  19236. applyMatrix4( matrix, optionalNormalMatrix ) {
  19237. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  19238. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  19239. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  19240. this.constant = - referencePoint.dot( normal );
  19241. return this;
  19242. }
  19243. /**
  19244. * Translates the plane by the distance defined by the given offset vector.
  19245. * Note that this only affects the plane constant and will not affect the normal vector.
  19246. *
  19247. * @param {Vector3} offset - The offset vector.
  19248. * @return {Plane} A reference to this plane.
  19249. */
  19250. translate( offset ) {
  19251. this.constant -= offset.dot( this.normal );
  19252. return this;
  19253. }
  19254. /**
  19255. * Returns `true` if this plane is equal with the given one.
  19256. *
  19257. * @param {Plane} plane - The plane to test for equality.
  19258. * @return {boolean} Whether this plane is equal with the given one.
  19259. */
  19260. equals( plane ) {
  19261. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  19262. }
  19263. /**
  19264. * Returns a new plane with copied values from this instance.
  19265. *
  19266. * @return {Plane} A clone of this instance.
  19267. */
  19268. clone() {
  19269. return new this.constructor().copy( this );
  19270. }
  19271. }
  19272. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19273. const _vector$6 = /*@__PURE__*/ new Vector3();
  19274. /**
  19275. * Frustums are used to determine what is inside the camera's field of view.
  19276. * They help speed up the rendering process - objects which lie outside a camera's
  19277. * frustum can safely be excluded from rendering.
  19278. *
  19279. * This class is mainly intended for use internally by a renderer.
  19280. */
  19281. class Frustum {
  19282. /**
  19283. * Constructs a new frustum.
  19284. *
  19285. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19286. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19287. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19288. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19289. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19290. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19291. */
  19292. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  19293. /**
  19294. * This array holds the planes that enclose the frustum.
  19295. *
  19296. * @type {Array<Plane>}
  19297. */
  19298. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  19299. }
  19300. /**
  19301. * Sets the frustum planes by copying the given planes.
  19302. *
  19303. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19304. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19305. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19306. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19307. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19308. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19309. * @return {Frustum} A reference to this frustum.
  19310. */
  19311. set( p0, p1, p2, p3, p4, p5 ) {
  19312. const planes = this.planes;
  19313. planes[ 0 ].copy( p0 );
  19314. planes[ 1 ].copy( p1 );
  19315. planes[ 2 ].copy( p2 );
  19316. planes[ 3 ].copy( p3 );
  19317. planes[ 4 ].copy( p4 );
  19318. planes[ 5 ].copy( p5 );
  19319. return this;
  19320. }
  19321. /**
  19322. * Copies the values of the given frustum to this instance.
  19323. *
  19324. * @param {Frustum} frustum - The frustum to copy.
  19325. * @return {Frustum} A reference to this frustum.
  19326. */
  19327. copy( frustum ) {
  19328. const planes = this.planes;
  19329. for ( let i = 0; i < 6; i ++ ) {
  19330. planes[ i ].copy( frustum.planes[ i ] );
  19331. }
  19332. return this;
  19333. }
  19334. /**
  19335. * Sets the frustum planes from the given projection matrix.
  19336. *
  19337. * @param {Matrix4} m - The projection matrix.
  19338. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  19339. * @return {Frustum} A reference to this frustum.
  19340. */
  19341. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  19342. const planes = this.planes;
  19343. const me = m.elements;
  19344. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  19345. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  19346. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  19347. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  19348. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  19349. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  19350. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  19351. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  19352. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  19353. if ( coordinateSystem === WebGLCoordinateSystem ) {
  19354. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  19355. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  19356. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  19357. } else {
  19358. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  19359. }
  19360. return this;
  19361. }
  19362. /**
  19363. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  19364. *
  19365. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  19366. *
  19367. * @param {Object3D} object - The 3D object to test.
  19368. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  19369. */
  19370. intersectsObject( object ) {
  19371. if ( object.boundingSphere !== undefined ) {
  19372. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  19373. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  19374. } else {
  19375. const geometry = object.geometry;
  19376. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19377. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  19378. }
  19379. return this.intersectsSphere( _sphere$3 );
  19380. }
  19381. /**
  19382. * Returns `true` if the given sprite is intersecting this frustum.
  19383. *
  19384. * @param {Sprite} sprite - The sprite to test.
  19385. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  19386. */
  19387. intersectsSprite( sprite ) {
  19388. _sphere$3.center.set( 0, 0, 0 );
  19389. _sphere$3.radius = 0.7071067811865476;
  19390. _sphere$3.applyMatrix4( sprite.matrixWorld );
  19391. return this.intersectsSphere( _sphere$3 );
  19392. }
  19393. /**
  19394. * Returns `true` if the given bounding sphere is intersecting this frustum.
  19395. *
  19396. * @param {Sphere} sphere - The bounding sphere to test.
  19397. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  19398. */
  19399. intersectsSphere( sphere ) {
  19400. const planes = this.planes;
  19401. const center = sphere.center;
  19402. const negRadius = - sphere.radius;
  19403. for ( let i = 0; i < 6; i ++ ) {
  19404. const distance = planes[ i ].distanceToPoint( center );
  19405. if ( distance < negRadius ) {
  19406. return false;
  19407. }
  19408. }
  19409. return true;
  19410. }
  19411. /**
  19412. * Returns `true` if the given bounding box is intersecting this frustum.
  19413. *
  19414. * @param {Box3} box - The bounding box to test.
  19415. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  19416. */
  19417. intersectsBox( box ) {
  19418. const planes = this.planes;
  19419. for ( let i = 0; i < 6; i ++ ) {
  19420. const plane = planes[ i ];
  19421. // corner at max distance
  19422. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  19423. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  19424. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  19425. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  19426. return false;
  19427. }
  19428. }
  19429. return true;
  19430. }
  19431. /**
  19432. * Returns `true` if the given point lies within the frustum.
  19433. *
  19434. * @param {Vector3} point - The point to test.
  19435. * @return {boolean} Whether the point lies within this frustum or not.
  19436. */
  19437. containsPoint( point ) {
  19438. const planes = this.planes;
  19439. for ( let i = 0; i < 6; i ++ ) {
  19440. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  19441. return false;
  19442. }
  19443. }
  19444. return true;
  19445. }
  19446. /**
  19447. * Returns a new frustum with copied values from this instance.
  19448. *
  19449. * @return {Frustum} A clone of this instance.
  19450. */
  19451. clone() {
  19452. return new this.constructor().copy( this );
  19453. }
  19454. }
  19455. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  19456. const _frustum$1 = /*@__PURE__*/ new Frustum();
  19457. /**
  19458. * FrustumArray is used to determine if an object is visible in at least one camera
  19459. * from an array of cameras. This is particularly useful for multi-view renderers.
  19460. */
  19461. class FrustumArray {
  19462. /**
  19463. * Constructs a new frustum array.
  19464. *
  19465. */
  19466. constructor() {
  19467. /**
  19468. * The coordinate system to use.
  19469. *
  19470. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  19471. * @default WebGLCoordinateSystem
  19472. */
  19473. this.coordinateSystem = WebGLCoordinateSystem;
  19474. }
  19475. /**
  19476. * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
  19477. * from the camera array.
  19478. *
  19479. * @param {Object3D} object - The 3D object to test.
  19480. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19481. * @return {boolean} Whether the 3D object is visible in any camera.
  19482. */
  19483. intersectsObject( object, cameraArray ) {
  19484. if ( ! cameraArray.isArrayCamera || cameraArray.cameras.length === 0 ) {
  19485. return false;
  19486. }
  19487. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19488. const camera = cameraArray.cameras[ i ];
  19489. _projScreenMatrix$2.multiplyMatrices(
  19490. camera.projectionMatrix,
  19491. camera.matrixWorldInverse
  19492. );
  19493. _frustum$1.setFromProjectionMatrix(
  19494. _projScreenMatrix$2,
  19495. this.coordinateSystem
  19496. );
  19497. if ( _frustum$1.intersectsObject( object ) ) {
  19498. return true; // Object is visible in at least one camera
  19499. }
  19500. }
  19501. return false; // Not visible in any camera
  19502. }
  19503. /**
  19504. * Returns `true` if the given sprite is intersecting any frustum
  19505. * from the camera array.
  19506. *
  19507. * @param {Sprite} sprite - The sprite to test.
  19508. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19509. * @return {boolean} Whether the sprite is visible in any camera.
  19510. */
  19511. intersectsSprite( sprite, cameraArray ) {
  19512. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19513. return false;
  19514. }
  19515. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19516. const camera = cameraArray.cameras[ i ];
  19517. _projScreenMatrix$2.multiplyMatrices(
  19518. camera.projectionMatrix,
  19519. camera.matrixWorldInverse
  19520. );
  19521. _frustum$1.setFromProjectionMatrix(
  19522. _projScreenMatrix$2,
  19523. this.coordinateSystem
  19524. );
  19525. if ( _frustum$1.intersectsSprite( sprite ) ) {
  19526. return true; // Sprite is visible in at least one camera
  19527. }
  19528. }
  19529. return false; // Not visible in any camera
  19530. }
  19531. /**
  19532. * Returns `true` if the given bounding sphere is intersecting any frustum
  19533. * from the camera array.
  19534. *
  19535. * @param {Sphere} sphere - The bounding sphere to test.
  19536. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19537. * @return {boolean} Whether the sphere is visible in any camera.
  19538. */
  19539. intersectsSphere( sphere, cameraArray ) {
  19540. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19541. return false;
  19542. }
  19543. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19544. const camera = cameraArray.cameras[ i ];
  19545. _projScreenMatrix$2.multiplyMatrices(
  19546. camera.projectionMatrix,
  19547. camera.matrixWorldInverse
  19548. );
  19549. _frustum$1.setFromProjectionMatrix(
  19550. _projScreenMatrix$2,
  19551. this.coordinateSystem
  19552. );
  19553. if ( _frustum$1.intersectsSphere( sphere ) ) {
  19554. return true; // Sphere is visible in at least one camera
  19555. }
  19556. }
  19557. return false; // Not visible in any camera
  19558. }
  19559. /**
  19560. * Returns `true` if the given bounding box is intersecting any frustum
  19561. * from the camera array.
  19562. *
  19563. * @param {Box3} box - The bounding box to test.
  19564. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19565. * @return {boolean} Whether the box is visible in any camera.
  19566. */
  19567. intersectsBox( box, cameraArray ) {
  19568. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19569. return false;
  19570. }
  19571. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19572. const camera = cameraArray.cameras[ i ];
  19573. _projScreenMatrix$2.multiplyMatrices(
  19574. camera.projectionMatrix,
  19575. camera.matrixWorldInverse
  19576. );
  19577. _frustum$1.setFromProjectionMatrix(
  19578. _projScreenMatrix$2,
  19579. this.coordinateSystem
  19580. );
  19581. if ( _frustum$1.intersectsBox( box ) ) {
  19582. return true; // Box is visible in at least one camera
  19583. }
  19584. }
  19585. return false; // Not visible in any camera
  19586. }
  19587. /**
  19588. * Returns `true` if the given point lies within any frustum
  19589. * from the camera array.
  19590. *
  19591. * @param {Vector3} point - The point to test.
  19592. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19593. * @return {boolean} Whether the point is visible in any camera.
  19594. */
  19595. containsPoint( point, cameraArray ) {
  19596. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19597. return false;
  19598. }
  19599. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19600. const camera = cameraArray.cameras[ i ];
  19601. _projScreenMatrix$2.multiplyMatrices(
  19602. camera.projectionMatrix,
  19603. camera.matrixWorldInverse
  19604. );
  19605. _frustum$1.setFromProjectionMatrix(
  19606. _projScreenMatrix$2,
  19607. this.coordinateSystem
  19608. );
  19609. if ( _frustum$1.containsPoint( point ) ) {
  19610. return true; // Point is visible in at least one camera
  19611. }
  19612. }
  19613. return false; // Not visible in any camera
  19614. }
  19615. /**
  19616. * Returns a new frustum array with copied values from this instance.
  19617. *
  19618. * @return {FrustumArray} A clone of this instance.
  19619. */
  19620. clone() {
  19621. return new FrustumArray();
  19622. }
  19623. }
  19624. function ascIdSort( a, b ) {
  19625. return a - b;
  19626. }
  19627. function sortOpaque( a, b ) {
  19628. return a.z - b.z;
  19629. }
  19630. function sortTransparent( a, b ) {
  19631. return b.z - a.z;
  19632. }
  19633. class MultiDrawRenderList {
  19634. constructor() {
  19635. this.index = 0;
  19636. this.pool = [];
  19637. this.list = [];
  19638. }
  19639. push( start, count, z, index ) {
  19640. const pool = this.pool;
  19641. const list = this.list;
  19642. if ( this.index >= pool.length ) {
  19643. pool.push( {
  19644. start: -1,
  19645. count: -1,
  19646. z: -1,
  19647. index: -1,
  19648. } );
  19649. }
  19650. const item = pool[ this.index ];
  19651. list.push( item );
  19652. this.index ++;
  19653. item.start = start;
  19654. item.count = count;
  19655. item.z = z;
  19656. item.index = index;
  19657. }
  19658. reset() {
  19659. this.list.length = 0;
  19660. this.index = 0;
  19661. }
  19662. }
  19663. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  19664. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  19665. const _frustum = /*@__PURE__*/ new Frustum();
  19666. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  19667. const _box$1 = /*@__PURE__*/ new Box3();
  19668. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19669. const _vector$5 = /*@__PURE__*/ new Vector3();
  19670. const _forward = /*@__PURE__*/ new Vector3();
  19671. const _temp = /*@__PURE__*/ new Vector3();
  19672. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19673. const _mesh = /*@__PURE__*/ new Mesh();
  19674. const _batchIntersects = [];
  19675. // copies data from attribute "src" into "target" starting at "targetOffset"
  19676. function copyAttributeData( src, target, targetOffset = 0 ) {
  19677. const itemSize = target.itemSize;
  19678. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19679. // use the component getters and setters if the array data cannot
  19680. // be copied directly
  19681. const vertexCount = src.count;
  19682. for ( let i = 0; i < vertexCount; i ++ ) {
  19683. for ( let c = 0; c < itemSize; c ++ ) {
  19684. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19685. }
  19686. }
  19687. } else {
  19688. // faster copy approach using typed array set function
  19689. target.array.set( src.array, targetOffset * itemSize );
  19690. }
  19691. target.needsUpdate = true;
  19692. }
  19693. // safely copies array contents to a potentially smaller array
  19694. function copyArrayContents( src, target ) {
  19695. if ( src.constructor !== target.constructor ) {
  19696. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  19697. const len = Math.min( src.length, target.length );
  19698. for ( let i = 0; i < len; i ++ ) {
  19699. target[ i ] = src[ i ];
  19700. }
  19701. } else {
  19702. // if the arrays use the same data layout we can use a fast block copy
  19703. const len = Math.min( src.length, target.length );
  19704. target.set( new src.constructor( src.buffer, 0, len ) );
  19705. }
  19706. }
  19707. /**
  19708. * A special version of a mesh with multi draw batch rendering support. Use
  19709. * this class if you have to render a large number of objects with the same
  19710. * material but with different geometries or world transformations. The usage of
  19711. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  19712. * rendering performance in your application.
  19713. *
  19714. * ```js
  19715. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  19716. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  19717. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  19718. *
  19719. * // initialize and add geometries into the batched mesh
  19720. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  19721. * const boxGeometryId = batchedMesh.addGeometry( box );
  19722. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  19723. *
  19724. * // create instances of those geometries
  19725. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  19726. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  19727. *
  19728. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  19729. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  19730. *
  19731. * // position the geometries
  19732. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  19733. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  19734. *
  19735. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  19736. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  19737. *
  19738. * scene.add( batchedMesh );
  19739. * ```
  19740. *
  19741. * @augments Mesh
  19742. */
  19743. class BatchedMesh extends Mesh {
  19744. /**
  19745. * Constructs a new batched mesh.
  19746. *
  19747. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  19748. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  19749. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  19750. * @param {Material|Array<Material>} [material] - The mesh material.
  19751. */
  19752. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19753. super( new BufferGeometry(), material );
  19754. /**
  19755. * This flag can be used for type testing.
  19756. *
  19757. * @type {boolean}
  19758. * @readonly
  19759. * @default true
  19760. */
  19761. this.isBatchedMesh = true;
  19762. /**
  19763. * When set ot `true`, the individual objects of a batch are frustum culled.
  19764. *
  19765. * @type {boolean}
  19766. * @default true
  19767. */
  19768. this.perObjectFrustumCulled = true;
  19769. /**
  19770. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  19771. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  19772. * rendered front to back.
  19773. *
  19774. * @type {boolean}
  19775. * @default true
  19776. */
  19777. this.sortObjects = true;
  19778. /**
  19779. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  19780. *
  19781. * @type {?Box3}
  19782. * @default null
  19783. */
  19784. this.boundingBox = null;
  19785. /**
  19786. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  19787. *
  19788. * @type {?Sphere}
  19789. * @default null
  19790. */
  19791. this.boundingSphere = null;
  19792. /**
  19793. * Takes a sort a function that is run before render. The function takes a list of instances to
  19794. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  19795. * sort with.
  19796. *
  19797. * @type {?Function}
  19798. * @default null
  19799. */
  19800. this.customSort = null;
  19801. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  19802. this._instanceInfo = [];
  19803. this._geometryInfo = [];
  19804. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  19805. this._availableInstanceIds = [];
  19806. this._availableGeometryIds = [];
  19807. // used to track where the next point is that geometry should be inserted
  19808. this._nextIndexStart = 0;
  19809. this._nextVertexStart = 0;
  19810. this._geometryCount = 0;
  19811. // flags
  19812. this._visibilityChanged = true;
  19813. this._geometryInitialized = false;
  19814. // cached user options
  19815. this._maxInstanceCount = maxInstanceCount;
  19816. this._maxVertexCount = maxVertexCount;
  19817. this._maxIndexCount = maxIndexCount;
  19818. // buffers for multi draw
  19819. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  19820. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  19821. this._multiDrawCount = 0;
  19822. this._multiDrawInstances = null;
  19823. // Local matrix per geometry by using data texture
  19824. this._matricesTexture = null;
  19825. this._indirectTexture = null;
  19826. this._colorsTexture = null;
  19827. this._initMatricesTexture();
  19828. this._initIndirectTexture();
  19829. }
  19830. /**
  19831. * The maximum number of individual instances that can be stored in the batch.
  19832. *
  19833. * @type {number}
  19834. * @readonly
  19835. */
  19836. get maxInstanceCount() {
  19837. return this._maxInstanceCount;
  19838. }
  19839. /**
  19840. * The instance count.
  19841. *
  19842. * @type {number}
  19843. * @readonly
  19844. */
  19845. get instanceCount() {
  19846. return this._instanceInfo.length - this._availableInstanceIds.length;
  19847. }
  19848. /**
  19849. * The number of unused vertices.
  19850. *
  19851. * @type {number}
  19852. * @readonly
  19853. */
  19854. get unusedVertexCount() {
  19855. return this._maxVertexCount - this._nextVertexStart;
  19856. }
  19857. /**
  19858. * The number of unused indices.
  19859. *
  19860. * @type {number}
  19861. * @readonly
  19862. */
  19863. get unusedIndexCount() {
  19864. return this._maxIndexCount - this._nextIndexStart;
  19865. }
  19866. _initMatricesTexture() {
  19867. // layout (1 matrix = 4 pixels)
  19868. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19869. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  19870. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  19871. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  19872. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  19873. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  19874. size = Math.ceil( size / 4 ) * 4;
  19875. size = Math.max( size, 4 );
  19876. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19877. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  19878. this._matricesTexture = matricesTexture;
  19879. }
  19880. _initIndirectTexture() {
  19881. let size = Math.sqrt( this._maxInstanceCount );
  19882. size = Math.ceil( size );
  19883. const indirectArray = new Uint32Array( size * size );
  19884. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  19885. this._indirectTexture = indirectTexture;
  19886. }
  19887. _initColorsTexture() {
  19888. let size = Math.sqrt( this._maxInstanceCount );
  19889. size = Math.ceil( size );
  19890. // 4 floats per RGBA pixel initialized to white
  19891. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  19892. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  19893. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  19894. this._colorsTexture = colorsTexture;
  19895. }
  19896. _initializeGeometry( reference ) {
  19897. const geometry = this.geometry;
  19898. const maxVertexCount = this._maxVertexCount;
  19899. const maxIndexCount = this._maxIndexCount;
  19900. if ( this._geometryInitialized === false ) {
  19901. for ( const attributeName in reference.attributes ) {
  19902. const srcAttribute = reference.getAttribute( attributeName );
  19903. const { array, itemSize, normalized } = srcAttribute;
  19904. const dstArray = new array.constructor( maxVertexCount * itemSize );
  19905. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  19906. geometry.setAttribute( attributeName, dstAttribute );
  19907. }
  19908. if ( reference.getIndex() !== null ) {
  19909. // Reserve last u16 index for primitive restart.
  19910. const indexArray = maxVertexCount > 65535
  19911. ? new Uint32Array( maxIndexCount )
  19912. : new Uint16Array( maxIndexCount );
  19913. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  19914. }
  19915. this._geometryInitialized = true;
  19916. }
  19917. }
  19918. // Make sure the geometry is compatible with the existing combined geometry attributes
  19919. _validateGeometry( geometry ) {
  19920. // check to ensure the geometries are using consistent attributes and indices
  19921. const batchGeometry = this.geometry;
  19922. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  19923. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  19924. }
  19925. for ( const attributeName in batchGeometry.attributes ) {
  19926. if ( ! geometry.hasAttribute( attributeName ) ) {
  19927. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  19928. }
  19929. const srcAttribute = geometry.getAttribute( attributeName );
  19930. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19931. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  19932. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  19933. }
  19934. }
  19935. }
  19936. /**
  19937. * Validates the instance defined by the given ID.
  19938. *
  19939. * @param {number} instanceId - The instance to validate.
  19940. */
  19941. validateInstanceId( instanceId ) {
  19942. const instanceInfo = this._instanceInfo;
  19943. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  19944. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  19945. }
  19946. }
  19947. /**
  19948. * Validates the geometry defined by the given ID.
  19949. *
  19950. * @param {number} geometryId - The geometry to validate.
  19951. */
  19952. validateGeometryId( geometryId ) {
  19953. const geometryInfoList = this._geometryInfo;
  19954. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  19955. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  19956. }
  19957. }
  19958. /**
  19959. * Takes a sort a function that is run before render. The function takes a list of instances to
  19960. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  19961. *
  19962. * @param {Function} func - The custom sort function.
  19963. * @return {BatchedMesh} A reference to this batched mesh.
  19964. */
  19965. setCustomSort( func ) {
  19966. this.customSort = func;
  19967. return this;
  19968. }
  19969. /**
  19970. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  19971. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  19972. * otherwise they are `null`.
  19973. */
  19974. computeBoundingBox() {
  19975. if ( this.boundingBox === null ) {
  19976. this.boundingBox = new Box3();
  19977. }
  19978. const boundingBox = this.boundingBox;
  19979. const instanceInfo = this._instanceInfo;
  19980. boundingBox.makeEmpty();
  19981. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19982. if ( instanceInfo[ i ].active === false ) continue;
  19983. const geometryId = instanceInfo[ i ].geometryIndex;
  19984. this.getMatrixAt( i, _matrix$1 );
  19985. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  19986. boundingBox.union( _box$1 );
  19987. }
  19988. }
  19989. /**
  19990. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  19991. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  19992. * otherwise they are `null`.
  19993. */
  19994. computeBoundingSphere() {
  19995. if ( this.boundingSphere === null ) {
  19996. this.boundingSphere = new Sphere();
  19997. }
  19998. const boundingSphere = this.boundingSphere;
  19999. const instanceInfo = this._instanceInfo;
  20000. boundingSphere.makeEmpty();
  20001. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20002. if ( instanceInfo[ i ].active === false ) continue;
  20003. const geometryId = instanceInfo[ i ].geometryIndex;
  20004. this.getMatrixAt( i, _matrix$1 );
  20005. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20006. boundingSphere.union( _sphere$2 );
  20007. }
  20008. }
  20009. /**
  20010. * Adds a new instance to the batch using the geometry of the given ID and returns
  20011. * a new id referring to the new instance to be used by other functions.
  20012. *
  20013. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  20014. * @return {number} The instance ID.
  20015. */
  20016. addInstance( geometryId ) {
  20017. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  20018. // ensure we're not over geometry
  20019. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  20020. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  20021. }
  20022. const instanceInfo = {
  20023. visible: true,
  20024. active: true,
  20025. geometryIndex: geometryId,
  20026. };
  20027. let drawId = null;
  20028. // Prioritize using previously freed instance ids
  20029. if ( this._availableInstanceIds.length > 0 ) {
  20030. this._availableInstanceIds.sort( ascIdSort );
  20031. drawId = this._availableInstanceIds.shift();
  20032. this._instanceInfo[ drawId ] = instanceInfo;
  20033. } else {
  20034. drawId = this._instanceInfo.length;
  20035. this._instanceInfo.push( instanceInfo );
  20036. }
  20037. const matricesTexture = this._matricesTexture;
  20038. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  20039. matricesTexture.needsUpdate = true;
  20040. const colorsTexture = this._colorsTexture;
  20041. if ( colorsTexture ) {
  20042. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  20043. colorsTexture.needsUpdate = true;
  20044. }
  20045. this._visibilityChanged = true;
  20046. return drawId;
  20047. }
  20048. /**
  20049. * Adds the given geometry to the batch and returns the associated
  20050. * geometry id referring to it to be used in other functions.
  20051. *
  20052. * @param {BufferGeometry} geometry - The geometry to add.
  20053. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  20054. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  20055. * to set a new geometry at this index at a later time that is larger than the original geometry.
  20056. * Defaults to the length of the given geometry vertex buffer.
  20057. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  20058. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  20059. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  20060. * the length of the given geometry index buffer.
  20061. * @return {number} The geometry ID.
  20062. */
  20063. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  20064. this._initializeGeometry( geometry );
  20065. this._validateGeometry( geometry );
  20066. const geometryInfo = {
  20067. // geometry information
  20068. vertexStart: -1,
  20069. vertexCount: -1,
  20070. reservedVertexCount: -1,
  20071. indexStart: -1,
  20072. indexCount: -1,
  20073. reservedIndexCount: -1,
  20074. // draw range information
  20075. start: -1,
  20076. count: -1,
  20077. // state
  20078. boundingBox: null,
  20079. boundingSphere: null,
  20080. active: true,
  20081. };
  20082. const geometryInfoList = this._geometryInfo;
  20083. geometryInfo.vertexStart = this._nextVertexStart;
  20084. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  20085. const index = geometry.getIndex();
  20086. const hasIndex = index !== null;
  20087. if ( hasIndex ) {
  20088. geometryInfo.indexStart = this._nextIndexStart;
  20089. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  20090. }
  20091. if (
  20092. geometryInfo.indexStart !== -1 &&
  20093. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  20094. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  20095. ) {
  20096. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  20097. }
  20098. // update id
  20099. let geometryId;
  20100. if ( this._availableGeometryIds.length > 0 ) {
  20101. this._availableGeometryIds.sort( ascIdSort );
  20102. geometryId = this._availableGeometryIds.shift();
  20103. geometryInfoList[ geometryId ] = geometryInfo;
  20104. } else {
  20105. geometryId = this._geometryCount;
  20106. this._geometryCount ++;
  20107. geometryInfoList.push( geometryInfo );
  20108. }
  20109. // update the geometry
  20110. this.setGeometryAt( geometryId, geometry );
  20111. // increment the next geometry position
  20112. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  20113. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20114. return geometryId;
  20115. }
  20116. /**
  20117. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  20118. * is not enough space reserved for geometry. Calling this will change all instances that are
  20119. * rendering that geometry.
  20120. *
  20121. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  20122. * @param {BufferGeometry} geometry - The new geometry.
  20123. * @return {number} The geometry ID.
  20124. */
  20125. setGeometryAt( geometryId, geometry ) {
  20126. if ( geometryId >= this._geometryCount ) {
  20127. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  20128. }
  20129. this._validateGeometry( geometry );
  20130. const batchGeometry = this.geometry;
  20131. const hasIndex = batchGeometry.getIndex() !== null;
  20132. const dstIndex = batchGeometry.getIndex();
  20133. const srcIndex = geometry.getIndex();
  20134. const geometryInfo = this._geometryInfo[ geometryId ];
  20135. if (
  20136. hasIndex &&
  20137. srcIndex.count > geometryInfo.reservedIndexCount ||
  20138. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  20139. ) {
  20140. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  20141. }
  20142. // copy geometry buffer data over
  20143. const vertexStart = geometryInfo.vertexStart;
  20144. const reservedVertexCount = geometryInfo.reservedVertexCount;
  20145. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  20146. for ( const attributeName in batchGeometry.attributes ) {
  20147. // copy attribute data
  20148. const srcAttribute = geometry.getAttribute( attributeName );
  20149. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20150. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  20151. // fill the rest in with zeroes
  20152. const itemSize = srcAttribute.itemSize;
  20153. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  20154. const index = vertexStart + i;
  20155. for ( let c = 0; c < itemSize; c ++ ) {
  20156. dstAttribute.setComponent( index, c, 0 );
  20157. }
  20158. }
  20159. dstAttribute.needsUpdate = true;
  20160. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  20161. }
  20162. // copy index
  20163. if ( hasIndex ) {
  20164. const indexStart = geometryInfo.indexStart;
  20165. const reservedIndexCount = geometryInfo.reservedIndexCount;
  20166. geometryInfo.indexCount = geometry.getIndex().count;
  20167. // copy index data over
  20168. for ( let i = 0; i < srcIndex.count; i ++ ) {
  20169. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  20170. }
  20171. // fill the rest in with zeroes
  20172. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  20173. dstIndex.setX( indexStart + i, vertexStart );
  20174. }
  20175. dstIndex.needsUpdate = true;
  20176. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  20177. }
  20178. // update the draw range
  20179. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20180. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  20181. // store the bounding boxes
  20182. geometryInfo.boundingBox = null;
  20183. if ( geometry.boundingBox !== null ) {
  20184. geometryInfo.boundingBox = geometry.boundingBox.clone();
  20185. }
  20186. geometryInfo.boundingSphere = null;
  20187. if ( geometry.boundingSphere !== null ) {
  20188. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  20189. }
  20190. this._visibilityChanged = true;
  20191. return geometryId;
  20192. }
  20193. /**
  20194. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  20195. * this geometry will also be removed as a side effect.
  20196. *
  20197. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  20198. * @return {BatchedMesh} A reference to this batched mesh.
  20199. */
  20200. deleteGeometry( geometryId ) {
  20201. const geometryInfoList = this._geometryInfo;
  20202. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20203. return this;
  20204. }
  20205. // delete any instances associated with this geometry
  20206. const instanceInfo = this._instanceInfo;
  20207. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20208. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  20209. this.deleteInstance( i );
  20210. }
  20211. }
  20212. geometryInfoList[ geometryId ].active = false;
  20213. this._availableGeometryIds.push( geometryId );
  20214. this._visibilityChanged = true;
  20215. return this;
  20216. }
  20217. /**
  20218. * Deletes an existing instance from the batch using the given ID.
  20219. *
  20220. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20221. * @return {BatchedMesh} A reference to this batched mesh.
  20222. */
  20223. deleteInstance( instanceId ) {
  20224. this.validateInstanceId( instanceId );
  20225. this._instanceInfo[ instanceId ].active = false;
  20226. this._availableInstanceIds.push( instanceId );
  20227. this._visibilityChanged = true;
  20228. return this;
  20229. }
  20230. /**
  20231. * Repacks the sub geometries in [name] to remove any unused space remaining from
  20232. * previously deleted geometry, freeing up space to add new geometry.
  20233. *
  20234. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20235. * @return {BatchedMesh} A reference to this batched mesh.
  20236. */
  20237. optimize() {
  20238. // track the next indices to copy data to
  20239. let nextVertexStart = 0;
  20240. let nextIndexStart = 0;
  20241. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  20242. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  20243. const geometryInfoList = this._geometryInfo;
  20244. const indices = geometryInfoList
  20245. .map( ( e, i ) => i )
  20246. .sort( ( a, b ) => {
  20247. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  20248. } );
  20249. const geometry = this.geometry;
  20250. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  20251. // if a geometry range is inactive then don't copy anything
  20252. const index = indices[ i ];
  20253. const geometryInfo = geometryInfoList[ index ];
  20254. if ( geometryInfo.active === false ) {
  20255. continue;
  20256. }
  20257. // if a geometry contains an index buffer then shift it, as well
  20258. if ( geometry.index !== null ) {
  20259. if ( geometryInfo.indexStart !== nextIndexStart ) {
  20260. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  20261. const index = geometry.index;
  20262. const array = index.array;
  20263. // shift the index pointers based on how the vertex data will shift
  20264. // adjusting the index must happen first so the original vertex start value is available
  20265. const elementDelta = nextVertexStart - vertexStart;
  20266. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  20267. array[ j ] = array[ j ] + elementDelta;
  20268. }
  20269. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  20270. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  20271. geometryInfo.indexStart = nextIndexStart;
  20272. }
  20273. nextIndexStart += geometryInfo.reservedIndexCount;
  20274. }
  20275. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  20276. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  20277. const { vertexStart, reservedVertexCount } = geometryInfo;
  20278. const attributes = geometry.attributes;
  20279. for ( const key in attributes ) {
  20280. const attribute = attributes[ key ];
  20281. const { array, itemSize } = attribute;
  20282. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  20283. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  20284. }
  20285. geometryInfo.vertexStart = nextVertexStart;
  20286. }
  20287. nextVertexStart += geometryInfo.reservedVertexCount;
  20288. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20289. // step the next geometry points to the shifted position
  20290. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  20291. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20292. }
  20293. return this;
  20294. }
  20295. /**
  20296. * Returns the bounding box for the given geometry.
  20297. *
  20298. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  20299. * @param {Box3} target - The target object that is used to store the method's result.
  20300. * @return {Box3|null} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  20301. */
  20302. getBoundingBoxAt( geometryId, target ) {
  20303. if ( geometryId >= this._geometryCount ) {
  20304. return null;
  20305. }
  20306. // compute bounding box
  20307. const geometry = this.geometry;
  20308. const geometryInfo = this._geometryInfo[ geometryId ];
  20309. if ( geometryInfo.boundingBox === null ) {
  20310. const box = new Box3();
  20311. const index = geometry.index;
  20312. const position = geometry.attributes.position;
  20313. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20314. let iv = i;
  20315. if ( index ) {
  20316. iv = index.getX( iv );
  20317. }
  20318. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  20319. }
  20320. geometryInfo.boundingBox = box;
  20321. }
  20322. target.copy( geometryInfo.boundingBox );
  20323. return target;
  20324. }
  20325. /**
  20326. * Returns the bounding sphere for the given geometry.
  20327. *
  20328. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  20329. * @param {Sphere} target - The target object that is used to store the method's result.
  20330. * @return {Sphere|null} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  20331. */
  20332. getBoundingSphereAt( geometryId, target ) {
  20333. if ( geometryId >= this._geometryCount ) {
  20334. return null;
  20335. }
  20336. // compute bounding sphere
  20337. const geometry = this.geometry;
  20338. const geometryInfo = this._geometryInfo[ geometryId ];
  20339. if ( geometryInfo.boundingSphere === null ) {
  20340. const sphere = new Sphere();
  20341. this.getBoundingBoxAt( geometryId, _box$1 );
  20342. _box$1.getCenter( sphere.center );
  20343. const index = geometry.index;
  20344. const position = geometry.attributes.position;
  20345. let maxRadiusSq = 0;
  20346. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20347. let iv = i;
  20348. if ( index ) {
  20349. iv = index.getX( iv );
  20350. }
  20351. _vector$5.fromBufferAttribute( position, iv );
  20352. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20353. }
  20354. sphere.radius = Math.sqrt( maxRadiusSq );
  20355. geometryInfo.boundingSphere = sphere;
  20356. }
  20357. target.copy( geometryInfo.boundingSphere );
  20358. return target;
  20359. }
  20360. /**
  20361. * Sets the given local transformation matrix to the defined instance.
  20362. * Negatively scaled matrices are not supported.
  20363. *
  20364. * @param {number} instanceId - The ID of an instance to set the matrix of.
  20365. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  20366. * @return {BatchedMesh} A reference to this batched mesh.
  20367. */
  20368. setMatrixAt( instanceId, matrix ) {
  20369. this.validateInstanceId( instanceId );
  20370. const matricesTexture = this._matricesTexture;
  20371. const matricesArray = this._matricesTexture.image.data;
  20372. matrix.toArray( matricesArray, instanceId * 16 );
  20373. matricesTexture.needsUpdate = true;
  20374. return this;
  20375. }
  20376. /**
  20377. * Returns the local transformation matrix of the defined instance.
  20378. *
  20379. * @param {number} instanceId - The ID of an instance to get the matrix of.
  20380. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  20381. * @return {Matrix4} The instance's local transformation matrix.
  20382. */
  20383. getMatrixAt( instanceId, matrix ) {
  20384. this.validateInstanceId( instanceId );
  20385. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  20386. }
  20387. /**
  20388. * Sets the given color to the defined instance.
  20389. *
  20390. * @param {number} instanceId - The ID of an instance to set the color of.
  20391. * @param {Color} color - The color to set the instance to.
  20392. * @return {BatchedMesh} A reference to this batched mesh.
  20393. */
  20394. setColorAt( instanceId, color ) {
  20395. this.validateInstanceId( instanceId );
  20396. if ( this._colorsTexture === null ) {
  20397. this._initColorsTexture();
  20398. }
  20399. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  20400. this._colorsTexture.needsUpdate = true;
  20401. return this;
  20402. }
  20403. /**
  20404. * Returns the color of the defined instance.
  20405. *
  20406. * @param {number} instanceId - The ID of an instance to get the color of.
  20407. * @param {Color} color - The target object that is used to store the method's result.
  20408. * @return {Color} The instance's color.
  20409. */
  20410. getColorAt( instanceId, color ) {
  20411. this.validateInstanceId( instanceId );
  20412. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  20413. }
  20414. /**
  20415. * Sets the visibility of the instance.
  20416. *
  20417. * @param {number} instanceId - The id of the instance to set the visibility of.
  20418. * @param {boolean} visible - Whether the instance is visible or not.
  20419. * @return {BatchedMesh} A reference to this batched mesh.
  20420. */
  20421. setVisibleAt( instanceId, visible ) {
  20422. this.validateInstanceId( instanceId );
  20423. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  20424. return this;
  20425. }
  20426. this._instanceInfo[ instanceId ].visible = visible;
  20427. this._visibilityChanged = true;
  20428. return this;
  20429. }
  20430. /**
  20431. * Returns the visibility state of the defined instance.
  20432. *
  20433. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  20434. * @return {boolean} Whether the instance is visible or not.
  20435. */
  20436. getVisibleAt( instanceId ) {
  20437. this.validateInstanceId( instanceId );
  20438. return this._instanceInfo[ instanceId ].visible;
  20439. }
  20440. /**
  20441. * Sets the geometry ID of the instance at the given index.
  20442. *
  20443. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  20444. * @param {number} geometryId - The geometry ID to be use by the instance.
  20445. * @return {BatchedMesh} A reference to this batched mesh.
  20446. */
  20447. setGeometryIdAt( instanceId, geometryId ) {
  20448. this.validateInstanceId( instanceId );
  20449. this.validateGeometryId( geometryId );
  20450. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  20451. return this;
  20452. }
  20453. /**
  20454. * Returns the geometry ID of the defined instance.
  20455. *
  20456. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  20457. * @return {number} The instance's geometry ID.
  20458. */
  20459. getGeometryIdAt( instanceId ) {
  20460. this.validateInstanceId( instanceId );
  20461. return this._instanceInfo[ instanceId ].geometryIndex;
  20462. }
  20463. /**
  20464. * Get the range representing the subset of triangles related to the attached geometry,
  20465. * indicating the starting offset and count, or `null` if invalid.
  20466. *
  20467. * @param {number} geometryId - The id of the geometry to get the range of.
  20468. * @param {Object} [target] - The target object that is used to store the method's result.
  20469. * @return {{
  20470. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  20471. * indexStart:number,indexCount:number,reservedIndexCount:number,
  20472. * start:number,count:number
  20473. * }} The result object with range data.
  20474. */
  20475. getGeometryRangeAt( geometryId, target = {} ) {
  20476. this.validateGeometryId( geometryId );
  20477. const geometryInfo = this._geometryInfo[ geometryId ];
  20478. target.vertexStart = geometryInfo.vertexStart;
  20479. target.vertexCount = geometryInfo.vertexCount;
  20480. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  20481. target.indexStart = geometryInfo.indexStart;
  20482. target.indexCount = geometryInfo.indexCount;
  20483. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  20484. target.start = geometryInfo.start;
  20485. target.count = geometryInfo.count;
  20486. return target;
  20487. }
  20488. /**
  20489. * Resizes the necessary buffers to support the provided number of instances.
  20490. * If the provided arguments shrink the number of instances but there are not enough
  20491. * unused Ids at the end of the list then an error is thrown.
  20492. *
  20493. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  20494. */
  20495. setInstanceCount( maxInstanceCount ) {
  20496. // shrink the available instances as much as possible
  20497. const availableInstanceIds = this._availableInstanceIds;
  20498. const instanceInfo = this._instanceInfo;
  20499. availableInstanceIds.sort( ascIdSort );
  20500. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length ) {
  20501. instanceInfo.pop();
  20502. availableInstanceIds.pop();
  20503. }
  20504. // throw an error if it can't be shrunk to the desired size
  20505. if ( maxInstanceCount < instanceInfo.length ) {
  20506. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  20507. }
  20508. // copy the multi draw counts
  20509. const multiDrawCounts = new Int32Array( maxInstanceCount );
  20510. const multiDrawStarts = new Int32Array( maxInstanceCount );
  20511. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  20512. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  20513. this._multiDrawCounts = multiDrawCounts;
  20514. this._multiDrawStarts = multiDrawStarts;
  20515. this._maxInstanceCount = maxInstanceCount;
  20516. // update texture data for instance sampling
  20517. const indirectTexture = this._indirectTexture;
  20518. const matricesTexture = this._matricesTexture;
  20519. const colorsTexture = this._colorsTexture;
  20520. indirectTexture.dispose();
  20521. this._initIndirectTexture();
  20522. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  20523. matricesTexture.dispose();
  20524. this._initMatricesTexture();
  20525. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  20526. if ( colorsTexture ) {
  20527. colorsTexture.dispose();
  20528. this._initColorsTexture();
  20529. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  20530. }
  20531. }
  20532. /**
  20533. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  20534. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  20535. * end of the geometry attributes then an error is thrown.
  20536. *
  20537. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  20538. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  20539. */
  20540. setGeometrySize( maxVertexCount, maxIndexCount ) {
  20541. // Check if we can shrink to the requested vertex attribute size
  20542. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  20543. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  20544. if ( requiredVertexLength > maxVertexCount ) {
  20545. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20546. }
  20547. // Check if we can shrink to the requested index attribute size
  20548. if ( this.geometry.index ) {
  20549. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  20550. if ( requiredIndexLength > maxIndexCount ) {
  20551. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20552. }
  20553. }
  20554. //
  20555. // dispose of the previous geometry
  20556. const oldGeometry = this.geometry;
  20557. oldGeometry.dispose();
  20558. // recreate the geometry needed based on the previous variant
  20559. this._maxVertexCount = maxVertexCount;
  20560. this._maxIndexCount = maxIndexCount;
  20561. if ( this._geometryInitialized ) {
  20562. this._geometryInitialized = false;
  20563. this.geometry = new BufferGeometry();
  20564. this._initializeGeometry( oldGeometry );
  20565. }
  20566. // copy data from the previous geometry
  20567. const geometry = this.geometry;
  20568. if ( oldGeometry.index ) {
  20569. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  20570. }
  20571. for ( const key in oldGeometry.attributes ) {
  20572. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  20573. }
  20574. }
  20575. raycast( raycaster, intersects ) {
  20576. const instanceInfo = this._instanceInfo;
  20577. const geometryInfoList = this._geometryInfo;
  20578. const matrixWorld = this.matrixWorld;
  20579. const batchGeometry = this.geometry;
  20580. // iterate over each geometry
  20581. _mesh.material = this.material;
  20582. _mesh.geometry.index = batchGeometry.index;
  20583. _mesh.geometry.attributes = batchGeometry.attributes;
  20584. if ( _mesh.geometry.boundingBox === null ) {
  20585. _mesh.geometry.boundingBox = new Box3();
  20586. }
  20587. if ( _mesh.geometry.boundingSphere === null ) {
  20588. _mesh.geometry.boundingSphere = new Sphere();
  20589. }
  20590. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20591. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  20592. continue;
  20593. }
  20594. const geometryId = instanceInfo[ i ].geometryIndex;
  20595. const geometryInfo = geometryInfoList[ geometryId ];
  20596. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  20597. // get the intersects
  20598. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  20599. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  20600. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  20601. _mesh.raycast( raycaster, _batchIntersects );
  20602. // add batch id to the intersects
  20603. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  20604. const intersect = _batchIntersects[ j ];
  20605. intersect.object = this;
  20606. intersect.batchId = i;
  20607. intersects.push( intersect );
  20608. }
  20609. _batchIntersects.length = 0;
  20610. }
  20611. _mesh.material = null;
  20612. _mesh.geometry.index = null;
  20613. _mesh.geometry.attributes = {};
  20614. _mesh.geometry.setDrawRange( 0, Infinity );
  20615. }
  20616. copy( source ) {
  20617. super.copy( source );
  20618. this.geometry = source.geometry.clone();
  20619. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  20620. this.sortObjects = source.sortObjects;
  20621. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  20622. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  20623. this._geometryInfo = source._geometryInfo.map( info => ( {
  20624. ...info,
  20625. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  20626. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  20627. } ) );
  20628. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  20629. this._availableInstanceIds = source._availableInstanceIds.slice();
  20630. this._availableGeometryIds = source._availableGeometryIds.slice();
  20631. this._nextIndexStart = source._nextIndexStart;
  20632. this._nextVertexStart = source._nextVertexStart;
  20633. this._geometryCount = source._geometryCount;
  20634. this._maxInstanceCount = source._maxInstanceCount;
  20635. this._maxVertexCount = source._maxVertexCount;
  20636. this._maxIndexCount = source._maxIndexCount;
  20637. this._geometryInitialized = source._geometryInitialized;
  20638. this._multiDrawCounts = source._multiDrawCounts.slice();
  20639. this._multiDrawStarts = source._multiDrawStarts.slice();
  20640. this._indirectTexture = source._indirectTexture.clone();
  20641. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  20642. this._matricesTexture = source._matricesTexture.clone();
  20643. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  20644. if ( this._colorsTexture !== null ) {
  20645. this._colorsTexture = source._colorsTexture.clone();
  20646. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  20647. }
  20648. return this;
  20649. }
  20650. /**
  20651. * Frees the GPU-related resources allocated by this instance. Call this
  20652. * method whenever this instance is no longer used in your app.
  20653. */
  20654. dispose() {
  20655. // Assuming the geometry is not shared with other meshes
  20656. this.geometry.dispose();
  20657. this._matricesTexture.dispose();
  20658. this._matricesTexture = null;
  20659. this._indirectTexture.dispose();
  20660. this._indirectTexture = null;
  20661. if ( this._colorsTexture !== null ) {
  20662. this._colorsTexture.dispose();
  20663. this._colorsTexture = null;
  20664. }
  20665. }
  20666. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  20667. // if visibility has not changed and frustum culling and object sorting is not required
  20668. // then skip iterating over all items
  20669. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  20670. return;
  20671. }
  20672. // the indexed version of the multi draw function requires specifying the start
  20673. // offset in bytes.
  20674. const index = geometry.getIndex();
  20675. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  20676. const instanceInfo = this._instanceInfo;
  20677. const multiDrawStarts = this._multiDrawStarts;
  20678. const multiDrawCounts = this._multiDrawCounts;
  20679. const geometryInfoList = this._geometryInfo;
  20680. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  20681. const indirectTexture = this._indirectTexture;
  20682. const indirectArray = indirectTexture.image.data;
  20683. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  20684. // prepare the frustum in the local frame
  20685. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  20686. _matrix$1
  20687. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  20688. .multiply( this.matrixWorld );
  20689. _frustum.setFromProjectionMatrix(
  20690. _matrix$1,
  20691. renderer.coordinateSystem
  20692. );
  20693. }
  20694. let multiDrawCount = 0;
  20695. if ( this.sortObjects ) {
  20696. // get the camera position in the local frame
  20697. _matrix$1.copy( this.matrixWorld ).invert();
  20698. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  20699. _forward.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  20700. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20701. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20702. const geometryId = instanceInfo[ i ].geometryIndex;
  20703. // get the bounds in world space
  20704. this.getMatrixAt( i, _matrix$1 );
  20705. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20706. // determine whether the batched geometry is within the frustum
  20707. let culled = false;
  20708. if ( perObjectFrustumCulled ) {
  20709. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20710. }
  20711. if ( ! culled ) {
  20712. // get the distance from camera used for sorting
  20713. const geometryInfo = geometryInfoList[ geometryId ];
  20714. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  20715. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  20716. }
  20717. }
  20718. }
  20719. // Sort the draw ranges and prep for rendering
  20720. const list = _renderList.list;
  20721. const customSort = this.customSort;
  20722. if ( customSort === null ) {
  20723. list.sort( material.transparent ? sortTransparent : sortOpaque );
  20724. } else {
  20725. customSort.call( this, list, camera );
  20726. }
  20727. for ( let i = 0, l = list.length; i < l; i ++ ) {
  20728. const item = list[ i ];
  20729. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  20730. multiDrawCounts[ multiDrawCount ] = item.count;
  20731. indirectArray[ multiDrawCount ] = item.index;
  20732. multiDrawCount ++;
  20733. }
  20734. _renderList.reset();
  20735. } else {
  20736. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20737. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20738. const geometryId = instanceInfo[ i ].geometryIndex;
  20739. // determine whether the batched geometry is within the frustum
  20740. let culled = false;
  20741. if ( perObjectFrustumCulled ) {
  20742. // get the bounds in world space
  20743. this.getMatrixAt( i, _matrix$1 );
  20744. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20745. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20746. }
  20747. if ( ! culled ) {
  20748. const geometryInfo = geometryInfoList[ geometryId ];
  20749. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  20750. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  20751. indirectArray[ multiDrawCount ] = i;
  20752. multiDrawCount ++;
  20753. }
  20754. }
  20755. }
  20756. }
  20757. indirectTexture.needsUpdate = true;
  20758. this._multiDrawCount = multiDrawCount;
  20759. this._visibilityChanged = false;
  20760. }
  20761. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  20762. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  20763. }
  20764. }
  20765. /**
  20766. * A material for rendering line primitives.
  20767. *
  20768. * Materials define the appearance of renderable 3D objects.
  20769. *
  20770. * ```js
  20771. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  20772. * ```
  20773. *
  20774. * @augments Material
  20775. */
  20776. class LineBasicMaterial extends Material {
  20777. /**
  20778. * Constructs a new line basic material.
  20779. *
  20780. * @param {Object} [parameters] - An object with one or more properties
  20781. * defining the material's appearance. Any property of the material
  20782. * (including any property from inherited materials) can be passed
  20783. * in here. Color values can be passed any type of value accepted
  20784. * by {@link Color#set}.
  20785. */
  20786. constructor( parameters ) {
  20787. super();
  20788. /**
  20789. * This flag can be used for type testing.
  20790. *
  20791. * @type {boolean}
  20792. * @readonly
  20793. * @default true
  20794. */
  20795. this.isLineBasicMaterial = true;
  20796. this.type = 'LineBasicMaterial';
  20797. /**
  20798. * Color of the material.
  20799. *
  20800. * @type {Color}
  20801. * @default (1,1,1)
  20802. */
  20803. this.color = new Color( 0xffffff );
  20804. /**
  20805. * Sets the color of the lines using data from a texture. The texture map
  20806. * color is modulated by the diffuse `color`.
  20807. *
  20808. * @type {?Texture}
  20809. * @default null
  20810. */
  20811. this.map = null;
  20812. /**
  20813. * Controls line thickness or lines.
  20814. *
  20815. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  20816. * ignore this setting and always render line primitives with a
  20817. * width of one pixel.
  20818. *
  20819. * @type {number}
  20820. * @default 1
  20821. */
  20822. this.linewidth = 1;
  20823. /**
  20824. * Defines appearance of line ends.
  20825. *
  20826. * Can only be used with {@link SVGRenderer}.
  20827. *
  20828. * @type {('butt'|'round'|'square')}
  20829. * @default 'round'
  20830. */
  20831. this.linecap = 'round';
  20832. /**
  20833. * Defines appearance of line joints.
  20834. *
  20835. * Can only be used with {@link SVGRenderer}.
  20836. *
  20837. * @type {('round'|'bevel'|'miter')}
  20838. * @default 'round'
  20839. */
  20840. this.linejoin = 'round';
  20841. /**
  20842. * Whether the material is affected by fog or not.
  20843. *
  20844. * @type {boolean}
  20845. * @default true
  20846. */
  20847. this.fog = true;
  20848. this.setValues( parameters );
  20849. }
  20850. copy( source ) {
  20851. super.copy( source );
  20852. this.color.copy( source.color );
  20853. this.map = source.map;
  20854. this.linewidth = source.linewidth;
  20855. this.linecap = source.linecap;
  20856. this.linejoin = source.linejoin;
  20857. this.fog = source.fog;
  20858. return this;
  20859. }
  20860. }
  20861. const _vStart = /*@__PURE__*/ new Vector3();
  20862. const _vEnd = /*@__PURE__*/ new Vector3();
  20863. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  20864. const _ray$1 = /*@__PURE__*/ new Ray();
  20865. const _sphere$1 = /*@__PURE__*/ new Sphere();
  20866. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  20867. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  20868. /**
  20869. * A continuous line. The line are rendered by connecting consecutive
  20870. * vertices with straight lines.
  20871. *
  20872. * ```js
  20873. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  20874. *
  20875. * const points = [];
  20876. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  20877. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  20878. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  20879. *
  20880. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  20881. *
  20882. * const line = new THREE.Line( geometry, material );
  20883. * scene.add( line );
  20884. * ```
  20885. *
  20886. * @augments Object3D
  20887. */
  20888. class Line extends Object3D {
  20889. /**
  20890. * Constructs a new line.
  20891. *
  20892. * @param {BufferGeometry} [geometry] - The line geometry.
  20893. * @param {Material|Array<Material>} [material] - The line material.
  20894. */
  20895. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  20896. super();
  20897. /**
  20898. * This flag can be used for type testing.
  20899. *
  20900. * @type {boolean}
  20901. * @readonly
  20902. * @default true
  20903. */
  20904. this.isLine = true;
  20905. this.type = 'Line';
  20906. /**
  20907. * The line geometry.
  20908. *
  20909. * @type {BufferGeometry}
  20910. */
  20911. this.geometry = geometry;
  20912. /**
  20913. * The line material.
  20914. *
  20915. * @type {Material|Array<Material>}
  20916. * @default LineBasicMaterial
  20917. */
  20918. this.material = material;
  20919. /**
  20920. * A dictionary representing the morph targets in the geometry. The key is the
  20921. * morph targets name, the value its attribute index. This member is `undefined`
  20922. * by default and only set when morph targets are detected in the geometry.
  20923. *
  20924. * @type {Object<String,number>|undefined}
  20925. * @default undefined
  20926. */
  20927. this.morphTargetDictionary = undefined;
  20928. /**
  20929. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  20930. * is applied. This member is `undefined` by default and only set when morph targets are
  20931. * detected in the geometry.
  20932. *
  20933. * @type {Array<number>|undefined}
  20934. * @default undefined
  20935. */
  20936. this.morphTargetInfluences = undefined;
  20937. this.updateMorphTargets();
  20938. }
  20939. copy( source, recursive ) {
  20940. super.copy( source, recursive );
  20941. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20942. this.geometry = source.geometry;
  20943. return this;
  20944. }
  20945. /**
  20946. * Computes an array of distance values which are necessary for rendering dashed lines.
  20947. * For each vertex in the geometry, the method calculates the cumulative length from the
  20948. * current point to the very beginning of the line.
  20949. *
  20950. * @return {Line} A reference to this line.
  20951. */
  20952. computeLineDistances() {
  20953. const geometry = this.geometry;
  20954. // we assume non-indexed geometry
  20955. if ( geometry.index === null ) {
  20956. const positionAttribute = geometry.attributes.position;
  20957. const lineDistances = [ 0 ];
  20958. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  20959. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  20960. _vEnd.fromBufferAttribute( positionAttribute, i );
  20961. lineDistances[ i ] = lineDistances[ i - 1 ];
  20962. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  20963. }
  20964. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20965. } else {
  20966. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20967. }
  20968. return this;
  20969. }
  20970. /**
  20971. * Computes intersection points between a casted ray and this line.
  20972. *
  20973. * @param {Raycaster} raycaster - The raycaster.
  20974. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  20975. */
  20976. raycast( raycaster, intersects ) {
  20977. const geometry = this.geometry;
  20978. const matrixWorld = this.matrixWorld;
  20979. const threshold = raycaster.params.Line.threshold;
  20980. const drawRange = geometry.drawRange;
  20981. // Checking boundingSphere distance to ray
  20982. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20983. _sphere$1.copy( geometry.boundingSphere );
  20984. _sphere$1.applyMatrix4( matrixWorld );
  20985. _sphere$1.radius += threshold;
  20986. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  20987. //
  20988. _inverseMatrix$1.copy( matrixWorld ).invert();
  20989. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  20990. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20991. const localThresholdSq = localThreshold * localThreshold;
  20992. const step = this.isLineSegments ? 2 : 1;
  20993. const index = geometry.index;
  20994. const attributes = geometry.attributes;
  20995. const positionAttribute = attributes.position;
  20996. if ( index !== null ) {
  20997. const start = Math.max( 0, drawRange.start );
  20998. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20999. for ( let i = start, l = end - 1; i < l; i += step ) {
  21000. const a = index.getX( i );
  21001. const b = index.getX( i + 1 );
  21002. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  21003. if ( intersect ) {
  21004. intersects.push( intersect );
  21005. }
  21006. }
  21007. if ( this.isLineLoop ) {
  21008. const a = index.getX( end - 1 );
  21009. const b = index.getX( start );
  21010. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  21011. if ( intersect ) {
  21012. intersects.push( intersect );
  21013. }
  21014. }
  21015. } else {
  21016. const start = Math.max( 0, drawRange.start );
  21017. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21018. for ( let i = start, l = end - 1; i < l; i += step ) {
  21019. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  21020. if ( intersect ) {
  21021. intersects.push( intersect );
  21022. }
  21023. }
  21024. if ( this.isLineLoop ) {
  21025. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  21026. if ( intersect ) {
  21027. intersects.push( intersect );
  21028. }
  21029. }
  21030. }
  21031. }
  21032. /**
  21033. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  21034. * to make sure existing morph targets can influence this 3D object.
  21035. */
  21036. updateMorphTargets() {
  21037. const geometry = this.geometry;
  21038. const morphAttributes = geometry.morphAttributes;
  21039. const keys = Object.keys( morphAttributes );
  21040. if ( keys.length > 0 ) {
  21041. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21042. if ( morphAttribute !== undefined ) {
  21043. this.morphTargetInfluences = [];
  21044. this.morphTargetDictionary = {};
  21045. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21046. const name = morphAttribute[ m ].name || String( m );
  21047. this.morphTargetInfluences.push( 0 );
  21048. this.morphTargetDictionary[ name ] = m;
  21049. }
  21050. }
  21051. }
  21052. }
  21053. }
  21054. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  21055. const positionAttribute = object.geometry.attributes.position;
  21056. _vStart.fromBufferAttribute( positionAttribute, a );
  21057. _vEnd.fromBufferAttribute( positionAttribute, b );
  21058. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  21059. if ( distSq > thresholdSq ) return;
  21060. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  21061. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  21062. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21063. return {
  21064. distance: distance,
  21065. // What do we want? intersection point on the ray or on the segment??
  21066. // point: raycaster.ray.at( distance ),
  21067. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  21068. index: i,
  21069. face: null,
  21070. faceIndex: null,
  21071. barycoord: null,
  21072. object: object
  21073. };
  21074. }
  21075. const _start = /*@__PURE__*/ new Vector3();
  21076. const _end = /*@__PURE__*/ new Vector3();
  21077. /**
  21078. * A series of lines drawn between pairs of vertices.
  21079. *
  21080. * @augments Line
  21081. */
  21082. class LineSegments extends Line {
  21083. /**
  21084. * Constructs a new line segments.
  21085. *
  21086. * @param {BufferGeometry} [geometry] - The line geometry.
  21087. * @param {Material|Array<Material>} [material] - The line material.
  21088. */
  21089. constructor( geometry, material ) {
  21090. super( geometry, material );
  21091. /**
  21092. * This flag can be used for type testing.
  21093. *
  21094. * @type {boolean}
  21095. * @readonly
  21096. * @default true
  21097. */
  21098. this.isLineSegments = true;
  21099. this.type = 'LineSegments';
  21100. }
  21101. computeLineDistances() {
  21102. const geometry = this.geometry;
  21103. // we assume non-indexed geometry
  21104. if ( geometry.index === null ) {
  21105. const positionAttribute = geometry.attributes.position;
  21106. const lineDistances = [];
  21107. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  21108. _start.fromBufferAttribute( positionAttribute, i );
  21109. _end.fromBufferAttribute( positionAttribute, i + 1 );
  21110. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  21111. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  21112. }
  21113. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21114. } else {
  21115. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21116. }
  21117. return this;
  21118. }
  21119. }
  21120. /**
  21121. * A continuous line. This is nearly the same as {@link Line} the only difference
  21122. * is that the last vertex is connected with the first vertex in order to close
  21123. * the line to form a loop.
  21124. *
  21125. * @augments Line
  21126. */
  21127. class LineLoop extends Line {
  21128. /**
  21129. * Constructs a new line loop.
  21130. *
  21131. * @param {BufferGeometry} [geometry] - The line geometry.
  21132. * @param {Material|Array<Material>} [material] - The line material.
  21133. */
  21134. constructor( geometry, material ) {
  21135. super( geometry, material );
  21136. /**
  21137. * This flag can be used for type testing.
  21138. *
  21139. * @type {boolean}
  21140. * @readonly
  21141. * @default true
  21142. */
  21143. this.isLineLoop = true;
  21144. this.type = 'LineLoop';
  21145. }
  21146. }
  21147. /**
  21148. * A material for rendering point primitives.
  21149. *
  21150. * Materials define the appearance of renderable 3D objects.
  21151. *
  21152. * ```js
  21153. * const vertices = [];
  21154. *
  21155. * for ( let i = 0; i < 10000; i ++ ) {
  21156. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  21157. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  21158. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  21159. *
  21160. * vertices.push( x, y, z );
  21161. * }
  21162. *
  21163. * const geometry = new THREE.BufferGeometry();
  21164. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  21165. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  21166. * const points = new THREE.Points( geometry, material );
  21167. * scene.add( points );
  21168. * ```
  21169. *
  21170. * @augments Material
  21171. */
  21172. class PointsMaterial extends Material {
  21173. /**
  21174. * Constructs a new points material.
  21175. *
  21176. * @param {Object} [parameters] - An object with one or more properties
  21177. * defining the material's appearance. Any property of the material
  21178. * (including any property from inherited materials) can be passed
  21179. * in here. Color values can be passed any type of value accepted
  21180. * by {@link Color#set}.
  21181. */
  21182. constructor( parameters ) {
  21183. super();
  21184. /**
  21185. * This flag can be used for type testing.
  21186. *
  21187. * @type {boolean}
  21188. * @readonly
  21189. * @default true
  21190. */
  21191. this.isPointsMaterial = true;
  21192. this.type = 'PointsMaterial';
  21193. /**
  21194. * Color of the material.
  21195. *
  21196. * @type {Color}
  21197. * @default (1,1,1)
  21198. */
  21199. this.color = new Color( 0xffffff );
  21200. /**
  21201. * The color map. May optionally include an alpha channel, typically combined
  21202. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  21203. * color is modulated by the diffuse `color`.
  21204. *
  21205. * @type {?Texture}
  21206. * @default null
  21207. */
  21208. this.map = null;
  21209. /**
  21210. * The alpha map is a grayscale texture that controls the opacity across the
  21211. * surface (black: fully transparent; white: fully opaque).
  21212. *
  21213. * Only the color of the texture is used, ignoring the alpha channel if one
  21214. * exists. For RGB and RGBA textures, the renderer will use the green channel
  21215. * when sampling this texture due to the extra bit of precision provided for
  21216. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  21217. * luminance/alpha textures will also still work as expected.
  21218. *
  21219. * @type {?Texture}
  21220. * @default null
  21221. */
  21222. this.alphaMap = null;
  21223. /**
  21224. * Defines the size of the points in pixels.
  21225. *
  21226. * 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}.
  21227. *
  21228. * @type {number}
  21229. * @default 1
  21230. */
  21231. this.size = 1;
  21232. /**
  21233. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  21234. *
  21235. * @type {boolean}
  21236. * @default true
  21237. */
  21238. this.sizeAttenuation = true;
  21239. /**
  21240. * Whether the material is affected by fog or not.
  21241. *
  21242. * @type {boolean}
  21243. * @default true
  21244. */
  21245. this.fog = true;
  21246. this.setValues( parameters );
  21247. }
  21248. copy( source ) {
  21249. super.copy( source );
  21250. this.color.copy( source.color );
  21251. this.map = source.map;
  21252. this.alphaMap = source.alphaMap;
  21253. this.size = source.size;
  21254. this.sizeAttenuation = source.sizeAttenuation;
  21255. this.fog = source.fog;
  21256. return this;
  21257. }
  21258. }
  21259. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  21260. const _ray = /*@__PURE__*/ new Ray();
  21261. const _sphere = /*@__PURE__*/ new Sphere();
  21262. const _position$2 = /*@__PURE__*/ new Vector3();
  21263. /**
  21264. * A class for displaying points or point clouds.
  21265. *
  21266. * @augments Object3D
  21267. */
  21268. class Points extends Object3D {
  21269. /**
  21270. * Constructs a new point cloud.
  21271. *
  21272. * @param {BufferGeometry} [geometry] - The points geometry.
  21273. * @param {Material|Array<Material>} [material] - The points material.
  21274. */
  21275. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  21276. super();
  21277. /**
  21278. * This flag can be used for type testing.
  21279. *
  21280. * @type {boolean}
  21281. * @readonly
  21282. * @default true
  21283. */
  21284. this.isPoints = true;
  21285. this.type = 'Points';
  21286. /**
  21287. * The points geometry.
  21288. *
  21289. * @type {BufferGeometry}
  21290. */
  21291. this.geometry = geometry;
  21292. /**
  21293. * The line material.
  21294. *
  21295. * @type {Material|Array<Material>}
  21296. * @default PointsMaterial
  21297. */
  21298. this.material = material;
  21299. /**
  21300. * A dictionary representing the morph targets in the geometry. The key is the
  21301. * morph targets name, the value its attribute index. This member is `undefined`
  21302. * by default and only set when morph targets are detected in the geometry.
  21303. *
  21304. * @type {Object<String,number>|undefined}
  21305. * @default undefined
  21306. */
  21307. this.morphTargetDictionary = undefined;
  21308. /**
  21309. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21310. * is applied. This member is `undefined` by default and only set when morph targets are
  21311. * detected in the geometry.
  21312. *
  21313. * @type {Array<number>|undefined}
  21314. * @default undefined
  21315. */
  21316. this.morphTargetInfluences = undefined;
  21317. this.updateMorphTargets();
  21318. }
  21319. copy( source, recursive ) {
  21320. super.copy( source, recursive );
  21321. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21322. this.geometry = source.geometry;
  21323. return this;
  21324. }
  21325. /**
  21326. * Computes intersection points between a casted ray and this point cloud.
  21327. *
  21328. * @param {Raycaster} raycaster - The raycaster.
  21329. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21330. */
  21331. raycast( raycaster, intersects ) {
  21332. const geometry = this.geometry;
  21333. const matrixWorld = this.matrixWorld;
  21334. const threshold = raycaster.params.Points.threshold;
  21335. const drawRange = geometry.drawRange;
  21336. // Checking boundingSphere distance to ray
  21337. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21338. _sphere.copy( geometry.boundingSphere );
  21339. _sphere.applyMatrix4( matrixWorld );
  21340. _sphere.radius += threshold;
  21341. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  21342. //
  21343. _inverseMatrix.copy( matrixWorld ).invert();
  21344. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  21345. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21346. const localThresholdSq = localThreshold * localThreshold;
  21347. const index = geometry.index;
  21348. const attributes = geometry.attributes;
  21349. const positionAttribute = attributes.position;
  21350. if ( index !== null ) {
  21351. const start = Math.max( 0, drawRange.start );
  21352. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21353. for ( let i = start, il = end; i < il; i ++ ) {
  21354. const a = index.getX( i );
  21355. _position$2.fromBufferAttribute( positionAttribute, a );
  21356. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21357. }
  21358. } else {
  21359. const start = Math.max( 0, drawRange.start );
  21360. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21361. for ( let i = start, l = end; i < l; i ++ ) {
  21362. _position$2.fromBufferAttribute( positionAttribute, i );
  21363. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21364. }
  21365. }
  21366. }
  21367. /**
  21368. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  21369. * to make sure existing morph targets can influence this 3D object.
  21370. */
  21371. updateMorphTargets() {
  21372. const geometry = this.geometry;
  21373. const morphAttributes = geometry.morphAttributes;
  21374. const keys = Object.keys( morphAttributes );
  21375. if ( keys.length > 0 ) {
  21376. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21377. if ( morphAttribute !== undefined ) {
  21378. this.morphTargetInfluences = [];
  21379. this.morphTargetDictionary = {};
  21380. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21381. const name = morphAttribute[ m ].name || String( m );
  21382. this.morphTargetInfluences.push( 0 );
  21383. this.morphTargetDictionary[ name ] = m;
  21384. }
  21385. }
  21386. }
  21387. }
  21388. }
  21389. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  21390. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  21391. if ( rayPointDistanceSq < localThresholdSq ) {
  21392. const intersectPoint = new Vector3();
  21393. _ray.closestPointToPoint( point, intersectPoint );
  21394. intersectPoint.applyMatrix4( matrixWorld );
  21395. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  21396. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21397. intersects.push( {
  21398. distance: distance,
  21399. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  21400. point: intersectPoint,
  21401. index: index,
  21402. face: null,
  21403. faceIndex: null,
  21404. barycoord: null,
  21405. object: object
  21406. } );
  21407. }
  21408. }
  21409. /**
  21410. * A texture for use with a video.
  21411. *
  21412. * ```js
  21413. * // assuming you have created a HTML video element with id="video"
  21414. * const video = document.getElementById( 'video' );
  21415. * const texture = new THREE.VideoTexture( video );
  21416. * ```
  21417. *
  21418. * Note: After the initial use of a texture, its dimensions, format, and type
  21419. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  21420. *
  21421. * @augments Texture
  21422. */
  21423. class VideoTexture extends Texture {
  21424. /**
  21425. * Constructs a new video texture.
  21426. *
  21427. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  21428. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21429. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21430. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21431. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21432. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21433. * @param {number} [format=RGBAFormat] - The texture format.
  21434. * @param {number} [type=UnsignedByteType] - The texture type.
  21435. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21436. */
  21437. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  21438. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21439. /**
  21440. * This flag can be used for type testing.
  21441. *
  21442. * @type {boolean}
  21443. * @readonly
  21444. * @default true
  21445. */
  21446. this.isVideoTexture = true;
  21447. /**
  21448. * Whether to generate mipmaps (if possible) for a texture.
  21449. *
  21450. * Overwritten and set to `false` by default.
  21451. *
  21452. * @type {boolean}
  21453. * @default false
  21454. */
  21455. this.generateMipmaps = false;
  21456. const scope = this;
  21457. function updateVideo() {
  21458. scope.needsUpdate = true;
  21459. video.requestVideoFrameCallback( updateVideo );
  21460. }
  21461. if ( 'requestVideoFrameCallback' in video ) {
  21462. video.requestVideoFrameCallback( updateVideo );
  21463. }
  21464. }
  21465. clone() {
  21466. return new this.constructor( this.image ).copy( this );
  21467. }
  21468. /**
  21469. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  21470. * to `true` every time a new frame is available.
  21471. *
  21472. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  21473. */
  21474. update() {
  21475. const video = this.image;
  21476. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  21477. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  21478. this.needsUpdate = true;
  21479. }
  21480. }
  21481. }
  21482. /**
  21483. * This class can be used as an alternative way to define video data. Instead of using
  21484. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  21485. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  21486. * video frames are decoded with the WebCodecs API.
  21487. *
  21488. * ```js
  21489. * const texture = new THREE.VideoFrameTexture();
  21490. * texture.setFrame( frame );
  21491. * ```
  21492. *
  21493. * @augments VideoTexture
  21494. */
  21495. class VideoFrameTexture extends VideoTexture {
  21496. /**
  21497. * Constructs a new video frame texture.
  21498. *
  21499. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21500. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21501. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21502. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21503. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21504. * @param {number} [format=RGBAFormat] - The texture format.
  21505. * @param {number} [type=UnsignedByteType] - The texture type.
  21506. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21507. */
  21508. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21509. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21510. /**
  21511. * This flag can be used for type testing.
  21512. *
  21513. * @type {boolean}
  21514. * @readonly
  21515. * @default true
  21516. */
  21517. this.isVideoFrameTexture = true;
  21518. }
  21519. /**
  21520. * This method overwritten with an empty implementation since
  21521. * this type of texture is updated via `setFrame()`.
  21522. */
  21523. update() {}
  21524. clone() {
  21525. return new this.constructor().copy( this ); // restoring Texture.clone()
  21526. }
  21527. /**
  21528. * Sets the current frame of the video. This will automatically update the texture
  21529. * so the data can be used for rendering.
  21530. *
  21531. * @param {VideoFrame} frame - The video frame.
  21532. */
  21533. setFrame( frame ) {
  21534. this.image = frame;
  21535. this.needsUpdate = true;
  21536. }
  21537. }
  21538. /**
  21539. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  21540. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  21541. * as a texture for further usage.
  21542. *
  21543. * ```js
  21544. * const pixelRatio = window.devicePixelRatio;
  21545. * const textureSize = 128 * pixelRatio;
  21546. *
  21547. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  21548. *
  21549. * // calculate start position for copying part of the frame data
  21550. * const vector = new Vector2();
  21551. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  21552. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  21553. *
  21554. * renderer.render( scene, camera );
  21555. *
  21556. * // copy part of the rendered frame into the framebuffer texture
  21557. * renderer.copyFramebufferToTexture( frameTexture, vector );
  21558. * ```
  21559. *
  21560. * @augments Texture
  21561. */
  21562. class FramebufferTexture extends Texture {
  21563. /**
  21564. * Constructs a new framebuffer texture.
  21565. *
  21566. * @param {number} width - The width of the texture.
  21567. * @param {number} height - The height of the texture.
  21568. */
  21569. constructor( width, height ) {
  21570. super( { width, height } );
  21571. /**
  21572. * This flag can be used for type testing.
  21573. *
  21574. * @type {boolean}
  21575. * @readonly
  21576. * @default true
  21577. */
  21578. this.isFramebufferTexture = true;
  21579. /**
  21580. * How the texture is sampled when a texel covers more than one pixel.
  21581. *
  21582. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21583. *
  21584. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21585. * @default NearestFilter
  21586. */
  21587. this.magFilter = NearestFilter;
  21588. /**
  21589. * How the texture is sampled when a texel covers less than one pixel.
  21590. *
  21591. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21592. *
  21593. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21594. * @default NearestFilter
  21595. */
  21596. this.minFilter = NearestFilter;
  21597. /**
  21598. * Whether to generate mipmaps (if possible) for a texture.
  21599. *
  21600. * Overwritten and set to `false` by default.
  21601. *
  21602. * @type {boolean}
  21603. * @default false
  21604. */
  21605. this.generateMipmaps = false;
  21606. this.needsUpdate = true;
  21607. }
  21608. }
  21609. /**
  21610. * Creates a texture based on data in compressed form.
  21611. *
  21612. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21613. *
  21614. * @augments Texture
  21615. */
  21616. class CompressedTexture extends Texture {
  21617. /**
  21618. * Constructs a new compressed texture.
  21619. *
  21620. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21621. * the data and dimensions.
  21622. * @param {number} width - The width of the texture.
  21623. * @param {number} height - The height of the texture.
  21624. * @param {number} [format=RGBAFormat] - The texture format.
  21625. * @param {number} [type=UnsignedByteType] - The texture type.
  21626. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21627. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21628. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21629. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21630. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21631. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21632. * @param {string} [colorSpace=NoColorSpace] - The color space.
  21633. */
  21634. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  21635. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21636. /**
  21637. * This flag can be used for type testing.
  21638. *
  21639. * @type {boolean}
  21640. * @readonly
  21641. * @default true
  21642. */
  21643. this.isCompressedTexture = true;
  21644. /**
  21645. * The image property of a compressed texture just defines its dimensions.
  21646. *
  21647. * @type {{width:number,height:number}}
  21648. */
  21649. this.image = { width: width, height: height };
  21650. /**
  21651. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  21652. *
  21653. * @type {Array<Object>}
  21654. */
  21655. this.mipmaps = mipmaps;
  21656. /**
  21657. * If set to `true`, the texture is flipped along the vertical axis when
  21658. * uploaded to the GPU.
  21659. *
  21660. * Overwritten and set to `false` by default since it is not possible to
  21661. * flip compressed textures.
  21662. *
  21663. * @type {boolean}
  21664. * @default false
  21665. * @readonly
  21666. */
  21667. this.flipY = false;
  21668. /**
  21669. * Whether to generate mipmaps (if possible) for a texture.
  21670. *
  21671. * Overwritten and set to `false` by default since it is not
  21672. * possible to generate mipmaps for compressed data. Mipmaps
  21673. * must be embedded in the compressed texture file.
  21674. *
  21675. * @type {boolean}
  21676. * @default false
  21677. * @readonly
  21678. */
  21679. this.generateMipmaps = false;
  21680. }
  21681. }
  21682. /**
  21683. * Creates a texture 2D array based on data in compressed form.
  21684. *
  21685. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21686. *
  21687. * @augments CompressedTexture
  21688. */
  21689. class CompressedArrayTexture extends CompressedTexture {
  21690. /**
  21691. * Constructs a new compressed array texture.
  21692. *
  21693. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21694. * the data and dimensions.
  21695. * @param {number} width - The width of the texture.
  21696. * @param {number} height - The height of the texture.
  21697. * @param {number} depth - The depth of the texture.
  21698. * @param {number} [format=RGBAFormat] - The min filter value.
  21699. * @param {number} [type=UnsignedByteType] - The min filter value.
  21700. */
  21701. constructor( mipmaps, width, height, depth, format, type ) {
  21702. super( mipmaps, width, height, format, type );
  21703. /**
  21704. * This flag can be used for type testing.
  21705. *
  21706. * @type {boolean}
  21707. * @readonly
  21708. * @default true
  21709. */
  21710. this.isCompressedArrayTexture = true;
  21711. /**
  21712. * The image property of a compressed texture just defines its dimensions.
  21713. *
  21714. * @name CompressedArrayTexture#image
  21715. * @type {{width:number,height:number,depth:number}}
  21716. */
  21717. this.image.depth = depth;
  21718. /**
  21719. * This defines how the texture is wrapped in the depth and corresponds to
  21720. * *W* in UVW mapping.
  21721. *
  21722. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  21723. * @default ClampToEdgeWrapping
  21724. */
  21725. this.wrapR = ClampToEdgeWrapping;
  21726. /**
  21727. * A set of all layers which need to be updated in the texture.
  21728. *
  21729. * @type {Set<number>}
  21730. */
  21731. this.layerUpdates = new Set();
  21732. }
  21733. /**
  21734. * Describes that a specific layer of the texture needs to be updated.
  21735. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  21736. * entire compressed texture array is sent to the GPU. Marking specific
  21737. * layers will only transmit subsets of all mipmaps associated with a
  21738. * specific depth in the array which is often much more performant.
  21739. *
  21740. * @param {number} layerIndex - The layer index that should be updated.
  21741. */
  21742. addLayerUpdate( layerIndex ) {
  21743. this.layerUpdates.add( layerIndex );
  21744. }
  21745. /**
  21746. * Resets the layer updates registry.
  21747. */
  21748. clearLayerUpdates() {
  21749. this.layerUpdates.clear();
  21750. }
  21751. }
  21752. /**
  21753. * Creates a cube texture based on data in compressed form.
  21754. *
  21755. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21756. *
  21757. * @augments CompressedTexture
  21758. */
  21759. class CompressedCubeTexture extends CompressedTexture {
  21760. /**
  21761. * Constructs a new compressed texture.
  21762. *
  21763. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  21764. * @param {number} [format=RGBAFormat] - The texture format.
  21765. * @param {number} [type=UnsignedByteType] - The texture type.
  21766. */
  21767. constructor( images, format, type ) {
  21768. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  21769. /**
  21770. * This flag can be used for type testing.
  21771. *
  21772. * @type {boolean}
  21773. * @readonly
  21774. * @default true
  21775. */
  21776. this.isCompressedCubeTexture = true;
  21777. /**
  21778. * This flag can be used for type testing.
  21779. *
  21780. * @type {boolean}
  21781. * @readonly
  21782. * @default true
  21783. */
  21784. this.isCubeTexture = true;
  21785. this.image = images;
  21786. }
  21787. }
  21788. /**
  21789. * Creates a texture from a canvas element.
  21790. *
  21791. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  21792. * to `true` immediately since a canvas can directly be used for rendering.
  21793. *
  21794. * @augments Texture
  21795. */
  21796. class CanvasTexture extends Texture {
  21797. /**
  21798. * Constructs a new texture.
  21799. *
  21800. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  21801. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21802. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21803. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21804. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21805. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21806. * @param {number} [format=RGBAFormat] - The texture format.
  21807. * @param {number} [type=UnsignedByteType] - The texture type.
  21808. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21809. */
  21810. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21811. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21812. /**
  21813. * This flag can be used for type testing.
  21814. *
  21815. * @type {boolean}
  21816. * @readonly
  21817. * @default true
  21818. */
  21819. this.isCanvasTexture = true;
  21820. this.needsUpdate = true;
  21821. }
  21822. }
  21823. /**
  21824. * This class can be used to automatically save the depth information of a
  21825. * rendering into a texture.
  21826. *
  21827. * @augments Texture
  21828. */
  21829. class DepthTexture extends Texture {
  21830. /**
  21831. * Constructs a new depth texture.
  21832. *
  21833. * @param {number} width - The width of the texture.
  21834. * @param {number} height - The height of the texture.
  21835. * @param {number} [type=UnsignedIntType] - The texture type.
  21836. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21837. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21838. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21839. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21840. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21841. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21842. * @param {number} [format=DepthFormat] - The texture format.
  21843. */
  21844. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat ) {
  21845. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  21846. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  21847. }
  21848. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21849. /**
  21850. * This flag can be used for type testing.
  21851. *
  21852. * @type {boolean}
  21853. * @readonly
  21854. * @default true
  21855. */
  21856. this.isDepthTexture = true;
  21857. /**
  21858. * The image property of a depth texture just defines its dimensions.
  21859. *
  21860. * @type {{width:number,height:number}}
  21861. */
  21862. this.image = { width: width, height: height };
  21863. /**
  21864. * If set to `true`, the texture is flipped along the vertical axis when
  21865. * uploaded to the GPU.
  21866. *
  21867. * Overwritten and set to `false` by default.
  21868. *
  21869. * @type {boolean}
  21870. * @default false
  21871. */
  21872. this.flipY = false;
  21873. /**
  21874. * Whether to generate mipmaps (if possible) for a texture.
  21875. *
  21876. * Overwritten and set to `false` by default.
  21877. *
  21878. * @type {boolean}
  21879. * @default false
  21880. */
  21881. this.generateMipmaps = false;
  21882. /**
  21883. * Code corresponding to the depth compare function.
  21884. *
  21885. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  21886. * @default null
  21887. */
  21888. this.compareFunction = null;
  21889. }
  21890. copy( source ) {
  21891. super.copy( source );
  21892. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  21893. this.compareFunction = source.compareFunction;
  21894. return this;
  21895. }
  21896. toJSON( meta ) {
  21897. const data = super.toJSON( meta );
  21898. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  21899. return data;
  21900. }
  21901. }
  21902. /**
  21903. * Creates an array of depth textures.
  21904. *
  21905. * @augments DepthTexture
  21906. */
  21907. class DepthArrayTexture extends DepthTexture {
  21908. /**
  21909. * Constructs a new depth array texture.
  21910. *
  21911. * @param {number} [width=1] - The width of the texture.
  21912. * @param {number} [height=1] - The height of the texture.
  21913. * @param {number} [depth=1] - The depth of the texture.
  21914. */
  21915. constructor( width = 1, height = 1, depth = 1 ) {
  21916. super( width, height );
  21917. /**
  21918. * This flag can be used for type testing.
  21919. *
  21920. * @type {boolean}
  21921. * @readonly
  21922. * @default true
  21923. */
  21924. this.isDepthArrayTexture = true;
  21925. /**
  21926. * The image definition of a depth texture.
  21927. *
  21928. * @type {{width:number,height:number,depth:number}}
  21929. */
  21930. this.image = { width: width, height: height, depth: depth };
  21931. /**
  21932. * If set to `true`, the texture is flipped along the vertical axis when
  21933. * uploaded to the GPU.
  21934. *
  21935. * Overwritten and set to `false` by default.
  21936. *
  21937. * @type {boolean}
  21938. * @default false
  21939. */
  21940. this.flipY = false;
  21941. /**
  21942. * Whether to generate mipmaps (if possible) for a texture.
  21943. *
  21944. * Overwritten and set to `false` by default.
  21945. *
  21946. * @type {boolean}
  21947. * @default false
  21948. */
  21949. this.generateMipmaps = false;
  21950. /**
  21951. * Code corresponding to the depth compare function.
  21952. *
  21953. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  21954. * @default null
  21955. */
  21956. this.compareFunction = null;
  21957. /**
  21958. * A set of all layers which need to be updated in the texture.
  21959. *
  21960. * @type {Set<number>}
  21961. */
  21962. this.layerUpdates = new Set();
  21963. }
  21964. /**
  21965. * Describes that a specific layer of the texture needs to be updated.
  21966. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  21967. * entire slice is sent to the GPU. Marking specific
  21968. * layers will only transmit subsets of all mipmaps associated with a
  21969. * specific depth in the array which is often much more performant.
  21970. *
  21971. * @param {number} layerIndex - The layer index that should be updated.
  21972. */
  21973. addLayerUpdate( layerIndex ) {
  21974. this.layerUpdates.add( layerIndex );
  21975. }
  21976. /**
  21977. * Resets the layer updates registry.
  21978. */
  21979. clearLayerUpdates() {
  21980. this.layerUpdates.clear();
  21981. }
  21982. }
  21983. /**
  21984. * A geometry class for representing a capsule.
  21985. *
  21986. * ```js
  21987. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  21988. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  21989. * const capsule = new THREE.Mesh( geometry, material );
  21990. * scene.add( capsule );
  21991. * ```
  21992. *
  21993. * @augments BufferGeometry
  21994. */
  21995. class CapsuleGeometry extends BufferGeometry {
  21996. /**
  21997. * Constructs a new capsule geometry.
  21998. *
  21999. * @param {number} [radius=1] - Radius of the capsule.
  22000. * @param {number} [height=1] - Height of the middle section.
  22001. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  22002. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  22003. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  22004. */
  22005. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  22006. super();
  22007. this.type = 'CapsuleGeometry';
  22008. /**
  22009. * Holds the constructor parameters that have been
  22010. * used to generate the geometry. Any modification
  22011. * after instantiation does not change the geometry.
  22012. *
  22013. * @type {Object}
  22014. */
  22015. this.parameters = {
  22016. radius: radius,
  22017. height: height,
  22018. capSegments: capSegments,
  22019. radialSegments: radialSegments,
  22020. heightSegments: heightSegments,
  22021. };
  22022. height = Math.max( 0, height );
  22023. capSegments = Math.max( 1, Math.floor( capSegments ) );
  22024. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  22025. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  22026. // buffers
  22027. const indices = [];
  22028. const vertices = [];
  22029. const normals = [];
  22030. const uvs = [];
  22031. // helper variables
  22032. const halfHeight = height / 2;
  22033. const capArcLength = ( Math.PI / 2 ) * radius;
  22034. const cylinderPartLength = height;
  22035. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  22036. const numVerticalSegments = capSegments * 2 + heightSegments;
  22037. const verticesPerRow = radialSegments + 1;
  22038. const normal = new Vector3();
  22039. const vertex = new Vector3();
  22040. // generate vertices, normals, and uvs
  22041. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  22042. let currentArcLength = 0;
  22043. let profileY = 0;
  22044. let profileRadius = 0;
  22045. let normalYComponent = 0;
  22046. if ( iy <= capSegments ) {
  22047. // bottom cap
  22048. const segmentProgress = iy / capSegments;
  22049. const angle = ( segmentProgress * Math.PI ) / 2;
  22050. profileY = - halfHeight - radius * Math.cos( angle );
  22051. profileRadius = radius * Math.sin( angle );
  22052. normalYComponent = - radius * Math.cos( angle );
  22053. currentArcLength = segmentProgress * capArcLength;
  22054. } else if ( iy <= capSegments + heightSegments ) {
  22055. // middle section
  22056. const segmentProgress = ( iy - capSegments ) / heightSegments;
  22057. profileY = - halfHeight + segmentProgress * height;
  22058. profileRadius = radius;
  22059. normalYComponent = 0;
  22060. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  22061. } else {
  22062. // top cap
  22063. const segmentProgress =
  22064. ( iy - capSegments - heightSegments ) / capSegments;
  22065. const angle = ( segmentProgress * Math.PI ) / 2;
  22066. profileY = halfHeight + radius * Math.sin( angle );
  22067. profileRadius = radius * Math.cos( angle );
  22068. normalYComponent = radius * Math.sin( angle );
  22069. currentArcLength =
  22070. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  22071. }
  22072. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  22073. // special case for the poles
  22074. let uOffset = 0;
  22075. if ( iy === 0 ) {
  22076. uOffset = 0.5 / radialSegments;
  22077. } else if ( iy === numVerticalSegments ) {
  22078. uOffset = -0.5 / radialSegments;
  22079. }
  22080. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  22081. const u = ix / radialSegments;
  22082. const theta = u * Math.PI * 2;
  22083. const sinTheta = Math.sin( theta );
  22084. const cosTheta = Math.cos( theta );
  22085. // vertex
  22086. vertex.x = - profileRadius * cosTheta;
  22087. vertex.y = profileY;
  22088. vertex.z = profileRadius * sinTheta;
  22089. vertices.push( vertex.x, vertex.y, vertex.z );
  22090. // normal
  22091. normal.set(
  22092. - profileRadius * cosTheta,
  22093. normalYComponent,
  22094. profileRadius * sinTheta
  22095. );
  22096. normal.normalize();
  22097. normals.push( normal.x, normal.y, normal.z );
  22098. // uv
  22099. uvs.push( u + uOffset, v );
  22100. }
  22101. if ( iy > 0 ) {
  22102. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  22103. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  22104. const i1 = prevIndexRow + ix;
  22105. const i2 = prevIndexRow + ix + 1;
  22106. const i3 = iy * verticesPerRow + ix;
  22107. const i4 = iy * verticesPerRow + ix + 1;
  22108. indices.push( i1, i2, i3 );
  22109. indices.push( i2, i4, i3 );
  22110. }
  22111. }
  22112. }
  22113. // build geometry
  22114. this.setIndex( indices );
  22115. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22116. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22117. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22118. }
  22119. copy( source ) {
  22120. super.copy( source );
  22121. this.parameters = Object.assign( {}, source.parameters );
  22122. return this;
  22123. }
  22124. /**
  22125. * Factory method for creating an instance of this class from the given
  22126. * JSON object.
  22127. *
  22128. * @param {Object} data - A JSON object representing the serialized geometry.
  22129. * @return {CapsuleGeometry} A new instance.
  22130. */
  22131. static fromJSON( data ) {
  22132. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  22133. }
  22134. }
  22135. /**
  22136. * A simple shape of Euclidean geometry. It is constructed from a
  22137. * number of triangular segments that are oriented around a central point and
  22138. * extend as far out as a given radius. It is built counter-clockwise from a
  22139. * start angle and a given central angle. It can also be used to create
  22140. * regular polygons, where the number of segments determines the number of
  22141. * sides.
  22142. *
  22143. * ```js
  22144. * const geometry = new THREE.CircleGeometry( 5, 32 );
  22145. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22146. * const circle = new THREE.Mesh( geometry, material );
  22147. * scene.add( circle )
  22148. * ```
  22149. *
  22150. * @augments BufferGeometry
  22151. */
  22152. class CircleGeometry extends BufferGeometry {
  22153. /**
  22154. * Constructs a new circle geometry.
  22155. *
  22156. * @param {number} [radius=1] - Radius of the circle.
  22157. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  22158. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  22159. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  22160. * of the circular sector in radians. The default value results in a complete circle.
  22161. */
  22162. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22163. super();
  22164. this.type = 'CircleGeometry';
  22165. /**
  22166. * Holds the constructor parameters that have been
  22167. * used to generate the geometry. Any modification
  22168. * after instantiation does not change the geometry.
  22169. *
  22170. * @type {Object}
  22171. */
  22172. this.parameters = {
  22173. radius: radius,
  22174. segments: segments,
  22175. thetaStart: thetaStart,
  22176. thetaLength: thetaLength
  22177. };
  22178. segments = Math.max( 3, segments );
  22179. // buffers
  22180. const indices = [];
  22181. const vertices = [];
  22182. const normals = [];
  22183. const uvs = [];
  22184. // helper variables
  22185. const vertex = new Vector3();
  22186. const uv = new Vector2();
  22187. // center point
  22188. vertices.push( 0, 0, 0 );
  22189. normals.push( 0, 0, 1 );
  22190. uvs.push( 0.5, 0.5 );
  22191. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22192. const segment = thetaStart + s / segments * thetaLength;
  22193. // vertex
  22194. vertex.x = radius * Math.cos( segment );
  22195. vertex.y = radius * Math.sin( segment );
  22196. vertices.push( vertex.x, vertex.y, vertex.z );
  22197. // normal
  22198. normals.push( 0, 0, 1 );
  22199. // uvs
  22200. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22201. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22202. uvs.push( uv.x, uv.y );
  22203. }
  22204. // indices
  22205. for ( let i = 1; i <= segments; i ++ ) {
  22206. indices.push( i, i + 1, 0 );
  22207. }
  22208. // build geometry
  22209. this.setIndex( indices );
  22210. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22211. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22212. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22213. }
  22214. copy( source ) {
  22215. super.copy( source );
  22216. this.parameters = Object.assign( {}, source.parameters );
  22217. return this;
  22218. }
  22219. /**
  22220. * Factory method for creating an instance of this class from the given
  22221. * JSON object.
  22222. *
  22223. * @param {Object} data - A JSON object representing the serialized geometry.
  22224. * @return {CircleGeometry} A new instance.
  22225. */
  22226. static fromJSON( data ) {
  22227. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  22228. }
  22229. }
  22230. /**
  22231. * A geometry class for representing a cylinder.
  22232. *
  22233. * ```js
  22234. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  22235. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22236. * const cylinder = new THREE.Mesh( geometry, material );
  22237. * scene.add( cylinder );
  22238. * ```
  22239. *
  22240. * @augments BufferGeometry
  22241. */
  22242. class CylinderGeometry extends BufferGeometry {
  22243. /**
  22244. * Constructs a new cylinder geometry.
  22245. *
  22246. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  22247. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  22248. * @param {number} [height=1] - Height of the cylinder.
  22249. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  22250. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  22251. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  22252. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22253. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22254. * The default value results in a complete cylinder.
  22255. */
  22256. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22257. super();
  22258. this.type = 'CylinderGeometry';
  22259. /**
  22260. * Holds the constructor parameters that have been
  22261. * used to generate the geometry. Any modification
  22262. * after instantiation does not change the geometry.
  22263. *
  22264. * @type {Object}
  22265. */
  22266. this.parameters = {
  22267. radiusTop: radiusTop,
  22268. radiusBottom: radiusBottom,
  22269. height: height,
  22270. radialSegments: radialSegments,
  22271. heightSegments: heightSegments,
  22272. openEnded: openEnded,
  22273. thetaStart: thetaStart,
  22274. thetaLength: thetaLength
  22275. };
  22276. const scope = this;
  22277. radialSegments = Math.floor( radialSegments );
  22278. heightSegments = Math.floor( heightSegments );
  22279. // buffers
  22280. const indices = [];
  22281. const vertices = [];
  22282. const normals = [];
  22283. const uvs = [];
  22284. // helper variables
  22285. let index = 0;
  22286. const indexArray = [];
  22287. const halfHeight = height / 2;
  22288. let groupStart = 0;
  22289. // generate geometry
  22290. generateTorso();
  22291. if ( openEnded === false ) {
  22292. if ( radiusTop > 0 ) generateCap( true );
  22293. if ( radiusBottom > 0 ) generateCap( false );
  22294. }
  22295. // build geometry
  22296. this.setIndex( indices );
  22297. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22298. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22299. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22300. function generateTorso() {
  22301. const normal = new Vector3();
  22302. const vertex = new Vector3();
  22303. let groupCount = 0;
  22304. // this will be used to calculate the normal
  22305. const slope = ( radiusBottom - radiusTop ) / height;
  22306. // generate vertices, normals and uvs
  22307. for ( let y = 0; y <= heightSegments; y ++ ) {
  22308. const indexRow = [];
  22309. const v = y / heightSegments;
  22310. // calculate the radius of the current row
  22311. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22312. for ( let x = 0; x <= radialSegments; x ++ ) {
  22313. const u = x / radialSegments;
  22314. const theta = u * thetaLength + thetaStart;
  22315. const sinTheta = Math.sin( theta );
  22316. const cosTheta = Math.cos( theta );
  22317. // vertex
  22318. vertex.x = radius * sinTheta;
  22319. vertex.y = - v * height + halfHeight;
  22320. vertex.z = radius * cosTheta;
  22321. vertices.push( vertex.x, vertex.y, vertex.z );
  22322. // normal
  22323. normal.set( sinTheta, slope, cosTheta ).normalize();
  22324. normals.push( normal.x, normal.y, normal.z );
  22325. // uv
  22326. uvs.push( u, 1 - v );
  22327. // save index of vertex in respective row
  22328. indexRow.push( index ++ );
  22329. }
  22330. // now save vertices of the row in our index array
  22331. indexArray.push( indexRow );
  22332. }
  22333. // generate indices
  22334. for ( let x = 0; x < radialSegments; x ++ ) {
  22335. for ( let y = 0; y < heightSegments; y ++ ) {
  22336. // we use the index array to access the correct indices
  22337. const a = indexArray[ y ][ x ];
  22338. const b = indexArray[ y + 1 ][ x ];
  22339. const c = indexArray[ y + 1 ][ x + 1 ];
  22340. const d = indexArray[ y ][ x + 1 ];
  22341. // faces
  22342. if ( radiusTop > 0 || y !== 0 ) {
  22343. indices.push( a, b, d );
  22344. groupCount += 3;
  22345. }
  22346. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  22347. indices.push( b, c, d );
  22348. groupCount += 3;
  22349. }
  22350. }
  22351. }
  22352. // add a group to the geometry. this will ensure multi material support
  22353. scope.addGroup( groupStart, groupCount, 0 );
  22354. // calculate new start value for groups
  22355. groupStart += groupCount;
  22356. }
  22357. function generateCap( top ) {
  22358. // save the index of the first center vertex
  22359. const centerIndexStart = index;
  22360. const uv = new Vector2();
  22361. const vertex = new Vector3();
  22362. let groupCount = 0;
  22363. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22364. const sign = ( top === true ) ? 1 : -1;
  22365. // first we generate the center vertex data of the cap.
  22366. // because the geometry needs one set of uvs per face,
  22367. // we must generate a center vertex per face/segment
  22368. for ( let x = 1; x <= radialSegments; x ++ ) {
  22369. // vertex
  22370. vertices.push( 0, halfHeight * sign, 0 );
  22371. // normal
  22372. normals.push( 0, sign, 0 );
  22373. // uv
  22374. uvs.push( 0.5, 0.5 );
  22375. // increase index
  22376. index ++;
  22377. }
  22378. // save the index of the last center vertex
  22379. const centerIndexEnd = index;
  22380. // now we generate the surrounding vertices, normals and uvs
  22381. for ( let x = 0; x <= radialSegments; x ++ ) {
  22382. const u = x / radialSegments;
  22383. const theta = u * thetaLength + thetaStart;
  22384. const cosTheta = Math.cos( theta );
  22385. const sinTheta = Math.sin( theta );
  22386. // vertex
  22387. vertex.x = radius * sinTheta;
  22388. vertex.y = halfHeight * sign;
  22389. vertex.z = radius * cosTheta;
  22390. vertices.push( vertex.x, vertex.y, vertex.z );
  22391. // normal
  22392. normals.push( 0, sign, 0 );
  22393. // uv
  22394. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22395. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22396. uvs.push( uv.x, uv.y );
  22397. // increase index
  22398. index ++;
  22399. }
  22400. // generate indices
  22401. for ( let x = 0; x < radialSegments; x ++ ) {
  22402. const c = centerIndexStart + x;
  22403. const i = centerIndexEnd + x;
  22404. if ( top === true ) {
  22405. // face top
  22406. indices.push( i, i + 1, c );
  22407. } else {
  22408. // face bottom
  22409. indices.push( i + 1, i, c );
  22410. }
  22411. groupCount += 3;
  22412. }
  22413. // add a group to the geometry. this will ensure multi material support
  22414. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22415. // calculate new start value for groups
  22416. groupStart += groupCount;
  22417. }
  22418. }
  22419. copy( source ) {
  22420. super.copy( source );
  22421. this.parameters = Object.assign( {}, source.parameters );
  22422. return this;
  22423. }
  22424. /**
  22425. * Factory method for creating an instance of this class from the given
  22426. * JSON object.
  22427. *
  22428. * @param {Object} data - A JSON object representing the serialized geometry.
  22429. * @return {CylinderGeometry} A new instance.
  22430. */
  22431. static fromJSON( data ) {
  22432. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22433. }
  22434. }
  22435. /**
  22436. * A geometry class for representing a cone.
  22437. *
  22438. * ```js
  22439. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  22440. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22441. * const cone = new THREE.Mesh(geometry, material );
  22442. * scene.add( cone );
  22443. * ```
  22444. *
  22445. * @augments CylinderGeometry
  22446. */
  22447. class ConeGeometry extends CylinderGeometry {
  22448. /**
  22449. * Constructs a new cone geometry.
  22450. *
  22451. * @param {number} [radius=1] - Radius of the cone base.
  22452. * @param {number} [height=1] - Height of the cone.
  22453. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  22454. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  22455. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  22456. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22457. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22458. * The default value results in a complete cone.
  22459. */
  22460. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22461. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22462. this.type = 'ConeGeometry';
  22463. /**
  22464. * Holds the constructor parameters that have been
  22465. * used to generate the geometry. Any modification
  22466. * after instantiation does not change the geometry.
  22467. *
  22468. * @type {Object}
  22469. */
  22470. this.parameters = {
  22471. radius: radius,
  22472. height: height,
  22473. radialSegments: radialSegments,
  22474. heightSegments: heightSegments,
  22475. openEnded: openEnded,
  22476. thetaStart: thetaStart,
  22477. thetaLength: thetaLength
  22478. };
  22479. }
  22480. /**
  22481. * Factory method for creating an instance of this class from the given
  22482. * JSON object.
  22483. *
  22484. * @param {Object} data - A JSON object representing the serialized geometry.
  22485. * @return {ConeGeometry} A new instance.
  22486. */
  22487. static fromJSON( data ) {
  22488. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22489. }
  22490. }
  22491. /**
  22492. * A polyhedron is a solid in three dimensions with flat faces. This class
  22493. * will take an array of vertices, project them onto a sphere, and then
  22494. * divide them up to the desired level of detail.
  22495. *
  22496. * @augments BufferGeometry
  22497. */
  22498. class PolyhedronGeometry extends BufferGeometry {
  22499. /**
  22500. * Constructs a new polyhedron geometry.
  22501. *
  22502. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  22503. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  22504. * @param {number} [radius=1] - The radius of the shape.
  22505. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  22506. */
  22507. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22508. super();
  22509. this.type = 'PolyhedronGeometry';
  22510. /**
  22511. * Holds the constructor parameters that have been
  22512. * used to generate the geometry. Any modification
  22513. * after instantiation does not change the geometry.
  22514. *
  22515. * @type {Object}
  22516. */
  22517. this.parameters = {
  22518. vertices: vertices,
  22519. indices: indices,
  22520. radius: radius,
  22521. detail: detail
  22522. };
  22523. // default buffer data
  22524. const vertexBuffer = [];
  22525. const uvBuffer = [];
  22526. // the subdivision creates the vertex buffer data
  22527. subdivide( detail );
  22528. // all vertices should lie on a conceptual sphere with a given radius
  22529. applyRadius( radius );
  22530. // finally, create the uv data
  22531. generateUVs();
  22532. // build non-indexed geometry
  22533. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22534. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22535. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22536. if ( detail === 0 ) {
  22537. this.computeVertexNormals(); // flat normals
  22538. } else {
  22539. this.normalizeNormals(); // smooth normals
  22540. }
  22541. // helper functions
  22542. function subdivide( detail ) {
  22543. const a = new Vector3();
  22544. const b = new Vector3();
  22545. const c = new Vector3();
  22546. // iterate over all faces and apply a subdivision with the given detail value
  22547. for ( let i = 0; i < indices.length; i += 3 ) {
  22548. // get the vertices of the face
  22549. getVertexByIndex( indices[ i + 0 ], a );
  22550. getVertexByIndex( indices[ i + 1 ], b );
  22551. getVertexByIndex( indices[ i + 2 ], c );
  22552. // perform subdivision
  22553. subdivideFace( a, b, c, detail );
  22554. }
  22555. }
  22556. function subdivideFace( a, b, c, detail ) {
  22557. const cols = detail + 1;
  22558. // we use this multidimensional array as a data structure for creating the subdivision
  22559. const v = [];
  22560. // construct all of the vertices for this subdivision
  22561. for ( let i = 0; i <= cols; i ++ ) {
  22562. v[ i ] = [];
  22563. const aj = a.clone().lerp( c, i / cols );
  22564. const bj = b.clone().lerp( c, i / cols );
  22565. const rows = cols - i;
  22566. for ( let j = 0; j <= rows; j ++ ) {
  22567. if ( j === 0 && i === cols ) {
  22568. v[ i ][ j ] = aj;
  22569. } else {
  22570. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22571. }
  22572. }
  22573. }
  22574. // construct all of the faces
  22575. for ( let i = 0; i < cols; i ++ ) {
  22576. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22577. const k = Math.floor( j / 2 );
  22578. if ( j % 2 === 0 ) {
  22579. pushVertex( v[ i ][ k + 1 ] );
  22580. pushVertex( v[ i + 1 ][ k ] );
  22581. pushVertex( v[ i ][ k ] );
  22582. } else {
  22583. pushVertex( v[ i ][ k + 1 ] );
  22584. pushVertex( v[ i + 1 ][ k + 1 ] );
  22585. pushVertex( v[ i + 1 ][ k ] );
  22586. }
  22587. }
  22588. }
  22589. }
  22590. function applyRadius( radius ) {
  22591. const vertex = new Vector3();
  22592. // iterate over the entire buffer and apply the radius to each vertex
  22593. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22594. vertex.x = vertexBuffer[ i + 0 ];
  22595. vertex.y = vertexBuffer[ i + 1 ];
  22596. vertex.z = vertexBuffer[ i + 2 ];
  22597. vertex.normalize().multiplyScalar( radius );
  22598. vertexBuffer[ i + 0 ] = vertex.x;
  22599. vertexBuffer[ i + 1 ] = vertex.y;
  22600. vertexBuffer[ i + 2 ] = vertex.z;
  22601. }
  22602. }
  22603. function generateUVs() {
  22604. const vertex = new Vector3();
  22605. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22606. vertex.x = vertexBuffer[ i + 0 ];
  22607. vertex.y = vertexBuffer[ i + 1 ];
  22608. vertex.z = vertexBuffer[ i + 2 ];
  22609. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22610. const v = inclination( vertex ) / Math.PI + 0.5;
  22611. uvBuffer.push( u, 1 - v );
  22612. }
  22613. correctUVs();
  22614. correctSeam();
  22615. }
  22616. function correctSeam() {
  22617. // handle case when face straddles the seam, see #3269
  22618. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22619. // uv data of a single face
  22620. const x0 = uvBuffer[ i + 0 ];
  22621. const x1 = uvBuffer[ i + 2 ];
  22622. const x2 = uvBuffer[ i + 4 ];
  22623. const max = Math.max( x0, x1, x2 );
  22624. const min = Math.min( x0, x1, x2 );
  22625. // 0.9 is somewhat arbitrary
  22626. if ( max > 0.9 && min < 0.1 ) {
  22627. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  22628. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  22629. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  22630. }
  22631. }
  22632. }
  22633. function pushVertex( vertex ) {
  22634. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22635. }
  22636. function getVertexByIndex( index, vertex ) {
  22637. const stride = index * 3;
  22638. vertex.x = vertices[ stride + 0 ];
  22639. vertex.y = vertices[ stride + 1 ];
  22640. vertex.z = vertices[ stride + 2 ];
  22641. }
  22642. function correctUVs() {
  22643. const a = new Vector3();
  22644. const b = new Vector3();
  22645. const c = new Vector3();
  22646. const centroid = new Vector3();
  22647. const uvA = new Vector2();
  22648. const uvB = new Vector2();
  22649. const uvC = new Vector2();
  22650. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  22651. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  22652. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  22653. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  22654. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  22655. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  22656. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  22657. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  22658. const azi = azimuth( centroid );
  22659. correctUV( uvA, j + 0, a, azi );
  22660. correctUV( uvB, j + 2, b, azi );
  22661. correctUV( uvC, j + 4, c, azi );
  22662. }
  22663. }
  22664. function correctUV( uv, stride, vector, azimuth ) {
  22665. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  22666. uvBuffer[ stride ] = uv.x - 1;
  22667. }
  22668. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  22669. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  22670. }
  22671. }
  22672. // Angle around the Y axis, counter-clockwise when looking from above.
  22673. function azimuth( vector ) {
  22674. return Math.atan2( vector.z, - vector.x );
  22675. }
  22676. // Angle above the XZ plane.
  22677. function inclination( vector ) {
  22678. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22679. }
  22680. }
  22681. copy( source ) {
  22682. super.copy( source );
  22683. this.parameters = Object.assign( {}, source.parameters );
  22684. return this;
  22685. }
  22686. /**
  22687. * Factory method for creating an instance of this class from the given
  22688. * JSON object.
  22689. *
  22690. * @param {Object} data - A JSON object representing the serialized geometry.
  22691. * @return {PolyhedronGeometry} A new instance.
  22692. */
  22693. static fromJSON( data ) {
  22694. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  22695. }
  22696. }
  22697. /**
  22698. * A geometry class for representing a dodecahedron.
  22699. *
  22700. * ```js
  22701. * const geometry = new THREE.DodecahedronGeometry();
  22702. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22703. * const dodecahedron = new THREE.Mesh( geometry, material );
  22704. * scene.add( dodecahedron );
  22705. * ```
  22706. *
  22707. * @augments PolyhedronGeometry
  22708. */
  22709. class DodecahedronGeometry extends PolyhedronGeometry {
  22710. /**
  22711. * Constructs a new dodecahedron geometry.
  22712. *
  22713. * @param {number} [radius=1] - Radius of the dodecahedron.
  22714. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  22715. */
  22716. constructor( radius = 1, detail = 0 ) {
  22717. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22718. const r = 1 / t;
  22719. const vertices = [
  22720. // (±1, ±1, ±1)
  22721. -1, -1, -1, -1, -1, 1,
  22722. -1, 1, -1, -1, 1, 1,
  22723. 1, -1, -1, 1, -1, 1,
  22724. 1, 1, -1, 1, 1, 1,
  22725. // (0, ±1/φ, ±φ)
  22726. 0, - r, - t, 0, - r, t,
  22727. 0, r, - t, 0, r, t,
  22728. // (±1/φ, ±φ, 0)
  22729. - r, - t, 0, - r, t, 0,
  22730. r, - t, 0, r, t, 0,
  22731. // (±φ, 0, ±1/φ)
  22732. - t, 0, - r, t, 0, - r,
  22733. - t, 0, r, t, 0, r
  22734. ];
  22735. const indices = [
  22736. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22737. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22738. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22739. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22740. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22741. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22742. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22743. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22744. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22745. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22746. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22747. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22748. ];
  22749. super( vertices, indices, radius, detail );
  22750. this.type = 'DodecahedronGeometry';
  22751. /**
  22752. * Holds the constructor parameters that have been
  22753. * used to generate the geometry. Any modification
  22754. * after instantiation does not change the geometry.
  22755. *
  22756. * @type {Object}
  22757. */
  22758. this.parameters = {
  22759. radius: radius,
  22760. detail: detail
  22761. };
  22762. }
  22763. /**
  22764. * Factory method for creating an instance of this class from the given
  22765. * JSON object.
  22766. *
  22767. * @param {Object} data - A JSON object representing the serialized geometry.
  22768. * @return {DodecahedronGeometry} A new instance.
  22769. */
  22770. static fromJSON( data ) {
  22771. return new DodecahedronGeometry( data.radius, data.detail );
  22772. }
  22773. }
  22774. const _v0$1 = /*@__PURE__*/ new Vector3();
  22775. const _v1$1 = /*@__PURE__*/ new Vector3();
  22776. const _normal = /*@__PURE__*/ new Vector3();
  22777. const _triangle = /*@__PURE__*/ new Triangle();
  22778. /**
  22779. * Can be used as a helper object to view the edges of a geometry.
  22780. *
  22781. * ```js
  22782. * const geometry = new THREE.BoxGeometry();
  22783. * const edges = new THREE.EdgesGeometry( geometry );
  22784. * const line = new THREE.LineSegments( edges );
  22785. * scene.add( line );
  22786. * ```
  22787. *
  22788. * Note: It is not yet possible to serialize/deserialize instances of this class.
  22789. *
  22790. * @augments BufferGeometry
  22791. */
  22792. class EdgesGeometry extends BufferGeometry {
  22793. /**
  22794. * Constructs a new edges geometry.
  22795. *
  22796. * @param {?BufferGeometry} [geometry=null] - The geometry.
  22797. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  22798. * between the face normals of the adjoining faces exceeds this value.
  22799. */
  22800. constructor( geometry = null, thresholdAngle = 1 ) {
  22801. super();
  22802. this.type = 'EdgesGeometry';
  22803. /**
  22804. * Holds the constructor parameters that have been
  22805. * used to generate the geometry. Any modification
  22806. * after instantiation does not change the geometry.
  22807. *
  22808. * @type {Object}
  22809. */
  22810. this.parameters = {
  22811. geometry: geometry,
  22812. thresholdAngle: thresholdAngle
  22813. };
  22814. if ( geometry !== null ) {
  22815. const precisionPoints = 4;
  22816. const precision = Math.pow( 10, precisionPoints );
  22817. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  22818. const indexAttr = geometry.getIndex();
  22819. const positionAttr = geometry.getAttribute( 'position' );
  22820. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  22821. const indexArr = [ 0, 0, 0 ];
  22822. const vertKeys = [ 'a', 'b', 'c' ];
  22823. const hashes = new Array( 3 );
  22824. const edgeData = {};
  22825. const vertices = [];
  22826. for ( let i = 0; i < indexCount; i += 3 ) {
  22827. if ( indexAttr ) {
  22828. indexArr[ 0 ] = indexAttr.getX( i );
  22829. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  22830. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  22831. } else {
  22832. indexArr[ 0 ] = i;
  22833. indexArr[ 1 ] = i + 1;
  22834. indexArr[ 2 ] = i + 2;
  22835. }
  22836. const { a, b, c } = _triangle;
  22837. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  22838. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  22839. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  22840. _triangle.getNormal( _normal );
  22841. // create hashes for the edge from the vertices
  22842. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  22843. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  22844. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  22845. // skip degenerate triangles
  22846. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  22847. continue;
  22848. }
  22849. // iterate over every edge
  22850. for ( let j = 0; j < 3; j ++ ) {
  22851. // get the first and next vertex making up the edge
  22852. const jNext = ( j + 1 ) % 3;
  22853. const vecHash0 = hashes[ j ];
  22854. const vecHash1 = hashes[ jNext ];
  22855. const v0 = _triangle[ vertKeys[ j ] ];
  22856. const v1 = _triangle[ vertKeys[ jNext ] ];
  22857. const hash = `${ vecHash0 }_${ vecHash1 }`;
  22858. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  22859. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  22860. // if we found a sibling edge add it into the vertex array if
  22861. // it meets the angle threshold and delete the edge from the map.
  22862. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  22863. vertices.push( v0.x, v0.y, v0.z );
  22864. vertices.push( v1.x, v1.y, v1.z );
  22865. }
  22866. edgeData[ reverseHash ] = null;
  22867. } else if ( ! ( hash in edgeData ) ) {
  22868. // if we've already got an edge here then skip adding a new one
  22869. edgeData[ hash ] = {
  22870. index0: indexArr[ j ],
  22871. index1: indexArr[ jNext ],
  22872. normal: _normal.clone(),
  22873. };
  22874. }
  22875. }
  22876. }
  22877. // iterate over all remaining, unmatched edges and add them to the vertex array
  22878. for ( const key in edgeData ) {
  22879. if ( edgeData[ key ] ) {
  22880. const { index0, index1 } = edgeData[ key ];
  22881. _v0$1.fromBufferAttribute( positionAttr, index0 );
  22882. _v1$1.fromBufferAttribute( positionAttr, index1 );
  22883. vertices.push( _v0$1.x, _v0$1.y, _v0$1.z );
  22884. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  22885. }
  22886. }
  22887. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22888. }
  22889. }
  22890. copy( source ) {
  22891. super.copy( source );
  22892. this.parameters = Object.assign( {}, source.parameters );
  22893. return this;
  22894. }
  22895. }
  22896. /**
  22897. * An abstract base class for creating an analytic curve object that contains methods
  22898. * for interpolation.
  22899. *
  22900. * @abstract
  22901. */
  22902. class Curve {
  22903. /**
  22904. * Constructs a new curve.
  22905. */
  22906. constructor() {
  22907. /**
  22908. * The type property is used for detecting the object type
  22909. * in context of serialization/deserialization.
  22910. *
  22911. * @type {string}
  22912. * @readonly
  22913. */
  22914. this.type = 'Curve';
  22915. /**
  22916. * This value determines the amount of divisions when calculating the
  22917. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  22918. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  22919. * recommended to increase the value of this property if the curve is very large.
  22920. *
  22921. * @type {number}
  22922. * @default 200
  22923. */
  22924. this.arcLengthDivisions = 200;
  22925. /**
  22926. * Must be set to `true` if the curve parameters have changed.
  22927. *
  22928. * @type {boolean}
  22929. * @default false
  22930. */
  22931. this.needsUpdate = false;
  22932. /**
  22933. * An internal cache that holds precomputed curve length values.
  22934. *
  22935. * @private
  22936. * @type {?Array<number>}
  22937. * @default null
  22938. */
  22939. this.cacheArcLengths = null;
  22940. }
  22941. /**
  22942. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  22943. * for the given interpolation factor.
  22944. *
  22945. * @abstract
  22946. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22947. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22948. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  22949. */
  22950. getPoint( /* t, optionalTarget */ ) {
  22951. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  22952. }
  22953. /**
  22954. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  22955. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  22956. * of the curve which equidistant samples.
  22957. *
  22958. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22959. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22960. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  22961. */
  22962. getPointAt( u, optionalTarget ) {
  22963. const t = this.getUtoTmapping( u );
  22964. return this.getPoint( t, optionalTarget );
  22965. }
  22966. /**
  22967. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  22968. * the curve shape.
  22969. *
  22970. * @param {number} [divisions=5] - The number of divisions.
  22971. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  22972. */
  22973. getPoints( divisions = 5 ) {
  22974. const points = [];
  22975. for ( let d = 0; d <= divisions; d ++ ) {
  22976. points.push( this.getPoint( d / divisions ) );
  22977. }
  22978. return points;
  22979. }
  22980. // Get sequence of points using getPointAt( u )
  22981. /**
  22982. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  22983. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  22984. * curve.
  22985. *
  22986. * @param {number} [divisions=5] - The number of divisions.
  22987. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  22988. */
  22989. getSpacedPoints( divisions = 5 ) {
  22990. const points = [];
  22991. for ( let d = 0; d <= divisions; d ++ ) {
  22992. points.push( this.getPointAt( d / divisions ) );
  22993. }
  22994. return points;
  22995. }
  22996. /**
  22997. * Returns the total arc length of the curve.
  22998. *
  22999. * @return {number} The length of the curve.
  23000. */
  23001. getLength() {
  23002. const lengths = this.getLengths();
  23003. return lengths[ lengths.length - 1 ];
  23004. }
  23005. /**
  23006. * Returns an array of cumulative segment lengths of the curve.
  23007. *
  23008. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  23009. * @return {Array<number>} An array holding the cumulative segment lengths.
  23010. */
  23011. getLengths( divisions = this.arcLengthDivisions ) {
  23012. if ( this.cacheArcLengths &&
  23013. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23014. ! this.needsUpdate ) {
  23015. return this.cacheArcLengths;
  23016. }
  23017. this.needsUpdate = false;
  23018. const cache = [];
  23019. let current, last = this.getPoint( 0 );
  23020. let sum = 0;
  23021. cache.push( 0 );
  23022. for ( let p = 1; p <= divisions; p ++ ) {
  23023. current = this.getPoint( p / divisions );
  23024. sum += current.distanceTo( last );
  23025. cache.push( sum );
  23026. last = current;
  23027. }
  23028. this.cacheArcLengths = cache;
  23029. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23030. }
  23031. /**
  23032. * Update the cumulative segment distance cache. The method must be called
  23033. * every time curve parameters are changed. If an updated curve is part of a
  23034. * composed curve like {@link CurvePath}, this method must be called on the
  23035. * composed curve, too.
  23036. */
  23037. updateArcLengths() {
  23038. this.needsUpdate = true;
  23039. this.getLengths();
  23040. }
  23041. /**
  23042. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  23043. * interpolation factor in the same range that can be ued to sample equidistant points
  23044. * from a curve.
  23045. *
  23046. * @param {number} u - The interpolation factor.
  23047. * @param {?number} distance - An optional distance on the curve.
  23048. * @return {number} The updated interpolation factor.
  23049. */
  23050. getUtoTmapping( u, distance = null ) {
  23051. const arcLengths = this.getLengths();
  23052. let i = 0;
  23053. const il = arcLengths.length;
  23054. let targetArcLength; // The targeted u distance value to get
  23055. if ( distance ) {
  23056. targetArcLength = distance;
  23057. } else {
  23058. targetArcLength = u * arcLengths[ il - 1 ];
  23059. }
  23060. // binary search for the index with largest value smaller than target u distance
  23061. let low = 0, high = il - 1, comparison;
  23062. while ( low <= high ) {
  23063. 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
  23064. comparison = arcLengths[ i ] - targetArcLength;
  23065. if ( comparison < 0 ) {
  23066. low = i + 1;
  23067. } else if ( comparison > 0 ) {
  23068. high = i - 1;
  23069. } else {
  23070. high = i;
  23071. break;
  23072. // DONE
  23073. }
  23074. }
  23075. i = high;
  23076. if ( arcLengths[ i ] === targetArcLength ) {
  23077. return i / ( il - 1 );
  23078. }
  23079. // we could get finer grain at lengths, or use simple interpolation between two points
  23080. const lengthBefore = arcLengths[ i ];
  23081. const lengthAfter = arcLengths[ i + 1 ];
  23082. const segmentLength = lengthAfter - lengthBefore;
  23083. // determine where we are between the 'before' and 'after' points
  23084. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23085. // add that fractional amount to t
  23086. const t = ( i + segmentFraction ) / ( il - 1 );
  23087. return t;
  23088. }
  23089. /**
  23090. * Returns a unit vector tangent for the given interpolation factor.
  23091. * If the derived curve does not implement its tangent derivation,
  23092. * two points a small delta apart will be used to find its gradient
  23093. * which seems to give a reasonable approximation.
  23094. *
  23095. * @param {number} t - The interpolation factor.
  23096. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23097. * @return {(Vector2|Vector3)} The tangent vector.
  23098. */
  23099. getTangent( t, optionalTarget ) {
  23100. const delta = 0.0001;
  23101. let t1 = t - delta;
  23102. let t2 = t + delta;
  23103. // Capping in case of danger
  23104. if ( t1 < 0 ) t1 = 0;
  23105. if ( t2 > 1 ) t2 = 1;
  23106. const pt1 = this.getPoint( t1 );
  23107. const pt2 = this.getPoint( t2 );
  23108. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  23109. tangent.copy( pt2 ).sub( pt1 ).normalize();
  23110. return tangent;
  23111. }
  23112. /**
  23113. * Same as {@link Curve#getTangent} but with equidistant samples.
  23114. *
  23115. * @param {number} u - The interpolation factor.
  23116. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23117. * @return {(Vector2|Vector3)} The tangent vector.
  23118. * @see {@link Curve#getPointAt}
  23119. */
  23120. getTangentAt( u, optionalTarget ) {
  23121. const t = this.getUtoTmapping( u );
  23122. return this.getTangent( t, optionalTarget );
  23123. }
  23124. /**
  23125. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  23126. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  23127. *
  23128. * @param {number} segments - The number of segments.
  23129. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23130. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  23131. */
  23132. computeFrenetFrames( segments, closed = false ) {
  23133. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23134. const normal = new Vector3();
  23135. const tangents = [];
  23136. const normals = [];
  23137. const binormals = [];
  23138. const vec = new Vector3();
  23139. const mat = new Matrix4();
  23140. // compute the tangent vectors for each segment on the curve
  23141. for ( let i = 0; i <= segments; i ++ ) {
  23142. const u = i / segments;
  23143. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23144. }
  23145. // select an initial normal vector perpendicular to the first tangent vector,
  23146. // and in the direction of the minimum tangent xyz component
  23147. normals[ 0 ] = new Vector3();
  23148. binormals[ 0 ] = new Vector3();
  23149. let min = Number.MAX_VALUE;
  23150. const tx = Math.abs( tangents[ 0 ].x );
  23151. const ty = Math.abs( tangents[ 0 ].y );
  23152. const tz = Math.abs( tangents[ 0 ].z );
  23153. if ( tx <= min ) {
  23154. min = tx;
  23155. normal.set( 1, 0, 0 );
  23156. }
  23157. if ( ty <= min ) {
  23158. min = ty;
  23159. normal.set( 0, 1, 0 );
  23160. }
  23161. if ( tz <= min ) {
  23162. normal.set( 0, 0, 1 );
  23163. }
  23164. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23165. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23166. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23167. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23168. for ( let i = 1; i <= segments; i ++ ) {
  23169. normals[ i ] = normals[ i - 1 ].clone();
  23170. binormals[ i ] = binormals[ i - 1 ].clone();
  23171. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23172. if ( vec.length() > Number.EPSILON ) {
  23173. vec.normalize();
  23174. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  23175. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23176. }
  23177. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23178. }
  23179. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23180. if ( closed === true ) {
  23181. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  23182. theta /= segments;
  23183. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23184. theta = - theta;
  23185. }
  23186. for ( let i = 1; i <= segments; i ++ ) {
  23187. // twist a little...
  23188. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23189. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23190. }
  23191. }
  23192. return {
  23193. tangents: tangents,
  23194. normals: normals,
  23195. binormals: binormals
  23196. };
  23197. }
  23198. /**
  23199. * Returns a new curve with copied values from this instance.
  23200. *
  23201. * @return {Curve} A clone of this instance.
  23202. */
  23203. clone() {
  23204. return new this.constructor().copy( this );
  23205. }
  23206. /**
  23207. * Copies the values of the given curve to this instance.
  23208. *
  23209. * @param {Curve} source - The curve to copy.
  23210. * @return {Curve} A reference to this curve.
  23211. */
  23212. copy( source ) {
  23213. this.arcLengthDivisions = source.arcLengthDivisions;
  23214. return this;
  23215. }
  23216. /**
  23217. * Serializes the curve into JSON.
  23218. *
  23219. * @return {Object} A JSON object representing the serialized curve.
  23220. * @see {@link ObjectLoader#parse}
  23221. */
  23222. toJSON() {
  23223. const data = {
  23224. metadata: {
  23225. version: 4.6,
  23226. type: 'Curve',
  23227. generator: 'Curve.toJSON'
  23228. }
  23229. };
  23230. data.arcLengthDivisions = this.arcLengthDivisions;
  23231. data.type = this.type;
  23232. return data;
  23233. }
  23234. /**
  23235. * Deserializes the curve from the given JSON.
  23236. *
  23237. * @param {Object} json - The JSON holding the serialized curve.
  23238. * @return {Curve} A reference to this curve.
  23239. */
  23240. fromJSON( json ) {
  23241. this.arcLengthDivisions = json.arcLengthDivisions;
  23242. return this;
  23243. }
  23244. }
  23245. /**
  23246. * A curve representing an ellipse.
  23247. *
  23248. * ```js
  23249. * const curve = new THREE.EllipseCurve(
  23250. * 0, 0,
  23251. * 10, 10,
  23252. * 0, 2 * Math.PI,
  23253. * false,
  23254. * 0
  23255. * );
  23256. *
  23257. * const points = curve.getPoints( 50 );
  23258. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23259. *
  23260. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23261. *
  23262. * // Create the final object to add to the scene
  23263. * const ellipse = new THREE.Line( geometry, material );
  23264. * ```
  23265. *
  23266. * @augments Curve
  23267. */
  23268. class EllipseCurve extends Curve {
  23269. /**
  23270. * Constructs a new ellipse curve.
  23271. *
  23272. * @param {number} [aX=0] - The X center of the ellipse.
  23273. * @param {number} [aY=0] - The Y center of the ellipse.
  23274. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  23275. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  23276. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23277. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23278. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23279. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23280. */
  23281. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  23282. super();
  23283. /**
  23284. * This flag can be used for type testing.
  23285. *
  23286. * @type {boolean}
  23287. * @readonly
  23288. * @default true
  23289. */
  23290. this.isEllipseCurve = true;
  23291. this.type = 'EllipseCurve';
  23292. /**
  23293. * The X center of the ellipse.
  23294. *
  23295. * @type {number}
  23296. * @default 0
  23297. */
  23298. this.aX = aX;
  23299. /**
  23300. * The Y center of the ellipse.
  23301. *
  23302. * @type {number}
  23303. * @default 0
  23304. */
  23305. this.aY = aY;
  23306. /**
  23307. * The radius of the ellipse in the x direction.
  23308. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  23309. *
  23310. * @type {number}
  23311. * @default 1
  23312. */
  23313. this.xRadius = xRadius;
  23314. /**
  23315. * The radius of the ellipse in the y direction.
  23316. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  23317. *
  23318. * @type {number}
  23319. * @default 1
  23320. */
  23321. this.yRadius = yRadius;
  23322. /**
  23323. * The start angle of the curve in radians starting from the positive X axis.
  23324. *
  23325. * @type {number}
  23326. * @default 0
  23327. */
  23328. this.aStartAngle = aStartAngle;
  23329. /**
  23330. * The end angle of the curve in radians starting from the positive X axis.
  23331. *
  23332. * @type {number}
  23333. * @default Math.PI*2
  23334. */
  23335. this.aEndAngle = aEndAngle;
  23336. /**
  23337. * Whether the ellipse is drawn clockwise or not.
  23338. *
  23339. * @type {boolean}
  23340. * @default false
  23341. */
  23342. this.aClockwise = aClockwise;
  23343. /**
  23344. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23345. *
  23346. * @type {number}
  23347. * @default 0
  23348. */
  23349. this.aRotation = aRotation;
  23350. }
  23351. /**
  23352. * Returns a point on the curve.
  23353. *
  23354. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23355. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23356. * @return {Vector2} The position on the curve.
  23357. */
  23358. getPoint( t, optionalTarget = new Vector2() ) {
  23359. const point = optionalTarget;
  23360. const twoPi = Math.PI * 2;
  23361. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23362. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23363. // ensures that deltaAngle is 0 .. 2 PI
  23364. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23365. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23366. if ( deltaAngle < Number.EPSILON ) {
  23367. if ( samePoints ) {
  23368. deltaAngle = 0;
  23369. } else {
  23370. deltaAngle = twoPi;
  23371. }
  23372. }
  23373. if ( this.aClockwise === true && ! samePoints ) {
  23374. if ( deltaAngle === twoPi ) {
  23375. deltaAngle = - twoPi;
  23376. } else {
  23377. deltaAngle = deltaAngle - twoPi;
  23378. }
  23379. }
  23380. const angle = this.aStartAngle + t * deltaAngle;
  23381. let x = this.aX + this.xRadius * Math.cos( angle );
  23382. let y = this.aY + this.yRadius * Math.sin( angle );
  23383. if ( this.aRotation !== 0 ) {
  23384. const cos = Math.cos( this.aRotation );
  23385. const sin = Math.sin( this.aRotation );
  23386. const tx = x - this.aX;
  23387. const ty = y - this.aY;
  23388. // Rotate the point about the center of the ellipse.
  23389. x = tx * cos - ty * sin + this.aX;
  23390. y = tx * sin + ty * cos + this.aY;
  23391. }
  23392. return point.set( x, y );
  23393. }
  23394. copy( source ) {
  23395. super.copy( source );
  23396. this.aX = source.aX;
  23397. this.aY = source.aY;
  23398. this.xRadius = source.xRadius;
  23399. this.yRadius = source.yRadius;
  23400. this.aStartAngle = source.aStartAngle;
  23401. this.aEndAngle = source.aEndAngle;
  23402. this.aClockwise = source.aClockwise;
  23403. this.aRotation = source.aRotation;
  23404. return this;
  23405. }
  23406. toJSON() {
  23407. const data = super.toJSON();
  23408. data.aX = this.aX;
  23409. data.aY = this.aY;
  23410. data.xRadius = this.xRadius;
  23411. data.yRadius = this.yRadius;
  23412. data.aStartAngle = this.aStartAngle;
  23413. data.aEndAngle = this.aEndAngle;
  23414. data.aClockwise = this.aClockwise;
  23415. data.aRotation = this.aRotation;
  23416. return data;
  23417. }
  23418. fromJSON( json ) {
  23419. super.fromJSON( json );
  23420. this.aX = json.aX;
  23421. this.aY = json.aY;
  23422. this.xRadius = json.xRadius;
  23423. this.yRadius = json.yRadius;
  23424. this.aStartAngle = json.aStartAngle;
  23425. this.aEndAngle = json.aEndAngle;
  23426. this.aClockwise = json.aClockwise;
  23427. this.aRotation = json.aRotation;
  23428. return this;
  23429. }
  23430. }
  23431. /**
  23432. * A curve representing an arc.
  23433. *
  23434. * @augments EllipseCurve
  23435. */
  23436. class ArcCurve extends EllipseCurve {
  23437. /**
  23438. * Constructs a new arc curve.
  23439. *
  23440. * @param {number} [aX=0] - The X center of the ellipse.
  23441. * @param {number} [aY=0] - The Y center of the ellipse.
  23442. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  23443. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23444. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23445. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23446. */
  23447. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23448. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23449. /**
  23450. * This flag can be used for type testing.
  23451. *
  23452. * @type {boolean}
  23453. * @readonly
  23454. * @default true
  23455. */
  23456. this.isArcCurve = true;
  23457. this.type = 'ArcCurve';
  23458. }
  23459. }
  23460. function CubicPoly() {
  23461. /**
  23462. * Centripetal CatmullRom Curve - which is useful for avoiding
  23463. * cusps and self-intersections in non-uniform catmull rom curves.
  23464. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23465. *
  23466. * curve.type accepts centripetal(default), chordal and catmullrom
  23467. * curve.tension is used for catmullrom which defaults to 0.5
  23468. */
  23469. /*
  23470. Based on an optimized c++ solution in
  23471. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23472. - http://ideone.com/NoEbVM
  23473. This CubicPoly class could be used for reusing some variables and calculations,
  23474. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23475. which can be placed in CurveUtils.
  23476. */
  23477. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23478. /*
  23479. * Compute coefficients for a cubic polynomial
  23480. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23481. * such that
  23482. * p(0) = x0, p(1) = x1
  23483. * and
  23484. * p'(0) = t0, p'(1) = t1.
  23485. */
  23486. function init( x0, x1, t0, t1 ) {
  23487. c0 = x0;
  23488. c1 = t0;
  23489. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23490. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23491. }
  23492. return {
  23493. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23494. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23495. },
  23496. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23497. // compute tangents when parameterized in [t1,t2]
  23498. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23499. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23500. // rescale tangents for parametrization in [0,1]
  23501. t1 *= dt1;
  23502. t2 *= dt1;
  23503. init( x1, x2, t1, t2 );
  23504. },
  23505. calc: function ( t ) {
  23506. const t2 = t * t;
  23507. const t3 = t2 * t;
  23508. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23509. }
  23510. };
  23511. }
  23512. //
  23513. const tmp = /*@__PURE__*/ new Vector3();
  23514. const px = /*@__PURE__*/ new CubicPoly();
  23515. const py = /*@__PURE__*/ new CubicPoly();
  23516. const pz = /*@__PURE__*/ new CubicPoly();
  23517. /**
  23518. * A curve representing a Catmull-Rom spline.
  23519. *
  23520. * ```js
  23521. * //Create a closed wavey loop
  23522. * const curve = new THREE.CatmullRomCurve3( [
  23523. * new THREE.Vector3( -10, 0, 10 ),
  23524. * new THREE.Vector3( -5, 5, 5 ),
  23525. * new THREE.Vector3( 0, 0, 0 ),
  23526. * new THREE.Vector3( 5, -5, 5 ),
  23527. * new THREE.Vector3( 10, 0, 10 )
  23528. * ] );
  23529. *
  23530. * const points = curve.getPoints( 50 );
  23531. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23532. *
  23533. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23534. *
  23535. * // Create the final object to add to the scene
  23536. * const curveObject = new THREE.Line( geometry, material );
  23537. * ```
  23538. *
  23539. * @augments Curve
  23540. */
  23541. class CatmullRomCurve3 extends Curve {
  23542. /**
  23543. * Constructs a new Catmull-Rom curve.
  23544. *
  23545. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  23546. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23547. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  23548. * @param {number} [tension=0.5] - Tension of the curve.
  23549. */
  23550. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23551. super();
  23552. /**
  23553. * This flag can be used for type testing.
  23554. *
  23555. * @type {boolean}
  23556. * @readonly
  23557. * @default true
  23558. */
  23559. this.isCatmullRomCurve3 = true;
  23560. this.type = 'CatmullRomCurve3';
  23561. /**
  23562. * An array of 3D points defining the curve.
  23563. *
  23564. * @type {Array<Vector3>}
  23565. */
  23566. this.points = points;
  23567. /**
  23568. * Whether the curve is closed or not.
  23569. *
  23570. * @type {boolean}
  23571. * @default false
  23572. */
  23573. this.closed = closed;
  23574. /**
  23575. * The curve type.
  23576. *
  23577. * @type {('centripetal'|'chordal'|'catmullrom')}
  23578. * @default 'centripetal'
  23579. */
  23580. this.curveType = curveType;
  23581. /**
  23582. * Tension of the curve.
  23583. *
  23584. * @type {number}
  23585. * @default 0.5
  23586. */
  23587. this.tension = tension;
  23588. }
  23589. /**
  23590. * Returns a point on the curve.
  23591. *
  23592. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23593. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23594. * @return {Vector3} The position on the curve.
  23595. */
  23596. getPoint( t, optionalTarget = new Vector3() ) {
  23597. const point = optionalTarget;
  23598. const points = this.points;
  23599. const l = points.length;
  23600. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23601. let intPoint = Math.floor( p );
  23602. let weight = p - intPoint;
  23603. if ( this.closed ) {
  23604. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23605. } else if ( weight === 0 && intPoint === l - 1 ) {
  23606. intPoint = l - 2;
  23607. weight = 1;
  23608. }
  23609. let p0, p3; // 4 points (p1 & p2 defined below)
  23610. if ( this.closed || intPoint > 0 ) {
  23611. p0 = points[ ( intPoint - 1 ) % l ];
  23612. } else {
  23613. // extrapolate first point
  23614. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23615. p0 = tmp;
  23616. }
  23617. const p1 = points[ intPoint % l ];
  23618. const p2 = points[ ( intPoint + 1 ) % l ];
  23619. if ( this.closed || intPoint + 2 < l ) {
  23620. p3 = points[ ( intPoint + 2 ) % l ];
  23621. } else {
  23622. // extrapolate last point
  23623. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23624. p3 = tmp;
  23625. }
  23626. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23627. // init Centripetal / Chordal Catmull-Rom
  23628. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23629. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23630. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23631. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23632. // safety check for repeated points
  23633. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23634. if ( dt0 < 1e-4 ) dt0 = dt1;
  23635. if ( dt2 < 1e-4 ) dt2 = dt1;
  23636. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  23637. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  23638. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  23639. } else if ( this.curveType === 'catmullrom' ) {
  23640. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  23641. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  23642. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  23643. }
  23644. point.set(
  23645. px.calc( weight ),
  23646. py.calc( weight ),
  23647. pz.calc( weight )
  23648. );
  23649. return point;
  23650. }
  23651. copy( source ) {
  23652. super.copy( source );
  23653. this.points = [];
  23654. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23655. const point = source.points[ i ];
  23656. this.points.push( point.clone() );
  23657. }
  23658. this.closed = source.closed;
  23659. this.curveType = source.curveType;
  23660. this.tension = source.tension;
  23661. return this;
  23662. }
  23663. toJSON() {
  23664. const data = super.toJSON();
  23665. data.points = [];
  23666. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23667. const point = this.points[ i ];
  23668. data.points.push( point.toArray() );
  23669. }
  23670. data.closed = this.closed;
  23671. data.curveType = this.curveType;
  23672. data.tension = this.tension;
  23673. return data;
  23674. }
  23675. fromJSON( json ) {
  23676. super.fromJSON( json );
  23677. this.points = [];
  23678. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23679. const point = json.points[ i ];
  23680. this.points.push( new Vector3().fromArray( point ) );
  23681. }
  23682. this.closed = json.closed;
  23683. this.curveType = json.curveType;
  23684. this.tension = json.tension;
  23685. return this;
  23686. }
  23687. }
  23688. // Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  23689. /**
  23690. * Computes a point on a Catmull-Rom spline.
  23691. *
  23692. * @param {number} t - The interpolation factor.
  23693. * @param {number} p0 - The first control point.
  23694. * @param {number} p1 - The second control point.
  23695. * @param {number} p2 - The third control point.
  23696. * @param {number} p3 - The fourth control point.
  23697. * @return {number} The calculated point on a Catmull-Rom spline.
  23698. */
  23699. function CatmullRom( t, p0, p1, p2, p3 ) {
  23700. const v0 = ( p2 - p0 ) * 0.5;
  23701. const v1 = ( p3 - p1 ) * 0.5;
  23702. const t2 = t * t;
  23703. const t3 = t * t2;
  23704. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23705. }
  23706. //
  23707. function QuadraticBezierP0( t, p ) {
  23708. const k = 1 - t;
  23709. return k * k * p;
  23710. }
  23711. function QuadraticBezierP1( t, p ) {
  23712. return 2 * ( 1 - t ) * t * p;
  23713. }
  23714. function QuadraticBezierP2( t, p ) {
  23715. return t * t * p;
  23716. }
  23717. /**
  23718. * Computes a point on a Quadratic Bezier curve.
  23719. *
  23720. * @param {number} t - The interpolation factor.
  23721. * @param {number} p0 - The first control point.
  23722. * @param {number} p1 - The second control point.
  23723. * @param {number} p2 - The third control point.
  23724. * @return {number} The calculated point on a Quadratic Bezier curve.
  23725. */
  23726. function QuadraticBezier( t, p0, p1, p2 ) {
  23727. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  23728. QuadraticBezierP2( t, p2 );
  23729. }
  23730. //
  23731. function CubicBezierP0( t, p ) {
  23732. const k = 1 - t;
  23733. return k * k * k * p;
  23734. }
  23735. function CubicBezierP1( t, p ) {
  23736. const k = 1 - t;
  23737. return 3 * k * k * t * p;
  23738. }
  23739. function CubicBezierP2( t, p ) {
  23740. return 3 * ( 1 - t ) * t * t * p;
  23741. }
  23742. function CubicBezierP3( t, p ) {
  23743. return t * t * t * p;
  23744. }
  23745. /**
  23746. * Computes a point on a Cubic Bezier curve.
  23747. *
  23748. * @param {number} t - The interpolation factor.
  23749. * @param {number} p0 - The first control point.
  23750. * @param {number} p1 - The second control point.
  23751. * @param {number} p2 - The third control point.
  23752. * @param {number} p3 - The fourth control point.
  23753. * @return {number} The calculated point on a Cubic Bezier curve.
  23754. */
  23755. function CubicBezier( t, p0, p1, p2, p3 ) {
  23756. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  23757. CubicBezierP3( t, p3 );
  23758. }
  23759. /**
  23760. * A curve representing a 2D Cubic Bezier curve.
  23761. *
  23762. * ```js
  23763. * const curve = new THREE.CubicBezierCurve(
  23764. * new THREE.Vector2( - 0, 0 ),
  23765. * new THREE.Vector2( - 5, 15 ),
  23766. * new THREE.Vector2( 20, 15 ),
  23767. * new THREE.Vector2( 10, 0 )
  23768. * );
  23769. *
  23770. * const points = curve.getPoints( 50 );
  23771. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23772. *
  23773. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23774. *
  23775. * // Create the final object to add to the scene
  23776. * const curveObject = new THREE.Line( geometry, material );
  23777. * ```
  23778. *
  23779. * @augments Curve
  23780. */
  23781. class CubicBezierCurve extends Curve {
  23782. /**
  23783. * Constructs a new Cubic Bezier curve.
  23784. *
  23785. * @param {Vector2} [v0] - The start point.
  23786. * @param {Vector2} [v1] - The first control point.
  23787. * @param {Vector2} [v2] - The second control point.
  23788. * @param {Vector2} [v3] - The end point.
  23789. */
  23790. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  23791. super();
  23792. /**
  23793. * This flag can be used for type testing.
  23794. *
  23795. * @type {boolean}
  23796. * @readonly
  23797. * @default true
  23798. */
  23799. this.isCubicBezierCurve = true;
  23800. this.type = 'CubicBezierCurve';
  23801. /**
  23802. * The start point.
  23803. *
  23804. * @type {Vector2}
  23805. */
  23806. this.v0 = v0;
  23807. /**
  23808. * The first control point.
  23809. *
  23810. * @type {Vector2}
  23811. */
  23812. this.v1 = v1;
  23813. /**
  23814. * The second control point.
  23815. *
  23816. * @type {Vector2}
  23817. */
  23818. this.v2 = v2;
  23819. /**
  23820. * The end point.
  23821. *
  23822. * @type {Vector2}
  23823. */
  23824. this.v3 = v3;
  23825. }
  23826. /**
  23827. * Returns a point on the curve.
  23828. *
  23829. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23830. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23831. * @return {Vector2} The position on the curve.
  23832. */
  23833. getPoint( t, optionalTarget = new Vector2() ) {
  23834. const point = optionalTarget;
  23835. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23836. point.set(
  23837. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23838. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  23839. );
  23840. return point;
  23841. }
  23842. copy( source ) {
  23843. super.copy( source );
  23844. this.v0.copy( source.v0 );
  23845. this.v1.copy( source.v1 );
  23846. this.v2.copy( source.v2 );
  23847. this.v3.copy( source.v3 );
  23848. return this;
  23849. }
  23850. toJSON() {
  23851. const data = super.toJSON();
  23852. data.v0 = this.v0.toArray();
  23853. data.v1 = this.v1.toArray();
  23854. data.v2 = this.v2.toArray();
  23855. data.v3 = this.v3.toArray();
  23856. return data;
  23857. }
  23858. fromJSON( json ) {
  23859. super.fromJSON( json );
  23860. this.v0.fromArray( json.v0 );
  23861. this.v1.fromArray( json.v1 );
  23862. this.v2.fromArray( json.v2 );
  23863. this.v3.fromArray( json.v3 );
  23864. return this;
  23865. }
  23866. }
  23867. /**
  23868. * A curve representing a 3D Cubic Bezier curve.
  23869. *
  23870. * @augments Curve
  23871. */
  23872. class CubicBezierCurve3 extends Curve {
  23873. /**
  23874. * Constructs a new Cubic Bezier curve.
  23875. *
  23876. * @param {Vector3} [v0] - The start point.
  23877. * @param {Vector3} [v1] - The first control point.
  23878. * @param {Vector3} [v2] - The second control point.
  23879. * @param {Vector3} [v3] - The end point.
  23880. */
  23881. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  23882. super();
  23883. /**
  23884. * This flag can be used for type testing.
  23885. *
  23886. * @type {boolean}
  23887. * @readonly
  23888. * @default true
  23889. */
  23890. this.isCubicBezierCurve3 = true;
  23891. this.type = 'CubicBezierCurve3';
  23892. /**
  23893. * The start point.
  23894. *
  23895. * @type {Vector3}
  23896. */
  23897. this.v0 = v0;
  23898. /**
  23899. * The first control point.
  23900. *
  23901. * @type {Vector3}
  23902. */
  23903. this.v1 = v1;
  23904. /**
  23905. * The second control point.
  23906. *
  23907. * @type {Vector3}
  23908. */
  23909. this.v2 = v2;
  23910. /**
  23911. * The end point.
  23912. *
  23913. * @type {Vector3}
  23914. */
  23915. this.v3 = v3;
  23916. }
  23917. /**
  23918. * Returns a point on the curve.
  23919. *
  23920. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23921. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23922. * @return {Vector3} The position on the curve.
  23923. */
  23924. getPoint( t, optionalTarget = new Vector3() ) {
  23925. const point = optionalTarget;
  23926. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23927. point.set(
  23928. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23929. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  23930. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  23931. );
  23932. return point;
  23933. }
  23934. copy( source ) {
  23935. super.copy( source );
  23936. this.v0.copy( source.v0 );
  23937. this.v1.copy( source.v1 );
  23938. this.v2.copy( source.v2 );
  23939. this.v3.copy( source.v3 );
  23940. return this;
  23941. }
  23942. toJSON() {
  23943. const data = super.toJSON();
  23944. data.v0 = this.v0.toArray();
  23945. data.v1 = this.v1.toArray();
  23946. data.v2 = this.v2.toArray();
  23947. data.v3 = this.v3.toArray();
  23948. return data;
  23949. }
  23950. fromJSON( json ) {
  23951. super.fromJSON( json );
  23952. this.v0.fromArray( json.v0 );
  23953. this.v1.fromArray( json.v1 );
  23954. this.v2.fromArray( json.v2 );
  23955. this.v3.fromArray( json.v3 );
  23956. return this;
  23957. }
  23958. }
  23959. /**
  23960. * A curve representing a 2D line segment.
  23961. *
  23962. * @augments Curve
  23963. */
  23964. class LineCurve extends Curve {
  23965. /**
  23966. * Constructs a new line curve.
  23967. *
  23968. * @param {Vector2} [v1] - The start point.
  23969. * @param {Vector2} [v2] - The end point.
  23970. */
  23971. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  23972. super();
  23973. /**
  23974. * This flag can be used for type testing.
  23975. *
  23976. * @type {boolean}
  23977. * @readonly
  23978. * @default true
  23979. */
  23980. this.isLineCurve = true;
  23981. this.type = 'LineCurve';
  23982. /**
  23983. * The start point.
  23984. *
  23985. * @type {Vector2}
  23986. */
  23987. this.v1 = v1;
  23988. /**
  23989. * The end point.
  23990. *
  23991. * @type {Vector2}
  23992. */
  23993. this.v2 = v2;
  23994. }
  23995. /**
  23996. * Returns a point on the line.
  23997. *
  23998. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  23999. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24000. * @return {Vector2} The position on the line.
  24001. */
  24002. getPoint( t, optionalTarget = new Vector2() ) {
  24003. const point = optionalTarget;
  24004. if ( t === 1 ) {
  24005. point.copy( this.v2 );
  24006. } else {
  24007. point.copy( this.v2 ).sub( this.v1 );
  24008. point.multiplyScalar( t ).add( this.v1 );
  24009. }
  24010. return point;
  24011. }
  24012. // Line curve is linear, so we can overwrite default getPointAt
  24013. getPointAt( u, optionalTarget ) {
  24014. return this.getPoint( u, optionalTarget );
  24015. }
  24016. getTangent( t, optionalTarget = new Vector2() ) {
  24017. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24018. }
  24019. getTangentAt( u, optionalTarget ) {
  24020. return this.getTangent( u, optionalTarget );
  24021. }
  24022. copy( source ) {
  24023. super.copy( source );
  24024. this.v1.copy( source.v1 );
  24025. this.v2.copy( source.v2 );
  24026. return this;
  24027. }
  24028. toJSON() {
  24029. const data = super.toJSON();
  24030. data.v1 = this.v1.toArray();
  24031. data.v2 = this.v2.toArray();
  24032. return data;
  24033. }
  24034. fromJSON( json ) {
  24035. super.fromJSON( json );
  24036. this.v1.fromArray( json.v1 );
  24037. this.v2.fromArray( json.v2 );
  24038. return this;
  24039. }
  24040. }
  24041. /**
  24042. * A curve representing a 3D line segment.
  24043. *
  24044. * @augments Curve
  24045. */
  24046. class LineCurve3 extends Curve {
  24047. /**
  24048. * Constructs a new line curve.
  24049. *
  24050. * @param {Vector3} [v1] - The start point.
  24051. * @param {Vector3} [v2] - The end point.
  24052. */
  24053. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  24054. super();
  24055. /**
  24056. * This flag can be used for type testing.
  24057. *
  24058. * @type {boolean}
  24059. * @readonly
  24060. * @default true
  24061. */
  24062. this.isLineCurve3 = true;
  24063. this.type = 'LineCurve3';
  24064. /**
  24065. * The start point.
  24066. *
  24067. * @type {Vector3}
  24068. */
  24069. this.v1 = v1;
  24070. /**
  24071. * The end point.
  24072. *
  24073. * @type {Vector2}
  24074. */
  24075. this.v2 = v2;
  24076. }
  24077. /**
  24078. * Returns a point on the line.
  24079. *
  24080. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24081. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24082. * @return {Vector3} The position on the line.
  24083. */
  24084. getPoint( t, optionalTarget = new Vector3() ) {
  24085. const point = optionalTarget;
  24086. if ( t === 1 ) {
  24087. point.copy( this.v2 );
  24088. } else {
  24089. point.copy( this.v2 ).sub( this.v1 );
  24090. point.multiplyScalar( t ).add( this.v1 );
  24091. }
  24092. return point;
  24093. }
  24094. // Line curve is linear, so we can overwrite default getPointAt
  24095. getPointAt( u, optionalTarget ) {
  24096. return this.getPoint( u, optionalTarget );
  24097. }
  24098. getTangent( t, optionalTarget = new Vector3() ) {
  24099. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24100. }
  24101. getTangentAt( u, optionalTarget ) {
  24102. return this.getTangent( u, optionalTarget );
  24103. }
  24104. copy( source ) {
  24105. super.copy( source );
  24106. this.v1.copy( source.v1 );
  24107. this.v2.copy( source.v2 );
  24108. return this;
  24109. }
  24110. toJSON() {
  24111. const data = super.toJSON();
  24112. data.v1 = this.v1.toArray();
  24113. data.v2 = this.v2.toArray();
  24114. return data;
  24115. }
  24116. fromJSON( json ) {
  24117. super.fromJSON( json );
  24118. this.v1.fromArray( json.v1 );
  24119. this.v2.fromArray( json.v2 );
  24120. return this;
  24121. }
  24122. }
  24123. /**
  24124. * A curve representing a 2D Quadratic Bezier curve.
  24125. *
  24126. * ```js
  24127. * const curve = new THREE.QuadraticBezierCurve(
  24128. * new THREE.Vector2( - 10, 0 ),
  24129. * new THREE.Vector2( 20, 15 ),
  24130. * new THREE.Vector2( 10, 0 )
  24131. * )
  24132. *
  24133. * const points = curve.getPoints( 50 );
  24134. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24135. *
  24136. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24137. *
  24138. * // Create the final object to add to the scene
  24139. * const curveObject = new THREE.Line( geometry, material );
  24140. * ```
  24141. *
  24142. * @augments Curve
  24143. */
  24144. class QuadraticBezierCurve extends Curve {
  24145. /**
  24146. * Constructs a new Quadratic Bezier curve.
  24147. *
  24148. * @param {Vector2} [v0] - The start point.
  24149. * @param {Vector2} [v1] - The control point.
  24150. * @param {Vector2} [v2] - The end point.
  24151. */
  24152. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  24153. super();
  24154. /**
  24155. * This flag can be used for type testing.
  24156. *
  24157. * @type {boolean}
  24158. * @readonly
  24159. * @default true
  24160. */
  24161. this.isQuadraticBezierCurve = true;
  24162. this.type = 'QuadraticBezierCurve';
  24163. /**
  24164. * The start point.
  24165. *
  24166. * @type {Vector2}
  24167. */
  24168. this.v0 = v0;
  24169. /**
  24170. * The control point.
  24171. *
  24172. * @type {Vector2}
  24173. */
  24174. this.v1 = v1;
  24175. /**
  24176. * The end point.
  24177. *
  24178. * @type {Vector2}
  24179. */
  24180. this.v2 = v2;
  24181. }
  24182. /**
  24183. * Returns a point on the curve.
  24184. *
  24185. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24186. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24187. * @return {Vector2} The position on the curve.
  24188. */
  24189. getPoint( t, optionalTarget = new Vector2() ) {
  24190. const point = optionalTarget;
  24191. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24192. point.set(
  24193. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24194. QuadraticBezier( t, v0.y, v1.y, v2.y )
  24195. );
  24196. return point;
  24197. }
  24198. copy( source ) {
  24199. super.copy( source );
  24200. this.v0.copy( source.v0 );
  24201. this.v1.copy( source.v1 );
  24202. this.v2.copy( source.v2 );
  24203. return this;
  24204. }
  24205. toJSON() {
  24206. const data = super.toJSON();
  24207. data.v0 = this.v0.toArray();
  24208. data.v1 = this.v1.toArray();
  24209. data.v2 = this.v2.toArray();
  24210. return data;
  24211. }
  24212. fromJSON( json ) {
  24213. super.fromJSON( json );
  24214. this.v0.fromArray( json.v0 );
  24215. this.v1.fromArray( json.v1 );
  24216. this.v2.fromArray( json.v2 );
  24217. return this;
  24218. }
  24219. }
  24220. /**
  24221. * A curve representing a 3D Quadratic Bezier curve.
  24222. *
  24223. * @augments Curve
  24224. */
  24225. class QuadraticBezierCurve3 extends Curve {
  24226. /**
  24227. * Constructs a new Quadratic Bezier curve.
  24228. *
  24229. * @param {Vector3} [v0] - The start point.
  24230. * @param {Vector3} [v1] - The control point.
  24231. * @param {Vector3} [v2] - The end point.
  24232. */
  24233. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  24234. super();
  24235. /**
  24236. * This flag can be used for type testing.
  24237. *
  24238. * @type {boolean}
  24239. * @readonly
  24240. * @default true
  24241. */
  24242. this.isQuadraticBezierCurve3 = true;
  24243. this.type = 'QuadraticBezierCurve3';
  24244. /**
  24245. * The start point.
  24246. *
  24247. * @type {Vector3}
  24248. */
  24249. this.v0 = v0;
  24250. /**
  24251. * The control point.
  24252. *
  24253. * @type {Vector3}
  24254. */
  24255. this.v1 = v1;
  24256. /**
  24257. * The end point.
  24258. *
  24259. * @type {Vector3}
  24260. */
  24261. this.v2 = v2;
  24262. }
  24263. /**
  24264. * Returns a point on the curve.
  24265. *
  24266. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24267. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24268. * @return {Vector3} The position on the curve.
  24269. */
  24270. getPoint( t, optionalTarget = new Vector3() ) {
  24271. const point = optionalTarget;
  24272. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24273. point.set(
  24274. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24275. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  24276. QuadraticBezier( t, v0.z, v1.z, v2.z )
  24277. );
  24278. return point;
  24279. }
  24280. copy( source ) {
  24281. super.copy( source );
  24282. this.v0.copy( source.v0 );
  24283. this.v1.copy( source.v1 );
  24284. this.v2.copy( source.v2 );
  24285. return this;
  24286. }
  24287. toJSON() {
  24288. const data = super.toJSON();
  24289. data.v0 = this.v0.toArray();
  24290. data.v1 = this.v1.toArray();
  24291. data.v2 = this.v2.toArray();
  24292. return data;
  24293. }
  24294. fromJSON( json ) {
  24295. super.fromJSON( json );
  24296. this.v0.fromArray( json.v0 );
  24297. this.v1.fromArray( json.v1 );
  24298. this.v2.fromArray( json.v2 );
  24299. return this;
  24300. }
  24301. }
  24302. /**
  24303. * A curve representing a 2D spline curve.
  24304. *
  24305. * ```js
  24306. * // Create a sine-like wave
  24307. * const curve = new THREE.SplineCurve( [
  24308. * new THREE.Vector2( -10, 0 ),
  24309. * new THREE.Vector2( -5, 5 ),
  24310. * new THREE.Vector2( 0, 0 ),
  24311. * new THREE.Vector2( 5, -5 ),
  24312. * new THREE.Vector2( 10, 0 )
  24313. * ] );
  24314. *
  24315. * const points = curve.getPoints( 50 );
  24316. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24317. *
  24318. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24319. *
  24320. * // Create the final object to add to the scene
  24321. * const splineObject = new THREE.Line( geometry, material );
  24322. * ```
  24323. *
  24324. * @augments Curve
  24325. */
  24326. class SplineCurve extends Curve {
  24327. /**
  24328. * Constructs a new 2D spline curve.
  24329. *
  24330. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  24331. */
  24332. constructor( points = [] ) {
  24333. super();
  24334. /**
  24335. * This flag can be used for type testing.
  24336. *
  24337. * @type {boolean}
  24338. * @readonly
  24339. * @default true
  24340. */
  24341. this.isSplineCurve = true;
  24342. this.type = 'SplineCurve';
  24343. /**
  24344. * An array of 2D points defining the curve.
  24345. *
  24346. * @type {Array<Vector2>}
  24347. */
  24348. this.points = points;
  24349. }
  24350. /**
  24351. * Returns a point on the curve.
  24352. *
  24353. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24354. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24355. * @return {Vector2} The position on the curve.
  24356. */
  24357. getPoint( t, optionalTarget = new Vector2() ) {
  24358. const point = optionalTarget;
  24359. const points = this.points;
  24360. const p = ( points.length - 1 ) * t;
  24361. const intPoint = Math.floor( p );
  24362. const weight = p - intPoint;
  24363. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24364. const p1 = points[ intPoint ];
  24365. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24366. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24367. point.set(
  24368. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24369. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  24370. );
  24371. return point;
  24372. }
  24373. copy( source ) {
  24374. super.copy( source );
  24375. this.points = [];
  24376. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24377. const point = source.points[ i ];
  24378. this.points.push( point.clone() );
  24379. }
  24380. return this;
  24381. }
  24382. toJSON() {
  24383. const data = super.toJSON();
  24384. data.points = [];
  24385. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24386. const point = this.points[ i ];
  24387. data.points.push( point.toArray() );
  24388. }
  24389. return data;
  24390. }
  24391. fromJSON( json ) {
  24392. super.fromJSON( json );
  24393. this.points = [];
  24394. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24395. const point = json.points[ i ];
  24396. this.points.push( new Vector2().fromArray( point ) );
  24397. }
  24398. return this;
  24399. }
  24400. }
  24401. var Curves = /*#__PURE__*/Object.freeze({
  24402. __proto__: null,
  24403. ArcCurve: ArcCurve,
  24404. CatmullRomCurve3: CatmullRomCurve3,
  24405. CubicBezierCurve: CubicBezierCurve,
  24406. CubicBezierCurve3: CubicBezierCurve3,
  24407. EllipseCurve: EllipseCurve,
  24408. LineCurve: LineCurve,
  24409. LineCurve3: LineCurve3,
  24410. QuadraticBezierCurve: QuadraticBezierCurve,
  24411. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24412. SplineCurve: SplineCurve
  24413. });
  24414. /**
  24415. * A base class extending {@link Curve}. `CurvePath` is simply an
  24416. * array of connected curves, but retains the API of a curve.
  24417. *
  24418. * @augments Curve
  24419. */
  24420. class CurvePath extends Curve {
  24421. /**
  24422. * Constructs a new curve path.
  24423. */
  24424. constructor() {
  24425. super();
  24426. this.type = 'CurvePath';
  24427. /**
  24428. * An array of curves defining the
  24429. * path.
  24430. *
  24431. * @type {Array<Curve>}
  24432. */
  24433. this.curves = [];
  24434. /**
  24435. * Whether the path should automatically be closed
  24436. * by a line curve.
  24437. *
  24438. * @type {boolean}
  24439. * @default false
  24440. */
  24441. this.autoClose = false;
  24442. }
  24443. /**
  24444. * Adds a curve to this curve path.
  24445. *
  24446. * @param {Curve} curve - The curve to add.
  24447. */
  24448. add( curve ) {
  24449. this.curves.push( curve );
  24450. }
  24451. /**
  24452. * Adds a line curve to close the path.
  24453. *
  24454. * @return {CurvePath} A reference to this curve path.
  24455. */
  24456. closePath() {
  24457. // Add a line curve if start and end of lines are not connected
  24458. const startPoint = this.curves[ 0 ].getPoint( 0 );
  24459. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24460. if ( ! startPoint.equals( endPoint ) ) {
  24461. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  24462. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  24463. }
  24464. return this;
  24465. }
  24466. /**
  24467. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  24468. * for the given interpolation factor.
  24469. *
  24470. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24471. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  24472. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  24473. */
  24474. getPoint( t, optionalTarget ) {
  24475. // To get accurate point with reference to
  24476. // entire path distance at time t,
  24477. // following has to be done:
  24478. // 1. Length of each sub path have to be known
  24479. // 2. Locate and identify type of curve
  24480. // 3. Get t for the curve
  24481. // 4. Return curve.getPointAt(t')
  24482. const d = t * this.getLength();
  24483. const curveLengths = this.getCurveLengths();
  24484. let i = 0;
  24485. // To think about boundaries points.
  24486. while ( i < curveLengths.length ) {
  24487. if ( curveLengths[ i ] >= d ) {
  24488. const diff = curveLengths[ i ] - d;
  24489. const curve = this.curves[ i ];
  24490. const segmentLength = curve.getLength();
  24491. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24492. return curve.getPointAt( u, optionalTarget );
  24493. }
  24494. i ++;
  24495. }
  24496. return null;
  24497. // loop where sum != 0, sum > d , sum+1 <d
  24498. }
  24499. getLength() {
  24500. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24501. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24502. // getPoint() depends on getLength
  24503. const lens = this.getCurveLengths();
  24504. return lens[ lens.length - 1 ];
  24505. }
  24506. updateArcLengths() {
  24507. // cacheLengths must be recalculated.
  24508. this.needsUpdate = true;
  24509. this.cacheLengths = null;
  24510. this.getCurveLengths();
  24511. }
  24512. /**
  24513. * Returns list of cumulative curve lengths of the defined curves.
  24514. *
  24515. * @return {Array<number>} The curve lengths.
  24516. */
  24517. getCurveLengths() {
  24518. // Compute lengths and cache them
  24519. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24520. // We use cache values if curves and cache array are same length
  24521. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24522. return this.cacheLengths;
  24523. }
  24524. // Get length of sub-curve
  24525. // Push sums into cached array
  24526. const lengths = [];
  24527. let sums = 0;
  24528. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24529. sums += this.curves[ i ].getLength();
  24530. lengths.push( sums );
  24531. }
  24532. this.cacheLengths = lengths;
  24533. return lengths;
  24534. }
  24535. getSpacedPoints( divisions = 40 ) {
  24536. const points = [];
  24537. for ( let i = 0; i <= divisions; i ++ ) {
  24538. points.push( this.getPoint( i / divisions ) );
  24539. }
  24540. if ( this.autoClose ) {
  24541. points.push( points[ 0 ] );
  24542. }
  24543. return points;
  24544. }
  24545. getPoints( divisions = 12 ) {
  24546. const points = [];
  24547. let last;
  24548. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24549. const curve = curves[ i ];
  24550. const resolution = curve.isEllipseCurve ? divisions * 2
  24551. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  24552. : curve.isSplineCurve ? divisions * curve.points.length
  24553. : divisions;
  24554. const pts = curve.getPoints( resolution );
  24555. for ( let j = 0; j < pts.length; j ++ ) {
  24556. const point = pts[ j ];
  24557. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24558. points.push( point );
  24559. last = point;
  24560. }
  24561. }
  24562. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24563. points.push( points[ 0 ] );
  24564. }
  24565. return points;
  24566. }
  24567. copy( source ) {
  24568. super.copy( source );
  24569. this.curves = [];
  24570. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  24571. const curve = source.curves[ i ];
  24572. this.curves.push( curve.clone() );
  24573. }
  24574. this.autoClose = source.autoClose;
  24575. return this;
  24576. }
  24577. toJSON() {
  24578. const data = super.toJSON();
  24579. data.autoClose = this.autoClose;
  24580. data.curves = [];
  24581. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24582. const curve = this.curves[ i ];
  24583. data.curves.push( curve.toJSON() );
  24584. }
  24585. return data;
  24586. }
  24587. fromJSON( json ) {
  24588. super.fromJSON( json );
  24589. this.autoClose = json.autoClose;
  24590. this.curves = [];
  24591. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  24592. const curve = json.curves[ i ];
  24593. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24594. }
  24595. return this;
  24596. }
  24597. }
  24598. /**
  24599. * A 2D path representation. The class provides methods for creating paths
  24600. * and contours of 2D shapes similar to the 2D Canvas API.
  24601. *
  24602. * ```js
  24603. * const path = new THREE.Path();
  24604. *
  24605. * path.lineTo( 0, 0.8 );
  24606. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  24607. * path.lineTo( 1, 1 );
  24608. *
  24609. * const points = path.getPoints();
  24610. *
  24611. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24612. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  24613. *
  24614. * const line = new THREE.Line( geometry, material );
  24615. * scene.add( line );
  24616. * ```
  24617. *
  24618. * @augments CurvePath
  24619. */
  24620. class Path extends CurvePath {
  24621. /**
  24622. * Constructs a new path.
  24623. *
  24624. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  24625. */
  24626. constructor( points ) {
  24627. super();
  24628. this.type = 'Path';
  24629. /**
  24630. * The current offset of the path. Any new curve added will start here.
  24631. *
  24632. * @type {Vector2}
  24633. */
  24634. this.currentPoint = new Vector2();
  24635. if ( points ) {
  24636. this.setFromPoints( points );
  24637. }
  24638. }
  24639. /**
  24640. * Creates a path from the given list of points. The points are added
  24641. * to the path as instances of {@link LineCurve}.
  24642. *
  24643. * @param {Array<Vector2>} points - An array of 2D points.
  24644. * @return {Path} A reference to this path.
  24645. */
  24646. setFromPoints( points ) {
  24647. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  24648. for ( let i = 1, l = points.length; i < l; i ++ ) {
  24649. this.lineTo( points[ i ].x, points[ i ].y );
  24650. }
  24651. return this;
  24652. }
  24653. /**
  24654. * Moves {@link Path#currentPoint} to the given point.
  24655. *
  24656. * @param {number} x - The x coordinate.
  24657. * @param {number} y - The y coordinate.
  24658. * @return {Path} A reference to this path.
  24659. */
  24660. moveTo( x, y ) {
  24661. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  24662. return this;
  24663. }
  24664. /**
  24665. * Adds an instance of {@link LineCurve} to the path by connecting
  24666. * the current point with the given one.
  24667. *
  24668. * @param {number} x - The x coordinate of the end point.
  24669. * @param {number} y - The y coordinate of the end point.
  24670. * @return {Path} A reference to this path.
  24671. */
  24672. lineTo( x, y ) {
  24673. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  24674. this.curves.push( curve );
  24675. this.currentPoint.set( x, y );
  24676. return this;
  24677. }
  24678. /**
  24679. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  24680. * the current point with the given one.
  24681. *
  24682. * @param {number} aCPx - The x coordinate of the control point.
  24683. * @param {number} aCPy - The y coordinate of the control point.
  24684. * @param {number} aX - The x coordinate of the end point.
  24685. * @param {number} aY - The y coordinate of the end point.
  24686. * @return {Path} A reference to this path.
  24687. */
  24688. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  24689. const curve = new QuadraticBezierCurve(
  24690. this.currentPoint.clone(),
  24691. new Vector2( aCPx, aCPy ),
  24692. new Vector2( aX, aY )
  24693. );
  24694. this.curves.push( curve );
  24695. this.currentPoint.set( aX, aY );
  24696. return this;
  24697. }
  24698. /**
  24699. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  24700. * the current point with the given one.
  24701. *
  24702. * @param {number} aCP1x - The x coordinate of the first control point.
  24703. * @param {number} aCP1y - The y coordinate of the first control point.
  24704. * @param {number} aCP2x - The x coordinate of the second control point.
  24705. * @param {number} aCP2y - The y coordinate of the second control point.
  24706. * @param {number} aX - The x coordinate of the end point.
  24707. * @param {number} aY - The y coordinate of the end point.
  24708. * @return {Path} A reference to this path.
  24709. */
  24710. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24711. const curve = new CubicBezierCurve(
  24712. this.currentPoint.clone(),
  24713. new Vector2( aCP1x, aCP1y ),
  24714. new Vector2( aCP2x, aCP2y ),
  24715. new Vector2( aX, aY )
  24716. );
  24717. this.curves.push( curve );
  24718. this.currentPoint.set( aX, aY );
  24719. return this;
  24720. }
  24721. /**
  24722. * Adds an instance of {@link SplineCurve} to the path by connecting
  24723. * the current point with the given list of points.
  24724. *
  24725. * @param {Array<Vector2>} pts - An array of points in 2D space.
  24726. * @return {Path} A reference to this path.
  24727. */
  24728. splineThru( pts ) {
  24729. const npts = [ this.currentPoint.clone() ].concat( pts );
  24730. const curve = new SplineCurve( npts );
  24731. this.curves.push( curve );
  24732. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24733. return this;
  24734. }
  24735. /**
  24736. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  24737. * to the current point.
  24738. *
  24739. * @param {number} aX - The x coordinate of the center of the arc offsetted from the previous curve.
  24740. * @param {number} aY - The y coordinate of the center of the arc offsetted from the previous curve.
  24741. * @param {number} aRadius - The radius of the arc.
  24742. * @param {number} aStartAngle - The start angle in radians.
  24743. * @param {number} aEndAngle - The end angle in radians.
  24744. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24745. * @return {Path} A reference to this path.
  24746. */
  24747. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24748. const x0 = this.currentPoint.x;
  24749. const y0 = this.currentPoint.y;
  24750. this.absarc( aX + x0, aY + y0, aRadius,
  24751. aStartAngle, aEndAngle, aClockwise );
  24752. return this;
  24753. }
  24754. /**
  24755. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  24756. *
  24757. * @param {number} aX - The x coordinate of the center of the arc.
  24758. * @param {number} aY - The y coordinate of the center of the arc.
  24759. * @param {number} aRadius - The radius of the arc.
  24760. * @param {number} aStartAngle - The start angle in radians.
  24761. * @param {number} aEndAngle - The end angle in radians.
  24762. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24763. * @return {Path} A reference to this path.
  24764. */
  24765. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24766. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24767. return this;
  24768. }
  24769. /**
  24770. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  24771. * to the current point
  24772. *
  24773. * @param {number} aX - The x coordinate of the center of the ellipse offsetted from the previous curve.
  24774. * @param {number} aY - The y coordinate of the center of the ellipse offsetted from the previous curve.
  24775. * @param {number} xRadius - The radius of the ellipse in the x axis.
  24776. * @param {number} yRadius - The radius of the ellipse in the y axis.
  24777. * @param {number} aStartAngle - The start angle in radians.
  24778. * @param {number} aEndAngle - The end angle in radians.
  24779. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24780. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24781. * @return {Path} A reference to this path.
  24782. */
  24783. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24784. const x0 = this.currentPoint.x;
  24785. const y0 = this.currentPoint.y;
  24786. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24787. return this;
  24788. }
  24789. /**
  24790. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  24791. *
  24792. * @param {number} aX - The x coordinate of the absolute center of the ellipse.
  24793. * @param {number} aY - The y coordinate of the absolute center of the ellipse.
  24794. * @param {number} xRadius - The radius of the ellipse in the x axis.
  24795. * @param {number} yRadius - The radius of the ellipse in the y axis.
  24796. * @param {number} aStartAngle - The start angle in radians.
  24797. * @param {number} aEndAngle - The end angle in radians.
  24798. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24799. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24800. * @return {Path} A reference to this path.
  24801. */
  24802. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24803. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24804. if ( this.curves.length > 0 ) {
  24805. // if a previous curve is present, attempt to join
  24806. const firstPoint = curve.getPoint( 0 );
  24807. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24808. this.lineTo( firstPoint.x, firstPoint.y );
  24809. }
  24810. }
  24811. this.curves.push( curve );
  24812. const lastPoint = curve.getPoint( 1 );
  24813. this.currentPoint.copy( lastPoint );
  24814. return this;
  24815. }
  24816. copy( source ) {
  24817. super.copy( source );
  24818. this.currentPoint.copy( source.currentPoint );
  24819. return this;
  24820. }
  24821. toJSON() {
  24822. const data = super.toJSON();
  24823. data.currentPoint = this.currentPoint.toArray();
  24824. return data;
  24825. }
  24826. fromJSON( json ) {
  24827. super.fromJSON( json );
  24828. this.currentPoint.fromArray( json.currentPoint );
  24829. return this;
  24830. }
  24831. }
  24832. /**
  24833. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  24834. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  24835. * points, or to get triangulated faces.
  24836. *
  24837. * ```js
  24838. * const heartShape = new THREE.Shape();
  24839. *
  24840. * heartShape.moveTo( 25, 25 );
  24841. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  24842. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  24843. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  24844. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  24845. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  24846. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  24847. *
  24848. * const extrudeSettings = {
  24849. * depth: 8,
  24850. * bevelEnabled: true,
  24851. * bevelSegments: 2,
  24852. * steps: 2,
  24853. * bevelSize: 1,
  24854. * bevelThickness: 1
  24855. * };
  24856. *
  24857. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  24858. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  24859. * ```
  24860. *
  24861. * @augments Path
  24862. */
  24863. class Shape extends Path {
  24864. /**
  24865. * Constructs a new shape.
  24866. *
  24867. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  24868. */
  24869. constructor( points ) {
  24870. super( points );
  24871. /**
  24872. * The UUID of the shape.
  24873. *
  24874. * @type {string}
  24875. * @readonly
  24876. */
  24877. this.uuid = generateUUID();
  24878. this.type = 'Shape';
  24879. /**
  24880. * Defines the holes in the shape. Hole definitions must use the
  24881. * opposite winding order (CW/CCW) than the outer shape.
  24882. *
  24883. * @type {Array<Path>}
  24884. * @readonly
  24885. */
  24886. this.holes = [];
  24887. }
  24888. /**
  24889. * Returns an array representing each contour of the holes
  24890. * as a list of 2D points.
  24891. *
  24892. * @param {number} divisions - The fineness of the result.
  24893. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  24894. */
  24895. getPointsHoles( divisions ) {
  24896. const holesPts = [];
  24897. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24898. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  24899. }
  24900. return holesPts;
  24901. }
  24902. // get points of shape and holes (keypoints based on segments parameter)
  24903. /**
  24904. * Returns an object that holds contour data for the shape and its holes as
  24905. * arrays of 2D points.
  24906. *
  24907. * @param {number} divisions - The fineness of the result.
  24908. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  24909. */
  24910. extractPoints( divisions ) {
  24911. return {
  24912. shape: this.getPoints( divisions ),
  24913. holes: this.getPointsHoles( divisions )
  24914. };
  24915. }
  24916. copy( source ) {
  24917. super.copy( source );
  24918. this.holes = [];
  24919. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  24920. const hole = source.holes[ i ];
  24921. this.holes.push( hole.clone() );
  24922. }
  24923. return this;
  24924. }
  24925. toJSON() {
  24926. const data = super.toJSON();
  24927. data.uuid = this.uuid;
  24928. data.holes = [];
  24929. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24930. const hole = this.holes[ i ];
  24931. data.holes.push( hole.toJSON() );
  24932. }
  24933. return data;
  24934. }
  24935. fromJSON( json ) {
  24936. super.fromJSON( json );
  24937. this.uuid = json.uuid;
  24938. this.holes = [];
  24939. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  24940. const hole = json.holes[ i ];
  24941. this.holes.push( new Path().fromJSON( hole ) );
  24942. }
  24943. return this;
  24944. }
  24945. }
  24946. /* eslint-disable */
  24947. // copy of mapbox/earcut version 3.0.1
  24948. // https://github.com/mapbox/earcut/tree/v3.0.1
  24949. function earcut(data, holeIndices, dim = 2) {
  24950. const hasHoles = holeIndices && holeIndices.length;
  24951. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  24952. let outerNode = linkedList(data, 0, outerLen, dim, true);
  24953. const triangles = [];
  24954. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  24955. let minX, minY, invSize;
  24956. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  24957. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  24958. if (data.length > 80 * dim) {
  24959. minX = Infinity;
  24960. minY = Infinity;
  24961. let maxX = -Infinity;
  24962. let maxY = -Infinity;
  24963. for (let i = dim; i < outerLen; i += dim) {
  24964. const x = data[i];
  24965. const y = data[i + 1];
  24966. if (x < minX) minX = x;
  24967. if (y < minY) minY = y;
  24968. if (x > maxX) maxX = x;
  24969. if (y > maxY) maxY = y;
  24970. }
  24971. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  24972. invSize = Math.max(maxX - minX, maxY - minY);
  24973. invSize = invSize !== 0 ? 32767 / invSize : 0;
  24974. }
  24975. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  24976. return triangles;
  24977. }
  24978. // create a circular doubly linked list from polygon points in the specified winding order
  24979. function linkedList(data, start, end, dim, clockwise) {
  24980. let last;
  24981. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  24982. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  24983. } else {
  24984. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  24985. }
  24986. if (last && equals(last, last.next)) {
  24987. removeNode(last);
  24988. last = last.next;
  24989. }
  24990. return last;
  24991. }
  24992. // eliminate colinear or duplicate points
  24993. function filterPoints(start, end) {
  24994. if (!start) return start;
  24995. if (!end) end = start;
  24996. let p = start,
  24997. again;
  24998. do {
  24999. again = false;
  25000. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  25001. removeNode(p);
  25002. p = end = p.prev;
  25003. if (p === p.next) break;
  25004. again = true;
  25005. } else {
  25006. p = p.next;
  25007. }
  25008. } while (again || p !== end);
  25009. return end;
  25010. }
  25011. // main ear slicing loop which triangulates a polygon (given as a linked list)
  25012. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  25013. if (!ear) return;
  25014. // interlink polygon nodes in z-order
  25015. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  25016. let stop = ear;
  25017. // iterate through ears, slicing them one by one
  25018. while (ear.prev !== ear.next) {
  25019. const prev = ear.prev;
  25020. const next = ear.next;
  25021. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  25022. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  25023. removeNode(ear);
  25024. // skipping the next vertex leads to less sliver triangles
  25025. ear = next.next;
  25026. stop = next.next;
  25027. continue;
  25028. }
  25029. ear = next;
  25030. // if we looped through the whole remaining polygon and can't find any more ears
  25031. if (ear === stop) {
  25032. // try filtering points and slicing again
  25033. if (!pass) {
  25034. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  25035. // if this didn't work, try curing all small self-intersections locally
  25036. } else if (pass === 1) {
  25037. ear = cureLocalIntersections(filterPoints(ear), triangles);
  25038. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  25039. // as a last resort, try splitting the remaining polygon into two
  25040. } else if (pass === 2) {
  25041. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  25042. }
  25043. break;
  25044. }
  25045. }
  25046. }
  25047. // check whether a polygon node forms a valid ear with adjacent nodes
  25048. function isEar(ear) {
  25049. const a = ear.prev,
  25050. b = ear,
  25051. c = ear.next;
  25052. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25053. // now make sure we don't have other points inside the potential ear
  25054. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25055. // triangle bbox
  25056. const x0 = Math.min(ax, bx, cx),
  25057. y0 = Math.min(ay, by, cy),
  25058. x1 = Math.max(ax, bx, cx),
  25059. y1 = Math.max(ay, by, cy);
  25060. let p = c.next;
  25061. while (p !== a) {
  25062. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  25063. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  25064. area(p.prev, p, p.next) >= 0) return false;
  25065. p = p.next;
  25066. }
  25067. return true;
  25068. }
  25069. function isEarHashed(ear, minX, minY, invSize) {
  25070. const a = ear.prev,
  25071. b = ear,
  25072. c = ear.next;
  25073. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25074. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25075. // triangle bbox
  25076. const x0 = Math.min(ax, bx, cx),
  25077. y0 = Math.min(ay, by, cy),
  25078. x1 = Math.max(ax, bx, cx),
  25079. y1 = Math.max(ay, by, cy);
  25080. // z-order range for the current triangle bbox;
  25081. const minZ = zOrder(x0, y0, minX, minY, invSize),
  25082. maxZ = zOrder(x1, y1, minX, minY, invSize);
  25083. let p = ear.prevZ,
  25084. n = ear.nextZ;
  25085. // look for points inside the triangle in both directions
  25086. while (p && p.z >= minZ && n && n.z <= maxZ) {
  25087. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25088. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25089. p = p.prevZ;
  25090. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25091. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25092. n = n.nextZ;
  25093. }
  25094. // look for remaining points in decreasing z-order
  25095. while (p && p.z >= minZ) {
  25096. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25097. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25098. p = p.prevZ;
  25099. }
  25100. // look for remaining points in increasing z-order
  25101. while (n && n.z <= maxZ) {
  25102. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25103. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25104. n = n.nextZ;
  25105. }
  25106. return true;
  25107. }
  25108. // go through all polygon nodes and cure small local self-intersections
  25109. function cureLocalIntersections(start, triangles) {
  25110. let p = start;
  25111. do {
  25112. const a = p.prev,
  25113. b = p.next.next;
  25114. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  25115. triangles.push(a.i, p.i, b.i);
  25116. // remove two nodes involved
  25117. removeNode(p);
  25118. removeNode(p.next);
  25119. p = start = b;
  25120. }
  25121. p = p.next;
  25122. } while (p !== start);
  25123. return filterPoints(p);
  25124. }
  25125. // try splitting polygon into two and triangulate them independently
  25126. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  25127. // look for a valid diagonal that divides the polygon into two
  25128. let a = start;
  25129. do {
  25130. let b = a.next.next;
  25131. while (b !== a.prev) {
  25132. if (a.i !== b.i && isValidDiagonal(a, b)) {
  25133. // split the polygon in two by the diagonal
  25134. let c = splitPolygon(a, b);
  25135. // filter colinear points around the cuts
  25136. a = filterPoints(a, a.next);
  25137. c = filterPoints(c, c.next);
  25138. // run earcut on each half
  25139. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  25140. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  25141. return;
  25142. }
  25143. b = b.next;
  25144. }
  25145. a = a.next;
  25146. } while (a !== start);
  25147. }
  25148. // link every hole into the outer loop, producing a single-ring polygon without holes
  25149. function eliminateHoles(data, holeIndices, outerNode, dim) {
  25150. const queue = [];
  25151. for (let i = 0, len = holeIndices.length; i < len; i++) {
  25152. const start = holeIndices[i] * dim;
  25153. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  25154. const list = linkedList(data, start, end, dim, false);
  25155. if (list === list.next) list.steiner = true;
  25156. queue.push(getLeftmost(list));
  25157. }
  25158. queue.sort(compareXYSlope);
  25159. // process holes from left to right
  25160. for (let i = 0; i < queue.length; i++) {
  25161. outerNode = eliminateHole(queue[i], outerNode);
  25162. }
  25163. return outerNode;
  25164. }
  25165. function compareXYSlope(a, b) {
  25166. let result = a.x - b.x;
  25167. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  25168. // the bridge to the outer shell is always the point that they meet at.
  25169. if (result === 0) {
  25170. result = a.y - b.y;
  25171. if (result === 0) {
  25172. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  25173. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  25174. result = aSlope - bSlope;
  25175. }
  25176. }
  25177. return result;
  25178. }
  25179. // find a bridge between vertices that connects hole with an outer ring and and link it
  25180. function eliminateHole(hole, outerNode) {
  25181. const bridge = findHoleBridge(hole, outerNode);
  25182. if (!bridge) {
  25183. return outerNode;
  25184. }
  25185. const bridgeReverse = splitPolygon(bridge, hole);
  25186. // filter collinear points around the cuts
  25187. filterPoints(bridgeReverse, bridgeReverse.next);
  25188. return filterPoints(bridge, bridge.next);
  25189. }
  25190. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  25191. function findHoleBridge(hole, outerNode) {
  25192. let p = outerNode;
  25193. const hx = hole.x;
  25194. const hy = hole.y;
  25195. let qx = -Infinity;
  25196. let m;
  25197. // find a segment intersected by a ray from the hole's leftmost point to the left;
  25198. // segment's endpoint with lesser x will be potential connection point
  25199. // unless they intersect at a vertex, then choose the vertex
  25200. if (equals(hole, p)) return p;
  25201. do {
  25202. if (equals(hole, p.next)) return p.next;
  25203. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  25204. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  25205. if (x <= hx && x > qx) {
  25206. qx = x;
  25207. m = p.x < p.next.x ? p : p.next;
  25208. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  25209. }
  25210. }
  25211. p = p.next;
  25212. } while (p !== outerNode);
  25213. if (!m) return null;
  25214. // look for points inside the triangle of hole point, segment intersection and endpoint;
  25215. // if there are no points found, we have a valid connection;
  25216. // otherwise choose the point of the minimum angle with the ray as connection point
  25217. const stop = m;
  25218. const mx = m.x;
  25219. const my = m.y;
  25220. let tanMin = Infinity;
  25221. p = m;
  25222. do {
  25223. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  25224. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  25225. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  25226. if (locallyInside(p, hole) &&
  25227. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  25228. m = p;
  25229. tanMin = tan;
  25230. }
  25231. }
  25232. p = p.next;
  25233. } while (p !== stop);
  25234. return m;
  25235. }
  25236. // whether sector in vertex m contains sector in vertex p in the same coordinates
  25237. function sectorContainsSector(m, p) {
  25238. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  25239. }
  25240. // interlink polygon nodes in z-order
  25241. function indexCurve(start, minX, minY, invSize) {
  25242. let p = start;
  25243. do {
  25244. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  25245. p.prevZ = p.prev;
  25246. p.nextZ = p.next;
  25247. p = p.next;
  25248. } while (p !== start);
  25249. p.prevZ.nextZ = null;
  25250. p.prevZ = null;
  25251. sortLinked(p);
  25252. }
  25253. // Simon Tatham's linked list merge sort algorithm
  25254. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  25255. function sortLinked(list) {
  25256. let numMerges;
  25257. let inSize = 1;
  25258. do {
  25259. let p = list;
  25260. let e;
  25261. list = null;
  25262. let tail = null;
  25263. numMerges = 0;
  25264. while (p) {
  25265. numMerges++;
  25266. let q = p;
  25267. let pSize = 0;
  25268. for (let i = 0; i < inSize; i++) {
  25269. pSize++;
  25270. q = q.nextZ;
  25271. if (!q) break;
  25272. }
  25273. let qSize = inSize;
  25274. while (pSize > 0 || (qSize > 0 && q)) {
  25275. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  25276. e = p;
  25277. p = p.nextZ;
  25278. pSize--;
  25279. } else {
  25280. e = q;
  25281. q = q.nextZ;
  25282. qSize--;
  25283. }
  25284. if (tail) tail.nextZ = e;
  25285. else list = e;
  25286. e.prevZ = tail;
  25287. tail = e;
  25288. }
  25289. p = q;
  25290. }
  25291. tail.nextZ = null;
  25292. inSize *= 2;
  25293. } while (numMerges > 1);
  25294. return list;
  25295. }
  25296. // z-order of a point given coords and inverse of the longer side of data bbox
  25297. function zOrder(x, y, minX, minY, invSize) {
  25298. // coords are transformed into non-negative 15-bit integer range
  25299. x = (x - minX) * invSize | 0;
  25300. y = (y - minY) * invSize | 0;
  25301. x = (x | (x << 8)) & 0x00FF00FF;
  25302. x = (x | (x << 4)) & 0x0F0F0F0F;
  25303. x = (x | (x << 2)) & 0x33333333;
  25304. x = (x | (x << 1)) & 0x55555555;
  25305. y = (y | (y << 8)) & 0x00FF00FF;
  25306. y = (y | (y << 4)) & 0x0F0F0F0F;
  25307. y = (y | (y << 2)) & 0x33333333;
  25308. y = (y | (y << 1)) & 0x55555555;
  25309. return x | (y << 1);
  25310. }
  25311. // find the leftmost node of a polygon ring
  25312. function getLeftmost(start) {
  25313. let p = start,
  25314. leftmost = start;
  25315. do {
  25316. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  25317. p = p.next;
  25318. } while (p !== start);
  25319. return leftmost;
  25320. }
  25321. // check if a point lies within a convex triangle
  25322. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  25323. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  25324. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  25325. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  25326. }
  25327. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  25328. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  25329. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  25330. }
  25331. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25332. function isValidDiagonal(a, b) {
  25333. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges
  25334. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  25335. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25336. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25337. }
  25338. // signed area of a triangle
  25339. function area(p, q, r) {
  25340. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25341. }
  25342. // check if two points are equal
  25343. function equals(p1, p2) {
  25344. return p1.x === p2.x && p1.y === p2.y;
  25345. }
  25346. // check if two segments intersect
  25347. function intersects(p1, q1, p2, q2) {
  25348. const o1 = sign(area(p1, q1, p2));
  25349. const o2 = sign(area(p1, q1, q2));
  25350. const o3 = sign(area(p2, q2, p1));
  25351. const o4 = sign(area(p2, q2, q1));
  25352. if (o1 !== o2 && o3 !== o4) return true; // general case
  25353. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25354. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25355. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25356. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25357. return false;
  25358. }
  25359. // for collinear points p, q, r, check if point q lies on segment pr
  25360. function onSegment(p, q, r) {
  25361. 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);
  25362. }
  25363. function sign(num) {
  25364. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25365. }
  25366. // check if a polygon diagonal intersects any polygon segments
  25367. function intersectsPolygon(a, b) {
  25368. let p = a;
  25369. do {
  25370. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25371. intersects(p, p.next, a, b)) return true;
  25372. p = p.next;
  25373. } while (p !== a);
  25374. return false;
  25375. }
  25376. // check if a polygon diagonal is locally inside the polygon
  25377. function locallyInside(a, b) {
  25378. return area(a.prev, a, a.next) < 0 ?
  25379. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  25380. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  25381. }
  25382. // check if the middle point of a polygon diagonal is inside the polygon
  25383. function middleInside(a, b) {
  25384. let p = a;
  25385. let inside = false;
  25386. const px = (a.x + b.x) / 2;
  25387. const py = (a.y + b.y) / 2;
  25388. do {
  25389. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  25390. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  25391. inside = !inside;
  25392. p = p.next;
  25393. } while (p !== a);
  25394. return inside;
  25395. }
  25396. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25397. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25398. function splitPolygon(a, b) {
  25399. const a2 = createNode(a.i, a.x, a.y),
  25400. b2 = createNode(b.i, b.x, b.y),
  25401. an = a.next,
  25402. bp = b.prev;
  25403. a.next = b;
  25404. b.prev = a;
  25405. a2.next = an;
  25406. an.prev = a2;
  25407. b2.next = a2;
  25408. a2.prev = b2;
  25409. bp.next = b2;
  25410. b2.prev = bp;
  25411. return b2;
  25412. }
  25413. // create a node and optionally link it with previous one (in a circular doubly linked list)
  25414. function insertNode(i, x, y, last) {
  25415. const p = createNode(i, x, y);
  25416. if (!last) {
  25417. p.prev = p;
  25418. p.next = p;
  25419. } else {
  25420. p.next = last.next;
  25421. p.prev = last;
  25422. last.next.prev = p;
  25423. last.next = p;
  25424. }
  25425. return p;
  25426. }
  25427. function removeNode(p) {
  25428. p.next.prev = p.prev;
  25429. p.prev.next = p.next;
  25430. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  25431. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  25432. }
  25433. function createNode(i, x, y) {
  25434. return {
  25435. i, // vertex index in coordinates array
  25436. x, y, // vertex coordinates
  25437. prev: null, // previous and next vertex nodes in a polygon ring
  25438. next: null,
  25439. z: 0, // z-order curve value
  25440. prevZ: null, // previous and next nodes in z-order
  25441. nextZ: null,
  25442. steiner: false // indicates whether this is a steiner point
  25443. };
  25444. }
  25445. function signedArea(data, start, end, dim) {
  25446. let sum = 0;
  25447. for (let i = start, j = end - dim; i < end; i += dim) {
  25448. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  25449. j = i;
  25450. }
  25451. return sum;
  25452. }
  25453. class Earcut {
  25454. /**
  25455. * Triangulates the given shape definition by returning an array of triangles.
  25456. *
  25457. * @param {Array<number>} data - An array with 2D points.
  25458. * @param {Array<number>} holeIndices - An array with indices defining holes.
  25459. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  25460. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  25461. * representing vertex indices.
  25462. */
  25463. static triangulate( data, holeIndices, dim = 2 ) {
  25464. return earcut( data, holeIndices, dim );
  25465. }
  25466. }
  25467. /**
  25468. * A class containing utility functions for shapes.
  25469. *
  25470. * @hideconstructor
  25471. */
  25472. class ShapeUtils {
  25473. /**
  25474. * Calculate area of a ( 2D ) contour polygon.
  25475. *
  25476. * @param {Array<Vector2>} contour - An array of 2D points.
  25477. * @return {number} The area.
  25478. */
  25479. static area( contour ) {
  25480. const n = contour.length;
  25481. let a = 0.0;
  25482. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  25483. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  25484. }
  25485. return a * 0.5;
  25486. }
  25487. /**
  25488. * Returns `true` if the given contour uses a clockwise winding order.
  25489. *
  25490. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  25491. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  25492. */
  25493. static isClockWise( pts ) {
  25494. return ShapeUtils.area( pts ) < 0;
  25495. }
  25496. /**
  25497. * Triangulates the given shape definition.
  25498. *
  25499. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  25500. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  25501. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  25502. */
  25503. static triangulateShape( contour, holes ) {
  25504. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25505. const holeIndices = []; // array of hole indices
  25506. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25507. removeDupEndPts( contour );
  25508. addContour( vertices, contour );
  25509. //
  25510. let holeIndex = contour.length;
  25511. holes.forEach( removeDupEndPts );
  25512. for ( let i = 0; i < holes.length; i ++ ) {
  25513. holeIndices.push( holeIndex );
  25514. holeIndex += holes[ i ].length;
  25515. addContour( vertices, holes[ i ] );
  25516. }
  25517. //
  25518. const triangles = Earcut.triangulate( vertices, holeIndices );
  25519. //
  25520. for ( let i = 0; i < triangles.length; i += 3 ) {
  25521. faces.push( triangles.slice( i, i + 3 ) );
  25522. }
  25523. return faces;
  25524. }
  25525. }
  25526. function removeDupEndPts( points ) {
  25527. const l = points.length;
  25528. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  25529. points.pop();
  25530. }
  25531. }
  25532. function addContour( vertices, contour ) {
  25533. for ( let i = 0; i < contour.length; i ++ ) {
  25534. vertices.push( contour[ i ].x );
  25535. vertices.push( contour[ i ].y );
  25536. }
  25537. }
  25538. /**
  25539. * Creates extruded geometry from a path shape.
  25540. *
  25541. * ```js
  25542. * const length = 12, width = 8;
  25543. *
  25544. * const shape = new THREE.Shape();
  25545. * shape.moveTo( 0,0 );
  25546. * shape.lineTo( 0, width );
  25547. * shape.lineTo( length, width );
  25548. * shape.lineTo( length, 0 );
  25549. * shape.lineTo( 0, 0 );
  25550. *
  25551. * const geometry = new THREE.ExtrudeGeometry( shape );
  25552. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  25553. * const mesh = new THREE.Mesh( geometry, material ) ;
  25554. * scene.add( mesh );
  25555. * ```
  25556. *
  25557. * @augments BufferGeometry
  25558. */
  25559. class ExtrudeGeometry extends BufferGeometry {
  25560. /**
  25561. * Constructs a new extrude geometry.
  25562. *
  25563. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  25564. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  25565. */
  25566. 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 = {} ) {
  25567. super();
  25568. this.type = 'ExtrudeGeometry';
  25569. /**
  25570. * Holds the constructor parameters that have been
  25571. * used to generate the geometry. Any modification
  25572. * after instantiation does not change the geometry.
  25573. *
  25574. * @type {Object}
  25575. */
  25576. this.parameters = {
  25577. shapes: shapes,
  25578. options: options
  25579. };
  25580. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  25581. const scope = this;
  25582. const verticesArray = [];
  25583. const uvArray = [];
  25584. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25585. const shape = shapes[ i ];
  25586. addShape( shape );
  25587. }
  25588. // build geometry
  25589. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  25590. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  25591. this.computeVertexNormals();
  25592. // functions
  25593. function addShape( shape ) {
  25594. const placeholder = [];
  25595. // options
  25596. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  25597. const steps = options.steps !== undefined ? options.steps : 1;
  25598. const depth = options.depth !== undefined ? options.depth : 1;
  25599. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  25600. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  25601. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  25602. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  25603. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  25604. const extrudePath = options.extrudePath;
  25605. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  25606. //
  25607. let extrudePts, extrudeByPath = false;
  25608. let splineTube, binormal, normal, position2;
  25609. if ( extrudePath ) {
  25610. extrudePts = extrudePath.getSpacedPoints( steps );
  25611. extrudeByPath = true;
  25612. bevelEnabled = false; // bevels not supported for path extrusion
  25613. // SETUP TNB variables
  25614. // TODO1 - have a .isClosed in spline?
  25615. splineTube = extrudePath.computeFrenetFrames( steps, false );
  25616. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  25617. binormal = new Vector3();
  25618. normal = new Vector3();
  25619. position2 = new Vector3();
  25620. }
  25621. // Safeguards if bevels are not enabled
  25622. if ( ! bevelEnabled ) {
  25623. bevelSegments = 0;
  25624. bevelThickness = 0;
  25625. bevelSize = 0;
  25626. bevelOffset = 0;
  25627. }
  25628. // Variables initialization
  25629. const shapePoints = shape.extractPoints( curveSegments );
  25630. let vertices = shapePoints.shape;
  25631. const holes = shapePoints.holes;
  25632. const reverse = ! ShapeUtils.isClockWise( vertices );
  25633. if ( reverse ) {
  25634. vertices = vertices.reverse();
  25635. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  25636. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25637. const ahole = holes[ h ];
  25638. if ( ShapeUtils.isClockWise( ahole ) ) {
  25639. holes[ h ] = ahole.reverse();
  25640. }
  25641. }
  25642. }
  25643. /**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.
  25644. * @param {Array<Vector2>} points
  25645. */
  25646. function mergeOverlappingPoints( points ) {
  25647. const THRESHOLD = 1e-10;
  25648. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  25649. let prevPos = points[ 0 ];
  25650. for ( let i = 1; i <= points.length; i ++ ) {
  25651. const currentIndex = i % points.length;
  25652. const currentPos = points[ currentIndex ];
  25653. const dx = currentPos.x - prevPos.x;
  25654. const dy = currentPos.y - prevPos.y;
  25655. const distSq = dx * dx + dy * dy;
  25656. const scalingFactorSqrt = Math.max(
  25657. Math.abs( currentPos.x ),
  25658. Math.abs( currentPos.y ),
  25659. Math.abs( prevPos.x ),
  25660. Math.abs( prevPos.y )
  25661. );
  25662. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  25663. if ( distSq <= thresholdSqScaled ) {
  25664. points.splice( currentIndex, 1 );
  25665. i --;
  25666. continue;
  25667. }
  25668. prevPos = currentPos;
  25669. }
  25670. }
  25671. mergeOverlappingPoints( vertices );
  25672. holes.forEach( mergeOverlappingPoints );
  25673. const numHoles = holes.length;
  25674. /* Vertices */
  25675. const contour = vertices; // vertices has all points but contour has only points of circumference
  25676. for ( let h = 0; h < numHoles; h ++ ) {
  25677. const ahole = holes[ h ];
  25678. vertices = vertices.concat( ahole );
  25679. }
  25680. function scalePt2( pt, vec, size ) {
  25681. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  25682. return pt.clone().addScaledVector( vec, size );
  25683. }
  25684. const vlen = vertices.length;
  25685. // Find directions for point movement
  25686. function getBevelVec( inPt, inPrev, inNext ) {
  25687. // computes for inPt the corresponding point inPt' on a new contour
  25688. // shifted by 1 unit (length of normalized vector) to the left
  25689. // if we walk along contour clockwise, this new contour is outside the old one
  25690. //
  25691. // inPt' is the intersection of the two lines parallel to the two
  25692. // adjacent edges of inPt at a distance of 1 unit on the left side.
  25693. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  25694. // good reading for geometry algorithms (here: line-line intersection)
  25695. // http://geomalgorithms.com/a05-_intersect-1.html
  25696. const v_prev_x = inPt.x - inPrev.x,
  25697. v_prev_y = inPt.y - inPrev.y;
  25698. const v_next_x = inNext.x - inPt.x,
  25699. v_next_y = inNext.y - inPt.y;
  25700. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  25701. // check for collinear edges
  25702. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25703. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  25704. // not collinear
  25705. // length of vectors for normalizing
  25706. const v_prev_len = Math.sqrt( v_prev_lensq );
  25707. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  25708. // shift adjacent points by unit vectors to the left
  25709. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  25710. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  25711. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  25712. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  25713. // scaling factor for v_prev to intersection point
  25714. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  25715. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  25716. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25717. // vector from inPt to intersection point
  25718. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  25719. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  25720. // Don't normalize!, otherwise sharp corners become ugly
  25721. // but prevent crazy spikes
  25722. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  25723. if ( v_trans_lensq <= 2 ) {
  25724. return new Vector2( v_trans_x, v_trans_y );
  25725. } else {
  25726. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  25727. }
  25728. } else {
  25729. // handle special case of collinear edges
  25730. let direction_eq = false; // assumes: opposite
  25731. if ( v_prev_x > Number.EPSILON ) {
  25732. if ( v_next_x > Number.EPSILON ) {
  25733. direction_eq = true;
  25734. }
  25735. } else {
  25736. if ( v_prev_x < - Number.EPSILON ) {
  25737. if ( v_next_x < - Number.EPSILON ) {
  25738. direction_eq = true;
  25739. }
  25740. } else {
  25741. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  25742. direction_eq = true;
  25743. }
  25744. }
  25745. }
  25746. if ( direction_eq ) {
  25747. // console.log("Warning: lines are a straight sequence");
  25748. v_trans_x = - v_prev_y;
  25749. v_trans_y = v_prev_x;
  25750. shrink_by = Math.sqrt( v_prev_lensq );
  25751. } else {
  25752. // console.log("Warning: lines are a straight spike");
  25753. v_trans_x = v_prev_x;
  25754. v_trans_y = v_prev_y;
  25755. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  25756. }
  25757. }
  25758. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  25759. }
  25760. const contourMovements = [];
  25761. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25762. if ( j === il ) j = 0;
  25763. if ( k === il ) k = 0;
  25764. // (j)---(i)---(k)
  25765. // console.log('i,j,k', i, j , k)
  25766. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  25767. }
  25768. const holesMovements = [];
  25769. let oneHoleMovements, verticesMovements = contourMovements.concat();
  25770. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25771. const ahole = holes[ h ];
  25772. oneHoleMovements = [];
  25773. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25774. if ( j === il ) j = 0;
  25775. if ( k === il ) k = 0;
  25776. // (j)---(i)---(k)
  25777. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  25778. }
  25779. holesMovements.push( oneHoleMovements );
  25780. verticesMovements = verticesMovements.concat( oneHoleMovements );
  25781. }
  25782. let faces;
  25783. if ( bevelSegments === 0 ) {
  25784. faces = ShapeUtils.triangulateShape( contour, holes );
  25785. } else {
  25786. const contractedContourVertices = [];
  25787. const expandedHoleVertices = [];
  25788. // Loop bevelSegments, 1 for the front, 1 for the back
  25789. for ( let b = 0; b < bevelSegments; b ++ ) {
  25790. //for ( b = bevelSegments; b > 0; b -- ) {
  25791. const t = b / bevelSegments;
  25792. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25793. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25794. // contract shape
  25795. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25796. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25797. v( vert.x, vert.y, - z );
  25798. if ( t === 0 ) contractedContourVertices.push( vert );
  25799. }
  25800. // expand holes
  25801. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25802. const ahole = holes[ h ];
  25803. oneHoleMovements = holesMovements[ h ];
  25804. const oneHoleVertices = [];
  25805. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25806. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25807. v( vert.x, vert.y, - z );
  25808. if ( t === 0 ) oneHoleVertices.push( vert );
  25809. }
  25810. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  25811. }
  25812. }
  25813. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  25814. }
  25815. const flen = faces.length;
  25816. const bs = bevelSize + bevelOffset;
  25817. // Back facing vertices
  25818. for ( let i = 0; i < vlen; i ++ ) {
  25819. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25820. if ( ! extrudeByPath ) {
  25821. v( vert.x, vert.y, 0 );
  25822. } else {
  25823. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  25824. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  25825. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  25826. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  25827. v( position2.x, position2.y, position2.z );
  25828. }
  25829. }
  25830. // Add stepped vertices...
  25831. // Including front facing vertices
  25832. for ( let s = 1; s <= steps; s ++ ) {
  25833. for ( let i = 0; i < vlen; i ++ ) {
  25834. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25835. if ( ! extrudeByPath ) {
  25836. v( vert.x, vert.y, depth / steps * s );
  25837. } else {
  25838. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  25839. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  25840. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  25841. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  25842. v( position2.x, position2.y, position2.z );
  25843. }
  25844. }
  25845. }
  25846. // Add bevel segments planes
  25847. //for ( b = 1; b <= bevelSegments; b ++ ) {
  25848. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  25849. const t = b / bevelSegments;
  25850. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25851. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25852. // contract shape
  25853. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25854. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25855. v( vert.x, vert.y, depth + z );
  25856. }
  25857. // expand holes
  25858. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25859. const ahole = holes[ h ];
  25860. oneHoleMovements = holesMovements[ h ];
  25861. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25862. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25863. if ( ! extrudeByPath ) {
  25864. v( vert.x, vert.y, depth + z );
  25865. } else {
  25866. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  25867. }
  25868. }
  25869. }
  25870. }
  25871. /* Faces */
  25872. // Top and bottom faces
  25873. buildLidFaces();
  25874. // Sides faces
  25875. buildSideFaces();
  25876. ///// Internal functions
  25877. function buildLidFaces() {
  25878. const start = verticesArray.length / 3;
  25879. if ( bevelEnabled ) {
  25880. let layer = 0; // steps + 1
  25881. let offset = vlen * layer;
  25882. // Bottom faces
  25883. for ( let i = 0; i < flen; i ++ ) {
  25884. const face = faces[ i ];
  25885. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  25886. }
  25887. layer = steps + bevelSegments * 2;
  25888. offset = vlen * layer;
  25889. // Top faces
  25890. for ( let i = 0; i < flen; i ++ ) {
  25891. const face = faces[ i ];
  25892. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  25893. }
  25894. } else {
  25895. // Bottom faces
  25896. for ( let i = 0; i < flen; i ++ ) {
  25897. const face = faces[ i ];
  25898. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  25899. }
  25900. // Top faces
  25901. for ( let i = 0; i < flen; i ++ ) {
  25902. const face = faces[ i ];
  25903. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  25904. }
  25905. }
  25906. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  25907. }
  25908. // Create faces for the z-sides of the shape
  25909. function buildSideFaces() {
  25910. const start = verticesArray.length / 3;
  25911. let layeroffset = 0;
  25912. sidewalls( contour, layeroffset );
  25913. layeroffset += contour.length;
  25914. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25915. const ahole = holes[ h ];
  25916. sidewalls( ahole, layeroffset );
  25917. //, true
  25918. layeroffset += ahole.length;
  25919. }
  25920. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  25921. }
  25922. function sidewalls( contour, layeroffset ) {
  25923. let i = contour.length;
  25924. while ( -- i >= 0 ) {
  25925. const j = i;
  25926. let k = i - 1;
  25927. if ( k < 0 ) k = contour.length - 1;
  25928. //console.log('b', i,j, i-1, k,vertices.length);
  25929. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  25930. const slen1 = vlen * s;
  25931. const slen2 = vlen * ( s + 1 );
  25932. const a = layeroffset + j + slen1,
  25933. b = layeroffset + k + slen1,
  25934. c = layeroffset + k + slen2,
  25935. d = layeroffset + j + slen2;
  25936. f4( a, b, c, d );
  25937. }
  25938. }
  25939. }
  25940. function v( x, y, z ) {
  25941. placeholder.push( x );
  25942. placeholder.push( y );
  25943. placeholder.push( z );
  25944. }
  25945. function f3( a, b, c ) {
  25946. addVertex( a );
  25947. addVertex( b );
  25948. addVertex( c );
  25949. const nextIndex = verticesArray.length / 3;
  25950. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  25951. addUV( uvs[ 0 ] );
  25952. addUV( uvs[ 1 ] );
  25953. addUV( uvs[ 2 ] );
  25954. }
  25955. function f4( a, b, c, d ) {
  25956. addVertex( a );
  25957. addVertex( b );
  25958. addVertex( d );
  25959. addVertex( b );
  25960. addVertex( c );
  25961. addVertex( d );
  25962. const nextIndex = verticesArray.length / 3;
  25963. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  25964. addUV( uvs[ 0 ] );
  25965. addUV( uvs[ 1 ] );
  25966. addUV( uvs[ 3 ] );
  25967. addUV( uvs[ 1 ] );
  25968. addUV( uvs[ 2 ] );
  25969. addUV( uvs[ 3 ] );
  25970. }
  25971. function addVertex( index ) {
  25972. verticesArray.push( placeholder[ index * 3 + 0 ] );
  25973. verticesArray.push( placeholder[ index * 3 + 1 ] );
  25974. verticesArray.push( placeholder[ index * 3 + 2 ] );
  25975. }
  25976. function addUV( vector2 ) {
  25977. uvArray.push( vector2.x );
  25978. uvArray.push( vector2.y );
  25979. }
  25980. }
  25981. }
  25982. copy( source ) {
  25983. super.copy( source );
  25984. this.parameters = Object.assign( {}, source.parameters );
  25985. return this;
  25986. }
  25987. toJSON() {
  25988. const data = super.toJSON();
  25989. const shapes = this.parameters.shapes;
  25990. const options = this.parameters.options;
  25991. return toJSON$1( shapes, options, data );
  25992. }
  25993. /**
  25994. * Factory method for creating an instance of this class from the given
  25995. * JSON object.
  25996. *
  25997. * @param {Object} data - A JSON object representing the serialized geometry.
  25998. * @param {Array<Shape>} shapes - An array of shapes.
  25999. * @return {ExtrudeGeometry} A new instance.
  26000. */
  26001. static fromJSON( data, shapes ) {
  26002. const geometryShapes = [];
  26003. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26004. const shape = shapes[ data.shapes[ j ] ];
  26005. geometryShapes.push( shape );
  26006. }
  26007. const extrudePath = data.options.extrudePath;
  26008. if ( extrudePath !== undefined ) {
  26009. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  26010. }
  26011. return new ExtrudeGeometry( geometryShapes, data.options );
  26012. }
  26013. }
  26014. const WorldUVGenerator = {
  26015. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  26016. const a_x = vertices[ indexA * 3 ];
  26017. const a_y = vertices[ indexA * 3 + 1 ];
  26018. const b_x = vertices[ indexB * 3 ];
  26019. const b_y = vertices[ indexB * 3 + 1 ];
  26020. const c_x = vertices[ indexC * 3 ];
  26021. const c_y = vertices[ indexC * 3 + 1 ];
  26022. return [
  26023. new Vector2( a_x, a_y ),
  26024. new Vector2( b_x, b_y ),
  26025. new Vector2( c_x, c_y )
  26026. ];
  26027. },
  26028. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  26029. const a_x = vertices[ indexA * 3 ];
  26030. const a_y = vertices[ indexA * 3 + 1 ];
  26031. const a_z = vertices[ indexA * 3 + 2 ];
  26032. const b_x = vertices[ indexB * 3 ];
  26033. const b_y = vertices[ indexB * 3 + 1 ];
  26034. const b_z = vertices[ indexB * 3 + 2 ];
  26035. const c_x = vertices[ indexC * 3 ];
  26036. const c_y = vertices[ indexC * 3 + 1 ];
  26037. const c_z = vertices[ indexC * 3 + 2 ];
  26038. const d_x = vertices[ indexD * 3 ];
  26039. const d_y = vertices[ indexD * 3 + 1 ];
  26040. const d_z = vertices[ indexD * 3 + 2 ];
  26041. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  26042. return [
  26043. new Vector2( a_x, 1 - a_z ),
  26044. new Vector2( b_x, 1 - b_z ),
  26045. new Vector2( c_x, 1 - c_z ),
  26046. new Vector2( d_x, 1 - d_z )
  26047. ];
  26048. } else {
  26049. return [
  26050. new Vector2( a_y, 1 - a_z ),
  26051. new Vector2( b_y, 1 - b_z ),
  26052. new Vector2( c_y, 1 - c_z ),
  26053. new Vector2( d_y, 1 - d_z )
  26054. ];
  26055. }
  26056. }
  26057. };
  26058. function toJSON$1( shapes, options, data ) {
  26059. data.shapes = [];
  26060. if ( Array.isArray( shapes ) ) {
  26061. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26062. const shape = shapes[ i ];
  26063. data.shapes.push( shape.uuid );
  26064. }
  26065. } else {
  26066. data.shapes.push( shapes.uuid );
  26067. }
  26068. data.options = Object.assign( {}, options );
  26069. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  26070. return data;
  26071. }
  26072. /**
  26073. * A geometry class for representing an icosahedron.
  26074. *
  26075. * ```js
  26076. * const geometry = new THREE.IcosahedronGeometry();
  26077. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26078. * const icosahedron = new THREE.Mesh( geometry, material );
  26079. * scene.add( icosahedron );
  26080. * ```
  26081. *
  26082. * @augments PolyhedronGeometry
  26083. */
  26084. class IcosahedronGeometry extends PolyhedronGeometry {
  26085. /**
  26086. * Constructs a new icosahedron geometry.
  26087. *
  26088. * @param {number} [radius=1] - Radius of the icosahedron.
  26089. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  26090. */
  26091. constructor( radius = 1, detail = 0 ) {
  26092. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  26093. const vertices = [
  26094. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  26095. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  26096. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  26097. ];
  26098. const indices = [
  26099. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  26100. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  26101. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  26102. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  26103. ];
  26104. super( vertices, indices, radius, detail );
  26105. this.type = 'IcosahedronGeometry';
  26106. /**
  26107. * Holds the constructor parameters that have been
  26108. * used to generate the geometry. Any modification
  26109. * after instantiation does not change the geometry.
  26110. *
  26111. * @type {Object}
  26112. */
  26113. this.parameters = {
  26114. radius: radius,
  26115. detail: detail
  26116. };
  26117. }
  26118. /**
  26119. * Factory method for creating an instance of this class from the given
  26120. * JSON object.
  26121. *
  26122. * @param {Object} data - A JSON object representing the serialized geometry.
  26123. * @return {IcosahedronGeometry} A new instance.
  26124. */
  26125. static fromJSON( data ) {
  26126. return new IcosahedronGeometry( data.radius, data.detail );
  26127. }
  26128. }
  26129. /**
  26130. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  26131. *
  26132. * ```js
  26133. * const points = [];
  26134. * for ( let i = 0; i < 10; i ++ ) {
  26135. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  26136. * }
  26137. * const geometry = new THREE.LatheGeometry( points );
  26138. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26139. * const lathe = new THREE.Mesh( geometry, material );
  26140. * scene.add( lathe );
  26141. * ```
  26142. *
  26143. * @augments BufferGeometry
  26144. */
  26145. class LatheGeometry extends BufferGeometry {
  26146. /**
  26147. * Constructs a new lathe geometry.
  26148. *
  26149. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  26150. * must be greater than zero.
  26151. * @param {number} [segments=12] - The number of circumference segments to generate.
  26152. * @param {number} [phiStart=0] - The starting angle in radians.
  26153. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  26154. * closed lathe, less than 2PI is a portion.
  26155. */
  26156. 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 ) {
  26157. super();
  26158. this.type = 'LatheGeometry';
  26159. /**
  26160. * Holds the constructor parameters that have been
  26161. * used to generate the geometry. Any modification
  26162. * after instantiation does not change the geometry.
  26163. *
  26164. * @type {Object}
  26165. */
  26166. this.parameters = {
  26167. points: points,
  26168. segments: segments,
  26169. phiStart: phiStart,
  26170. phiLength: phiLength
  26171. };
  26172. segments = Math.floor( segments );
  26173. // clamp phiLength so it's in range of [ 0, 2PI ]
  26174. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  26175. // buffers
  26176. const indices = [];
  26177. const vertices = [];
  26178. const uvs = [];
  26179. const initNormals = [];
  26180. const normals = [];
  26181. // helper variables
  26182. const inverseSegments = 1.0 / segments;
  26183. const vertex = new Vector3();
  26184. const uv = new Vector2();
  26185. const normal = new Vector3();
  26186. const curNormal = new Vector3();
  26187. const prevNormal = new Vector3();
  26188. let dx = 0;
  26189. let dy = 0;
  26190. // pre-compute normals for initial "meridian"
  26191. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26192. switch ( j ) {
  26193. case 0: // special handling for 1st vertex on path
  26194. dx = points[ j + 1 ].x - points[ j ].x;
  26195. dy = points[ j + 1 ].y - points[ j ].y;
  26196. normal.x = dy * 1.0;
  26197. normal.y = - dx;
  26198. normal.z = dy * 0.0;
  26199. prevNormal.copy( normal );
  26200. normal.normalize();
  26201. initNormals.push( normal.x, normal.y, normal.z );
  26202. break;
  26203. case ( points.length - 1 ): // special handling for last Vertex on path
  26204. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  26205. break;
  26206. default: // default handling for all vertices in between
  26207. dx = points[ j + 1 ].x - points[ j ].x;
  26208. dy = points[ j + 1 ].y - points[ j ].y;
  26209. normal.x = dy * 1.0;
  26210. normal.y = - dx;
  26211. normal.z = dy * 0.0;
  26212. curNormal.copy( normal );
  26213. normal.x += prevNormal.x;
  26214. normal.y += prevNormal.y;
  26215. normal.z += prevNormal.z;
  26216. normal.normalize();
  26217. initNormals.push( normal.x, normal.y, normal.z );
  26218. prevNormal.copy( curNormal );
  26219. }
  26220. }
  26221. // generate vertices, uvs and normals
  26222. for ( let i = 0; i <= segments; i ++ ) {
  26223. const phi = phiStart + i * inverseSegments * phiLength;
  26224. const sin = Math.sin( phi );
  26225. const cos = Math.cos( phi );
  26226. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26227. // vertex
  26228. vertex.x = points[ j ].x * sin;
  26229. vertex.y = points[ j ].y;
  26230. vertex.z = points[ j ].x * cos;
  26231. vertices.push( vertex.x, vertex.y, vertex.z );
  26232. // uv
  26233. uv.x = i / segments;
  26234. uv.y = j / ( points.length - 1 );
  26235. uvs.push( uv.x, uv.y );
  26236. // normal
  26237. const x = initNormals[ 3 * j + 0 ] * sin;
  26238. const y = initNormals[ 3 * j + 1 ];
  26239. const z = initNormals[ 3 * j + 0 ] * cos;
  26240. normals.push( x, y, z );
  26241. }
  26242. }
  26243. // indices
  26244. for ( let i = 0; i < segments; i ++ ) {
  26245. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  26246. const base = j + i * points.length;
  26247. const a = base;
  26248. const b = base + points.length;
  26249. const c = base + points.length + 1;
  26250. const d = base + 1;
  26251. // faces
  26252. indices.push( a, b, d );
  26253. indices.push( c, d, b );
  26254. }
  26255. }
  26256. // build geometry
  26257. this.setIndex( indices );
  26258. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26259. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26260. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26261. }
  26262. copy( source ) {
  26263. super.copy( source );
  26264. this.parameters = Object.assign( {}, source.parameters );
  26265. return this;
  26266. }
  26267. /**
  26268. * Factory method for creating an instance of this class from the given
  26269. * JSON object.
  26270. *
  26271. * @param {Object} data - A JSON object representing the serialized geometry.
  26272. * @return {LatheGeometry} A new instance.
  26273. */
  26274. static fromJSON( data ) {
  26275. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  26276. }
  26277. }
  26278. /**
  26279. * A geometry class for representing an octahedron.
  26280. *
  26281. * ```js
  26282. * const geometry = new THREE.OctahedronGeometry();
  26283. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26284. * const octahedron = new THREE.Mesh( geometry, material );
  26285. * scene.add( octahedron );
  26286. * ```
  26287. *
  26288. * @augments PolyhedronGeometry
  26289. */
  26290. class OctahedronGeometry extends PolyhedronGeometry {
  26291. /**
  26292. * Constructs a new octahedron geometry.
  26293. *
  26294. * @param {number} [radius=1] - Radius of the octahedron.
  26295. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  26296. */
  26297. constructor( radius = 1, detail = 0 ) {
  26298. const vertices = [
  26299. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  26300. 0, -1, 0, 0, 0, 1, 0, 0, -1
  26301. ];
  26302. const indices = [
  26303. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  26304. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  26305. 1, 3, 4, 1, 4, 2
  26306. ];
  26307. super( vertices, indices, radius, detail );
  26308. this.type = 'OctahedronGeometry';
  26309. /**
  26310. * Holds the constructor parameters that have been
  26311. * used to generate the geometry. Any modification
  26312. * after instantiation does not change the geometry.
  26313. *
  26314. * @type {Object}
  26315. */
  26316. this.parameters = {
  26317. radius: radius,
  26318. detail: detail
  26319. };
  26320. }
  26321. /**
  26322. * Factory method for creating an instance of this class from the given
  26323. * JSON object.
  26324. *
  26325. * @param {Object} data - A JSON object representing the serialized geometry.
  26326. * @return {OctahedronGeometry} A new instance.
  26327. */
  26328. static fromJSON( data ) {
  26329. return new OctahedronGeometry( data.radius, data.detail );
  26330. }
  26331. }
  26332. /**
  26333. * A geometry class for representing a plane.
  26334. *
  26335. * ```js
  26336. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  26337. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26338. * const plane = new THREE.Mesh( geometry, material );
  26339. * scene.add( plane );
  26340. * ```
  26341. *
  26342. * @augments BufferGeometry
  26343. */
  26344. class PlaneGeometry extends BufferGeometry {
  26345. /**
  26346. * Constructs a new plane geometry.
  26347. *
  26348. * @param {number} [width=1] - The width along the X axis.
  26349. * @param {number} [height=1] - The height along the Y axis
  26350. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  26351. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  26352. */
  26353. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  26354. super();
  26355. this.type = 'PlaneGeometry';
  26356. /**
  26357. * Holds the constructor parameters that have been
  26358. * used to generate the geometry. Any modification
  26359. * after instantiation does not change the geometry.
  26360. *
  26361. * @type {Object}
  26362. */
  26363. this.parameters = {
  26364. width: width,
  26365. height: height,
  26366. widthSegments: widthSegments,
  26367. heightSegments: heightSegments
  26368. };
  26369. const width_half = width / 2;
  26370. const height_half = height / 2;
  26371. const gridX = Math.floor( widthSegments );
  26372. const gridY = Math.floor( heightSegments );
  26373. const gridX1 = gridX + 1;
  26374. const gridY1 = gridY + 1;
  26375. const segment_width = width / gridX;
  26376. const segment_height = height / gridY;
  26377. //
  26378. const indices = [];
  26379. const vertices = [];
  26380. const normals = [];
  26381. const uvs = [];
  26382. for ( let iy = 0; iy < gridY1; iy ++ ) {
  26383. const y = iy * segment_height - height_half;
  26384. for ( let ix = 0; ix < gridX1; ix ++ ) {
  26385. const x = ix * segment_width - width_half;
  26386. vertices.push( x, - y, 0 );
  26387. normals.push( 0, 0, 1 );
  26388. uvs.push( ix / gridX );
  26389. uvs.push( 1 - ( iy / gridY ) );
  26390. }
  26391. }
  26392. for ( let iy = 0; iy < gridY; iy ++ ) {
  26393. for ( let ix = 0; ix < gridX; ix ++ ) {
  26394. const a = ix + gridX1 * iy;
  26395. const b = ix + gridX1 * ( iy + 1 );
  26396. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  26397. const d = ( ix + 1 ) + gridX1 * iy;
  26398. indices.push( a, b, d );
  26399. indices.push( b, c, d );
  26400. }
  26401. }
  26402. this.setIndex( indices );
  26403. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26404. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26405. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26406. }
  26407. copy( source ) {
  26408. super.copy( source );
  26409. this.parameters = Object.assign( {}, source.parameters );
  26410. return this;
  26411. }
  26412. /**
  26413. * Factory method for creating an instance of this class from the given
  26414. * JSON object.
  26415. *
  26416. * @param {Object} data - A JSON object representing the serialized geometry.
  26417. * @return {PlaneGeometry} A new instance.
  26418. */
  26419. static fromJSON( data ) {
  26420. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  26421. }
  26422. }
  26423. /**
  26424. * A class for generating a two-dimensional ring geometry.
  26425. *
  26426. * ```js
  26427. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  26428. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26429. * const mesh = new THREE.Mesh( geometry, material );
  26430. * scene.add( mesh );
  26431. * ```
  26432. *
  26433. * @augments BufferGeometry
  26434. */
  26435. class RingGeometry extends BufferGeometry {
  26436. /**
  26437. * Constructs a new ring geometry.
  26438. *
  26439. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  26440. * @param {number} [outerRadius=1] - The outer radius of the ring.
  26441. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  26442. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  26443. * @param {number} [thetaStart=0] - Starting angle in radians.
  26444. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  26445. */
  26446. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26447. super();
  26448. this.type = 'RingGeometry';
  26449. /**
  26450. * Holds the constructor parameters that have been
  26451. * used to generate the geometry. Any modification
  26452. * after instantiation does not change the geometry.
  26453. *
  26454. * @type {Object}
  26455. */
  26456. this.parameters = {
  26457. innerRadius: innerRadius,
  26458. outerRadius: outerRadius,
  26459. thetaSegments: thetaSegments,
  26460. phiSegments: phiSegments,
  26461. thetaStart: thetaStart,
  26462. thetaLength: thetaLength
  26463. };
  26464. thetaSegments = Math.max( 3, thetaSegments );
  26465. phiSegments = Math.max( 1, phiSegments );
  26466. // buffers
  26467. const indices = [];
  26468. const vertices = [];
  26469. const normals = [];
  26470. const uvs = [];
  26471. // some helper variables
  26472. let radius = innerRadius;
  26473. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  26474. const vertex = new Vector3();
  26475. const uv = new Vector2();
  26476. // generate vertices, normals and uvs
  26477. for ( let j = 0; j <= phiSegments; j ++ ) {
  26478. for ( let i = 0; i <= thetaSegments; i ++ ) {
  26479. // values are generate from the inside of the ring to the outside
  26480. const segment = thetaStart + i / thetaSegments * thetaLength;
  26481. // vertex
  26482. vertex.x = radius * Math.cos( segment );
  26483. vertex.y = radius * Math.sin( segment );
  26484. vertices.push( vertex.x, vertex.y, vertex.z );
  26485. // normal
  26486. normals.push( 0, 0, 1 );
  26487. // uv
  26488. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  26489. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  26490. uvs.push( uv.x, uv.y );
  26491. }
  26492. // increase the radius for next row of vertices
  26493. radius += radiusStep;
  26494. }
  26495. // indices
  26496. for ( let j = 0; j < phiSegments; j ++ ) {
  26497. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  26498. for ( let i = 0; i < thetaSegments; i ++ ) {
  26499. const segment = i + thetaSegmentLevel;
  26500. const a = segment;
  26501. const b = segment + thetaSegments + 1;
  26502. const c = segment + thetaSegments + 2;
  26503. const d = segment + 1;
  26504. // faces
  26505. indices.push( a, b, d );
  26506. indices.push( b, c, d );
  26507. }
  26508. }
  26509. // build geometry
  26510. this.setIndex( indices );
  26511. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26512. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26513. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26514. }
  26515. copy( source ) {
  26516. super.copy( source );
  26517. this.parameters = Object.assign( {}, source.parameters );
  26518. return this;
  26519. }
  26520. /**
  26521. * Factory method for creating an instance of this class from the given
  26522. * JSON object.
  26523. *
  26524. * @param {Object} data - A JSON object representing the serialized geometry.
  26525. * @return {RingGeometry} A new instance.
  26526. */
  26527. static fromJSON( data ) {
  26528. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  26529. }
  26530. }
  26531. /**
  26532. * Creates an one-sided polygonal geometry from one or more path shapes.
  26533. *
  26534. * ```js
  26535. * const arcShape = new THREE.Shape()
  26536. * .moveTo( 5, 1 )
  26537. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  26538. *
  26539. * const geometry = new THREE.ShapeGeometry( arcShape );
  26540. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  26541. * const mesh = new THREE.Mesh( geometry, material ) ;
  26542. * scene.add( mesh );
  26543. * ```
  26544. *
  26545. * @augments BufferGeometry
  26546. */
  26547. class ShapeGeometry extends BufferGeometry {
  26548. /**
  26549. * Constructs a new shape geometry.
  26550. *
  26551. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26552. * @param {number} [curveSegments=12] - Number of segments per shape.
  26553. */
  26554. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  26555. super();
  26556. this.type = 'ShapeGeometry';
  26557. /**
  26558. * Holds the constructor parameters that have been
  26559. * used to generate the geometry. Any modification
  26560. * after instantiation does not change the geometry.
  26561. *
  26562. * @type {Object}
  26563. */
  26564. this.parameters = {
  26565. shapes: shapes,
  26566. curveSegments: curveSegments
  26567. };
  26568. // buffers
  26569. const indices = [];
  26570. const vertices = [];
  26571. const normals = [];
  26572. const uvs = [];
  26573. // helper variables
  26574. let groupStart = 0;
  26575. let groupCount = 0;
  26576. // allow single and array values for "shapes" parameter
  26577. if ( Array.isArray( shapes ) === false ) {
  26578. addShape( shapes );
  26579. } else {
  26580. for ( let i = 0; i < shapes.length; i ++ ) {
  26581. addShape( shapes[ i ] );
  26582. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  26583. groupStart += groupCount;
  26584. groupCount = 0;
  26585. }
  26586. }
  26587. // build geometry
  26588. this.setIndex( indices );
  26589. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26590. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26591. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26592. // helper functions
  26593. function addShape( shape ) {
  26594. const indexOffset = vertices.length / 3;
  26595. const points = shape.extractPoints( curveSegments );
  26596. let shapeVertices = points.shape;
  26597. const shapeHoles = points.holes;
  26598. // check direction of vertices
  26599. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  26600. shapeVertices = shapeVertices.reverse();
  26601. }
  26602. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26603. const shapeHole = shapeHoles[ i ];
  26604. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  26605. shapeHoles[ i ] = shapeHole.reverse();
  26606. }
  26607. }
  26608. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  26609. // join vertices of inner and outer paths to a single array
  26610. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26611. const shapeHole = shapeHoles[ i ];
  26612. shapeVertices = shapeVertices.concat( shapeHole );
  26613. }
  26614. // vertices, normals, uvs
  26615. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  26616. const vertex = shapeVertices[ i ];
  26617. vertices.push( vertex.x, vertex.y, 0 );
  26618. normals.push( 0, 0, 1 );
  26619. uvs.push( vertex.x, vertex.y ); // world uvs
  26620. }
  26621. // indices
  26622. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  26623. const face = faces[ i ];
  26624. const a = face[ 0 ] + indexOffset;
  26625. const b = face[ 1 ] + indexOffset;
  26626. const c = face[ 2 ] + indexOffset;
  26627. indices.push( a, b, c );
  26628. groupCount += 3;
  26629. }
  26630. }
  26631. }
  26632. copy( source ) {
  26633. super.copy( source );
  26634. this.parameters = Object.assign( {}, source.parameters );
  26635. return this;
  26636. }
  26637. toJSON() {
  26638. const data = super.toJSON();
  26639. const shapes = this.parameters.shapes;
  26640. return toJSON( shapes, data );
  26641. }
  26642. /**
  26643. * Factory method for creating an instance of this class from the given
  26644. * JSON object.
  26645. *
  26646. * @param {Object} data - A JSON object representing the serialized geometry.
  26647. * @param {Array<Shape>} shapes - An array of shapes.
  26648. * @return {ShapeGeometry} A new instance.
  26649. */
  26650. static fromJSON( data, shapes ) {
  26651. const geometryShapes = [];
  26652. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26653. const shape = shapes[ data.shapes[ j ] ];
  26654. geometryShapes.push( shape );
  26655. }
  26656. return new ShapeGeometry( geometryShapes, data.curveSegments );
  26657. }
  26658. }
  26659. function toJSON( shapes, data ) {
  26660. data.shapes = [];
  26661. if ( Array.isArray( shapes ) ) {
  26662. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26663. const shape = shapes[ i ];
  26664. data.shapes.push( shape.uuid );
  26665. }
  26666. } else {
  26667. data.shapes.push( shapes.uuid );
  26668. }
  26669. return data;
  26670. }
  26671. /**
  26672. * A class for generating a sphere geometry.
  26673. *
  26674. * ```js
  26675. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  26676. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26677. * const sphere = new THREE.Mesh( geometry, material );
  26678. * scene.add( sphere );
  26679. * ```
  26680. *
  26681. * @augments BufferGeometry
  26682. */
  26683. class SphereGeometry extends BufferGeometry {
  26684. /**
  26685. * Constructs a new sphere geometry.
  26686. *
  26687. * @param {number} [radius=1] - The sphere radius.
  26688. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  26689. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  26690. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  26691. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  26692. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  26693. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  26694. */
  26695. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  26696. super();
  26697. this.type = 'SphereGeometry';
  26698. /**
  26699. * Holds the constructor parameters that have been
  26700. * used to generate the geometry. Any modification
  26701. * after instantiation does not change the geometry.
  26702. *
  26703. * @type {Object}
  26704. */
  26705. this.parameters = {
  26706. radius: radius,
  26707. widthSegments: widthSegments,
  26708. heightSegments: heightSegments,
  26709. phiStart: phiStart,
  26710. phiLength: phiLength,
  26711. thetaStart: thetaStart,
  26712. thetaLength: thetaLength
  26713. };
  26714. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  26715. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  26716. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  26717. let index = 0;
  26718. const grid = [];
  26719. const vertex = new Vector3();
  26720. const normal = new Vector3();
  26721. // buffers
  26722. const indices = [];
  26723. const vertices = [];
  26724. const normals = [];
  26725. const uvs = [];
  26726. // generate vertices, normals and uvs
  26727. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  26728. const verticesRow = [];
  26729. const v = iy / heightSegments;
  26730. // special case for the poles
  26731. let uOffset = 0;
  26732. if ( iy === 0 && thetaStart === 0 ) {
  26733. uOffset = 0.5 / widthSegments;
  26734. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  26735. uOffset = -0.5 / widthSegments;
  26736. }
  26737. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  26738. const u = ix / widthSegments;
  26739. // vertex
  26740. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26741. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  26742. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26743. vertices.push( vertex.x, vertex.y, vertex.z );
  26744. // normal
  26745. normal.copy( vertex ).normalize();
  26746. normals.push( normal.x, normal.y, normal.z );
  26747. // uv
  26748. uvs.push( u + uOffset, 1 - v );
  26749. verticesRow.push( index ++ );
  26750. }
  26751. grid.push( verticesRow );
  26752. }
  26753. // indices
  26754. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  26755. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  26756. const a = grid[ iy ][ ix + 1 ];
  26757. const b = grid[ iy ][ ix ];
  26758. const c = grid[ iy + 1 ][ ix ];
  26759. const d = grid[ iy + 1 ][ ix + 1 ];
  26760. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  26761. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  26762. }
  26763. }
  26764. // build geometry
  26765. this.setIndex( indices );
  26766. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26767. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26768. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26769. }
  26770. copy( source ) {
  26771. super.copy( source );
  26772. this.parameters = Object.assign( {}, source.parameters );
  26773. return this;
  26774. }
  26775. /**
  26776. * Factory method for creating an instance of this class from the given
  26777. * JSON object.
  26778. *
  26779. * @param {Object} data - A JSON object representing the serialized geometry.
  26780. * @return {SphereGeometry} A new instance.
  26781. */
  26782. static fromJSON( data ) {
  26783. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  26784. }
  26785. }
  26786. /**
  26787. * A geometry class for representing an tetrahedron.
  26788. *
  26789. * ```js
  26790. * const geometry = new THREE.TetrahedronGeometry();
  26791. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26792. * const tetrahedron = new THREE.Mesh( geometry, material );
  26793. * scene.add( tetrahedron );
  26794. * ```
  26795. *
  26796. * @augments PolyhedronGeometry
  26797. */
  26798. class TetrahedronGeometry extends PolyhedronGeometry {
  26799. /**
  26800. * Constructs a new tetrahedron geometry.
  26801. *
  26802. * @param {number} [radius=1] - Radius of the tetrahedron.
  26803. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  26804. */
  26805. constructor( radius = 1, detail = 0 ) {
  26806. const vertices = [
  26807. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  26808. ];
  26809. const indices = [
  26810. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  26811. ];
  26812. super( vertices, indices, radius, detail );
  26813. this.type = 'TetrahedronGeometry';
  26814. /**
  26815. * Holds the constructor parameters that have been
  26816. * used to generate the geometry. Any modification
  26817. * after instantiation does not change the geometry.
  26818. *
  26819. * @type {Object}
  26820. */
  26821. this.parameters = {
  26822. radius: radius,
  26823. detail: detail
  26824. };
  26825. }
  26826. /**
  26827. * Factory method for creating an instance of this class from the given
  26828. * JSON object.
  26829. *
  26830. * @param {Object} data - A JSON object representing the serialized geometry.
  26831. * @return {TetrahedronGeometry} A new instance.
  26832. */
  26833. static fromJSON( data ) {
  26834. return new TetrahedronGeometry( data.radius, data.detail );
  26835. }
  26836. }
  26837. /**
  26838. * A geometry class for representing an torus.
  26839. *
  26840. * ```js
  26841. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  26842. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26843. * const torus = new THREE.Mesh( geometry, material );
  26844. * scene.add( torus );
  26845. * ```
  26846. *
  26847. * @augments BufferGeometry
  26848. */
  26849. class TorusGeometry extends BufferGeometry {
  26850. /**
  26851. * Constructs a new torus geometry.
  26852. *
  26853. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  26854. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  26855. * @param {number} [radialSegments=12] - The number of radial segments.
  26856. * @param {number} [tubularSegments=48] - The number of tubular segments.
  26857. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  26858. */
  26859. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  26860. super();
  26861. this.type = 'TorusGeometry';
  26862. /**
  26863. * Holds the constructor parameters that have been
  26864. * used to generate the geometry. Any modification
  26865. * after instantiation does not change the geometry.
  26866. *
  26867. * @type {Object}
  26868. */
  26869. this.parameters = {
  26870. radius: radius,
  26871. tube: tube,
  26872. radialSegments: radialSegments,
  26873. tubularSegments: tubularSegments,
  26874. arc: arc
  26875. };
  26876. radialSegments = Math.floor( radialSegments );
  26877. tubularSegments = Math.floor( tubularSegments );
  26878. // buffers
  26879. const indices = [];
  26880. const vertices = [];
  26881. const normals = [];
  26882. const uvs = [];
  26883. // helper variables
  26884. const center = new Vector3();
  26885. const vertex = new Vector3();
  26886. const normal = new Vector3();
  26887. // generate vertices, normals and uvs
  26888. for ( let j = 0; j <= radialSegments; j ++ ) {
  26889. for ( let i = 0; i <= tubularSegments; i ++ ) {
  26890. const u = i / tubularSegments * arc;
  26891. const v = j / radialSegments * Math.PI * 2;
  26892. // vertex
  26893. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  26894. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  26895. vertex.z = tube * Math.sin( v );
  26896. vertices.push( vertex.x, vertex.y, vertex.z );
  26897. // normal
  26898. center.x = radius * Math.cos( u );
  26899. center.y = radius * Math.sin( u );
  26900. normal.subVectors( vertex, center ).normalize();
  26901. normals.push( normal.x, normal.y, normal.z );
  26902. // uv
  26903. uvs.push( i / tubularSegments );
  26904. uvs.push( j / radialSegments );
  26905. }
  26906. }
  26907. // generate indices
  26908. for ( let j = 1; j <= radialSegments; j ++ ) {
  26909. for ( let i = 1; i <= tubularSegments; i ++ ) {
  26910. // indices
  26911. const a = ( tubularSegments + 1 ) * j + i - 1;
  26912. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  26913. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  26914. const d = ( tubularSegments + 1 ) * j + i;
  26915. // faces
  26916. indices.push( a, b, d );
  26917. indices.push( b, c, d );
  26918. }
  26919. }
  26920. // build geometry
  26921. this.setIndex( indices );
  26922. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26923. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26924. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26925. }
  26926. copy( source ) {
  26927. super.copy( source );
  26928. this.parameters = Object.assign( {}, source.parameters );
  26929. return this;
  26930. }
  26931. /**
  26932. * Factory method for creating an instance of this class from the given
  26933. * JSON object.
  26934. *
  26935. * @param {Object} data - A JSON object representing the serialized geometry.
  26936. * @return {TorusGeometry} A new instance.
  26937. */
  26938. static fromJSON( data ) {
  26939. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  26940. }
  26941. }
  26942. /**
  26943. * Creates a torus knot, the particular shape of which is defined by a pair
  26944. * of coprime integers, p and q. If p and q are not coprime, the result will
  26945. * be a torus link.
  26946. *
  26947. * ```js
  26948. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  26949. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26950. * const torusKnot = new THREE.Mesh( geometry, material );
  26951. * scene.add( torusKnot );
  26952. * ```
  26953. *
  26954. * @augments BufferGeometry
  26955. */
  26956. class TorusKnotGeometry extends BufferGeometry {
  26957. /**
  26958. * Constructs a new torus knot geometry.
  26959. *
  26960. * @param {number} [radius=1] - Radius of the torus knot.
  26961. * @param {number} [tube=0.4] - Radius of the tube.
  26962. * @param {number} [tubularSegments=64] - The number of tubular segments.
  26963. * @param {number} [radialSegments=8] - The number of radial segments.
  26964. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  26965. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  26966. */
  26967. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  26968. super();
  26969. this.type = 'TorusKnotGeometry';
  26970. /**
  26971. * Holds the constructor parameters that have been
  26972. * used to generate the geometry. Any modification
  26973. * after instantiation does not change the geometry.
  26974. *
  26975. * @type {Object}
  26976. */
  26977. this.parameters = {
  26978. radius: radius,
  26979. tube: tube,
  26980. tubularSegments: tubularSegments,
  26981. radialSegments: radialSegments,
  26982. p: p,
  26983. q: q
  26984. };
  26985. tubularSegments = Math.floor( tubularSegments );
  26986. radialSegments = Math.floor( radialSegments );
  26987. // buffers
  26988. const indices = [];
  26989. const vertices = [];
  26990. const normals = [];
  26991. const uvs = [];
  26992. // helper variables
  26993. const vertex = new Vector3();
  26994. const normal = new Vector3();
  26995. const P1 = new Vector3();
  26996. const P2 = new Vector3();
  26997. const B = new Vector3();
  26998. const T = new Vector3();
  26999. const N = new Vector3();
  27000. // generate vertices, normals and uvs
  27001. for ( let i = 0; i <= tubularSegments; ++ i ) {
  27002. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  27003. const u = i / tubularSegments * p * Math.PI * 2;
  27004. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  27005. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  27006. calculatePositionOnCurve( u, p, q, radius, P1 );
  27007. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  27008. // calculate orthonormal basis
  27009. T.subVectors( P2, P1 );
  27010. N.addVectors( P2, P1 );
  27011. B.crossVectors( T, N );
  27012. N.crossVectors( B, T );
  27013. // normalize B, N. T can be ignored, we don't use it
  27014. B.normalize();
  27015. N.normalize();
  27016. for ( let j = 0; j <= radialSegments; ++ j ) {
  27017. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  27018. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  27019. const v = j / radialSegments * Math.PI * 2;
  27020. const cx = - tube * Math.cos( v );
  27021. const cy = tube * Math.sin( v );
  27022. // now calculate the final vertex position.
  27023. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  27024. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  27025. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  27026. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  27027. vertices.push( vertex.x, vertex.y, vertex.z );
  27028. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  27029. normal.subVectors( vertex, P1 ).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 <= tubularSegments; j ++ ) {
  27038. for ( let i = 1; i <= radialSegments; i ++ ) {
  27039. // indices
  27040. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27041. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27042. const c = ( radialSegments + 1 ) * j + i;
  27043. const d = ( radialSegments + 1 ) * ( j - 1 ) + 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. // this function calculates the current position on the torus curve
  27055. function calculatePositionOnCurve( u, p, q, radius, position ) {
  27056. const cu = Math.cos( u );
  27057. const su = Math.sin( u );
  27058. const quOverP = q / p * u;
  27059. const cs = Math.cos( quOverP );
  27060. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  27061. position.y = radius * ( 2 + cs ) * su * 0.5;
  27062. position.z = radius * Math.sin( quOverP ) * 0.5;
  27063. }
  27064. }
  27065. copy( source ) {
  27066. super.copy( source );
  27067. this.parameters = Object.assign( {}, source.parameters );
  27068. return this;
  27069. }
  27070. /**
  27071. * Factory method for creating an instance of this class from the given
  27072. * JSON object.
  27073. *
  27074. * @param {Object} data - A JSON object representing the serialized geometry.
  27075. * @return {TorusKnotGeometry} A new instance.
  27076. */
  27077. static fromJSON( data ) {
  27078. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  27079. }
  27080. }
  27081. /**
  27082. * Creates a tube that extrudes along a 3D curve.
  27083. *
  27084. * ```js
  27085. * class CustomSinCurve extends THREE.Curve {
  27086. *
  27087. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  27088. *
  27089. * const tx = t * 3 - 1.5;
  27090. * const ty = Math.sin( 2 * Math.PI * t );
  27091. * const tz = 0;
  27092. *
  27093. * return optionalTarget.set( tx, ty, tz );
  27094. * }
  27095. *
  27096. * }
  27097. *
  27098. * const path = new CustomSinCurve( 10 );
  27099. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  27100. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  27101. * const mesh = new THREE.Mesh( geometry, material );
  27102. * scene.add( mesh );
  27103. * ```
  27104. *
  27105. * @augments BufferGeometry
  27106. */
  27107. class TubeGeometry extends BufferGeometry {
  27108. /**
  27109. * Constructs a new tube geometry.
  27110. *
  27111. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  27112. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  27113. * @param {number} [radius=1] -The radius of the tube.
  27114. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  27115. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  27116. */
  27117. 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 ) {
  27118. super();
  27119. this.type = 'TubeGeometry';
  27120. /**
  27121. * Holds the constructor parameters that have been
  27122. * used to generate the geometry. Any modification
  27123. * after instantiation does not change the geometry.
  27124. *
  27125. * @type {Object}
  27126. */
  27127. this.parameters = {
  27128. path: path,
  27129. tubularSegments: tubularSegments,
  27130. radius: radius,
  27131. radialSegments: radialSegments,
  27132. closed: closed
  27133. };
  27134. const frames = path.computeFrenetFrames( tubularSegments, closed );
  27135. // expose internals
  27136. this.tangents = frames.tangents;
  27137. this.normals = frames.normals;
  27138. this.binormals = frames.binormals;
  27139. // helper variables
  27140. const vertex = new Vector3();
  27141. const normal = new Vector3();
  27142. const uv = new Vector2();
  27143. let P = new Vector3();
  27144. // buffer
  27145. const vertices = [];
  27146. const normals = [];
  27147. const uvs = [];
  27148. const indices = [];
  27149. // create buffer data
  27150. generateBufferData();
  27151. // build geometry
  27152. this.setIndex( indices );
  27153. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27154. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27155. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27156. // functions
  27157. function generateBufferData() {
  27158. for ( let i = 0; i < tubularSegments; i ++ ) {
  27159. generateSegment( i );
  27160. }
  27161. // if the geometry is not closed, generate the last row of vertices and normals
  27162. // at the regular position on the given path
  27163. //
  27164. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  27165. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  27166. // uvs are generated in a separate function.
  27167. // this makes it easy compute correct values for closed geometries
  27168. generateUVs();
  27169. // finally create faces
  27170. generateIndices();
  27171. }
  27172. function generateSegment( i ) {
  27173. // we use getPointAt to sample evenly distributed points from the given path
  27174. P = path.getPointAt( i / tubularSegments, P );
  27175. // retrieve corresponding normal and binormal
  27176. const N = frames.normals[ i ];
  27177. const B = frames.binormals[ i ];
  27178. // generate normals and vertices for the current segment
  27179. for ( let j = 0; j <= radialSegments; j ++ ) {
  27180. const v = j / radialSegments * Math.PI * 2;
  27181. const sin = Math.sin( v );
  27182. const cos = - Math.cos( v );
  27183. // normal
  27184. normal.x = ( cos * N.x + sin * B.x );
  27185. normal.y = ( cos * N.y + sin * B.y );
  27186. normal.z = ( cos * N.z + sin * B.z );
  27187. normal.normalize();
  27188. normals.push( normal.x, normal.y, normal.z );
  27189. // vertex
  27190. vertex.x = P.x + radius * normal.x;
  27191. vertex.y = P.y + radius * normal.y;
  27192. vertex.z = P.z + radius * normal.z;
  27193. vertices.push( vertex.x, vertex.y, vertex.z );
  27194. }
  27195. }
  27196. function generateIndices() {
  27197. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27198. for ( let i = 1; i <= radialSegments; i ++ ) {
  27199. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27200. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27201. const c = ( radialSegments + 1 ) * j + i;
  27202. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27203. // faces
  27204. indices.push( a, b, d );
  27205. indices.push( b, c, d );
  27206. }
  27207. }
  27208. }
  27209. function generateUVs() {
  27210. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27211. for ( let j = 0; j <= radialSegments; j ++ ) {
  27212. uv.x = i / tubularSegments;
  27213. uv.y = j / radialSegments;
  27214. uvs.push( uv.x, uv.y );
  27215. }
  27216. }
  27217. }
  27218. }
  27219. copy( source ) {
  27220. super.copy( source );
  27221. this.parameters = Object.assign( {}, source.parameters );
  27222. return this;
  27223. }
  27224. toJSON() {
  27225. const data = super.toJSON();
  27226. data.path = this.parameters.path.toJSON();
  27227. return data;
  27228. }
  27229. /**
  27230. * Factory method for creating an instance of this class from the given
  27231. * JSON object.
  27232. *
  27233. * @param {Object} data - A JSON object representing the serialized geometry.
  27234. * @return {TubeGeometry} A new instance.
  27235. */
  27236. static fromJSON( data ) {
  27237. // This only works for built-in curves (e.g. CatmullRomCurve3).
  27238. // User defined curves or instances of CurvePath will not be deserialized.
  27239. return new TubeGeometry(
  27240. new Curves[ data.path.type ]().fromJSON( data.path ),
  27241. data.tubularSegments,
  27242. data.radius,
  27243. data.radialSegments,
  27244. data.closed
  27245. );
  27246. }
  27247. }
  27248. /**
  27249. * Can be used as a helper object to visualize a geometry as a wireframe.
  27250. *
  27251. * ```js
  27252. * const geometry = new THREE.SphereGeometry();
  27253. *
  27254. * const wireframe = new THREE.WireframeGeometry( geometry );
  27255. *
  27256. * const line = new THREE.LineSegments( wireframe );
  27257. * line.material.depthWrite = false;
  27258. * line.material.opacity = 0.25;
  27259. * line.material.transparent = true;
  27260. *
  27261. * scene.add( line );
  27262. * ```
  27263. *
  27264. * Note: It is not yet possible to serialize/deserialize instances of this class.
  27265. *
  27266. * @augments BufferGeometry
  27267. */
  27268. class WireframeGeometry extends BufferGeometry {
  27269. /**
  27270. * Constructs a new wireframe geometry.
  27271. *
  27272. * @param {?BufferGeometry} [geometry=null] - The geometry.
  27273. */
  27274. constructor( geometry = null ) {
  27275. super();
  27276. this.type = 'WireframeGeometry';
  27277. /**
  27278. * Holds the constructor parameters that have been
  27279. * used to generate the geometry. Any modification
  27280. * after instantiation does not change the geometry.
  27281. *
  27282. * @type {Object}
  27283. */
  27284. this.parameters = {
  27285. geometry: geometry
  27286. };
  27287. if ( geometry !== null ) {
  27288. // buffer
  27289. const vertices = [];
  27290. const edges = new Set();
  27291. // helper variables
  27292. const start = new Vector3();
  27293. const end = new Vector3();
  27294. if ( geometry.index !== null ) {
  27295. // indexed BufferGeometry
  27296. const position = geometry.attributes.position;
  27297. const indices = geometry.index;
  27298. let groups = geometry.groups;
  27299. if ( groups.length === 0 ) {
  27300. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  27301. }
  27302. // create a data structure that contains all edges without duplicates
  27303. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  27304. const group = groups[ o ];
  27305. const groupStart = group.start;
  27306. const groupCount = group.count;
  27307. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  27308. for ( let j = 0; j < 3; j ++ ) {
  27309. const index1 = indices.getX( i + j );
  27310. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  27311. start.fromBufferAttribute( position, index1 );
  27312. end.fromBufferAttribute( position, index2 );
  27313. if ( isUniqueEdge( start, end, edges ) === true ) {
  27314. vertices.push( start.x, start.y, start.z );
  27315. vertices.push( end.x, end.y, end.z );
  27316. }
  27317. }
  27318. }
  27319. }
  27320. } else {
  27321. // non-indexed BufferGeometry
  27322. const position = geometry.attributes.position;
  27323. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  27324. for ( let j = 0; j < 3; j ++ ) {
  27325. // three edges per triangle, an edge is represented as (index1, index2)
  27326. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  27327. const index1 = 3 * i + j;
  27328. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  27329. start.fromBufferAttribute( position, index1 );
  27330. end.fromBufferAttribute( position, index2 );
  27331. if ( isUniqueEdge( start, end, edges ) === true ) {
  27332. vertices.push( start.x, start.y, start.z );
  27333. vertices.push( end.x, end.y, end.z );
  27334. }
  27335. }
  27336. }
  27337. }
  27338. // build geometry
  27339. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27340. }
  27341. }
  27342. copy( source ) {
  27343. super.copy( source );
  27344. this.parameters = Object.assign( {}, source.parameters );
  27345. return this;
  27346. }
  27347. }
  27348. function isUniqueEdge( start, end, edges ) {
  27349. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  27350. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  27351. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  27352. return false;
  27353. } else {
  27354. edges.add( hash1 );
  27355. edges.add( hash2 );
  27356. return true;
  27357. }
  27358. }
  27359. var Geometries = /*#__PURE__*/Object.freeze({
  27360. __proto__: null,
  27361. BoxGeometry: BoxGeometry,
  27362. CapsuleGeometry: CapsuleGeometry,
  27363. CircleGeometry: CircleGeometry,
  27364. ConeGeometry: ConeGeometry,
  27365. CylinderGeometry: CylinderGeometry,
  27366. DodecahedronGeometry: DodecahedronGeometry,
  27367. EdgesGeometry: EdgesGeometry,
  27368. ExtrudeGeometry: ExtrudeGeometry,
  27369. IcosahedronGeometry: IcosahedronGeometry,
  27370. LatheGeometry: LatheGeometry,
  27371. OctahedronGeometry: OctahedronGeometry,
  27372. PlaneGeometry: PlaneGeometry,
  27373. PolyhedronGeometry: PolyhedronGeometry,
  27374. RingGeometry: RingGeometry,
  27375. ShapeGeometry: ShapeGeometry,
  27376. SphereGeometry: SphereGeometry,
  27377. TetrahedronGeometry: TetrahedronGeometry,
  27378. TorusGeometry: TorusGeometry,
  27379. TorusKnotGeometry: TorusKnotGeometry,
  27380. TubeGeometry: TubeGeometry,
  27381. WireframeGeometry: WireframeGeometry
  27382. });
  27383. /**
  27384. * This material can receive shadows, but otherwise is completely transparent.
  27385. *
  27386. * ```js
  27387. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  27388. * geometry.rotateX( - Math.PI / 2 );
  27389. *
  27390. * const material = new THREE.ShadowMaterial();
  27391. * material.opacity = 0.2;
  27392. *
  27393. * const plane = new THREE.Mesh( geometry, material );
  27394. * plane.position.y = -200;
  27395. * plane.receiveShadow = true;
  27396. * scene.add( plane );
  27397. * ```
  27398. *
  27399. * @augments Material
  27400. */
  27401. class ShadowMaterial extends Material {
  27402. /**
  27403. * Constructs a new shadow material.
  27404. *
  27405. * @param {Object} [parameters] - An object with one or more properties
  27406. * defining the material's appearance. Any property of the material
  27407. * (including any property from inherited materials) can be passed
  27408. * in here. Color values can be passed any type of value accepted
  27409. * by {@link Color#set}.
  27410. */
  27411. constructor( parameters ) {
  27412. super();
  27413. /**
  27414. * This flag can be used for type testing.
  27415. *
  27416. * @type {boolean}
  27417. * @readonly
  27418. * @default true
  27419. */
  27420. this.isShadowMaterial = true;
  27421. this.type = 'ShadowMaterial';
  27422. /**
  27423. * Color of the material.
  27424. *
  27425. * @type {Color}
  27426. * @default (0,0,0)
  27427. */
  27428. this.color = new Color( 0x000000 );
  27429. /**
  27430. * Overwritten since shadow materials are transparent
  27431. * by default.
  27432. *
  27433. * @type {boolean}
  27434. * @default true
  27435. */
  27436. this.transparent = true;
  27437. /**
  27438. * Whether the material is affected by fog or not.
  27439. *
  27440. * @type {boolean}
  27441. * @default true
  27442. */
  27443. this.fog = true;
  27444. this.setValues( parameters );
  27445. }
  27446. copy( source ) {
  27447. super.copy( source );
  27448. this.color.copy( source.color );
  27449. this.fog = source.fog;
  27450. return this;
  27451. }
  27452. }
  27453. /**
  27454. * This class works just like {@link ShaderMaterial}, except that definitions
  27455. * of built-in uniforms and attributes are not automatically prepended to the
  27456. * GLSL shader code.
  27457. *
  27458. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  27459. *
  27460. * @augments ShaderMaterial
  27461. */
  27462. class RawShaderMaterial extends ShaderMaterial {
  27463. /**
  27464. * Constructs a new raw shader material.
  27465. *
  27466. * @param {Object} [parameters] - An object with one or more properties
  27467. * defining the material's appearance. Any property of the material
  27468. * (including any property from inherited materials) can be passed
  27469. * in here. Color values can be passed any type of value accepted
  27470. * by {@link Color#set}.
  27471. */
  27472. constructor( parameters ) {
  27473. super( parameters );
  27474. /**
  27475. * This flag can be used for type testing.
  27476. *
  27477. * @type {boolean}
  27478. * @readonly
  27479. * @default true
  27480. */
  27481. this.isRawShaderMaterial = true;
  27482. this.type = 'RawShaderMaterial';
  27483. }
  27484. }
  27485. /**
  27486. * A standard physically based material, using Metallic-Roughness workflow.
  27487. *
  27488. * Physically based rendering (PBR) has recently become the standard in many
  27489. * 3D applications, such as [Unity]{@link https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/},
  27490. * [Unreal]{@link https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/} and
  27491. * [3D Studio Max]{@link http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017}.
  27492. *
  27493. * This approach differs from older approaches in that instead of using
  27494. * approximations for the way in which light interacts with a surface, a
  27495. * physically correct model is used. The idea is that, instead of tweaking
  27496. * materials to look good under specific lighting, a material can be created
  27497. * that will react 'correctly' under all lighting scenarios.
  27498. *
  27499. * In practice this gives a more accurate and realistic looking result than
  27500. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  27501. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  27502. * shading.
  27503. *
  27504. * Note that for best results you should always specify an environment map when using this material.
  27505. *
  27506. * For a non-technical introduction to the concept of PBR and how to set up a
  27507. * PBR material, check out these articles by the people at [marmoset]{@link https://www.marmoset.co}:
  27508. *
  27509. * - [Basic Theory of Physically Based Rendering]{@link https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/}
  27510. * - [Physically Based Rendering and You Can Too]{@link https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/}
  27511. *
  27512. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  27513. * [paper from Disney]{@link https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf}
  27514. * (pdf), by Brent Burley.
  27515. *
  27516. * @augments Material
  27517. */
  27518. class MeshStandardMaterial extends Material {
  27519. /**
  27520. * Constructs a new mesh standard material.
  27521. *
  27522. * @param {Object} [parameters] - An object with one or more properties
  27523. * defining the material's appearance. Any property of the material
  27524. * (including any property from inherited materials) can be passed
  27525. * in here. Color values can be passed any type of value accepted
  27526. * by {@link Color#set}.
  27527. */
  27528. constructor( parameters ) {
  27529. super();
  27530. /**
  27531. * This flag can be used for type testing.
  27532. *
  27533. * @type {boolean}
  27534. * @readonly
  27535. * @default true
  27536. */
  27537. this.isMeshStandardMaterial = true;
  27538. this.type = 'MeshStandardMaterial';
  27539. this.defines = { 'STANDARD': '' };
  27540. /**
  27541. * Color of the material.
  27542. *
  27543. * @type {Color}
  27544. * @default (1,1,1)
  27545. */
  27546. this.color = new Color( 0xffffff ); // diffuse
  27547. /**
  27548. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  27549. * means fully diffuse. If `roughnessMap` is also provided,
  27550. * both values are multiplied.
  27551. *
  27552. * @type {number}
  27553. * @default 1
  27554. */
  27555. this.roughness = 1.0;
  27556. /**
  27557. * How much the material is like a metal. Non-metallic materials such as wood
  27558. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  27559. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  27560. * If `metalnessMap` is also provided, both values are multiplied.
  27561. *
  27562. * @type {number}
  27563. * @default 0
  27564. */
  27565. this.metalness = 0.0;
  27566. /**
  27567. * The color map. May optionally include an alpha channel, typically combined
  27568. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27569. * color is modulated by the diffuse `color`.
  27570. *
  27571. * @type {?Texture}
  27572. * @default null
  27573. */
  27574. this.map = null;
  27575. /**
  27576. * The light map. Requires a second set of UVs.
  27577. *
  27578. * @type {?Texture}
  27579. * @default null
  27580. */
  27581. this.lightMap = null;
  27582. /**
  27583. * Intensity of the baked light.
  27584. *
  27585. * @type {number}
  27586. * @default 1
  27587. */
  27588. this.lightMapIntensity = 1.0;
  27589. /**
  27590. * The red channel of this texture is used as the ambient occlusion map.
  27591. * Requires a second set of UVs.
  27592. *
  27593. * @type {?Texture}
  27594. * @default null
  27595. */
  27596. this.aoMap = null;
  27597. /**
  27598. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  27599. * disables ambient occlusion. Where intensity is `1` and the AO map's
  27600. * red channel is also `1`, ambient light is fully occluded on a surface.
  27601. *
  27602. * @type {number}
  27603. * @default 1
  27604. */
  27605. this.aoMapIntensity = 1.0;
  27606. /**
  27607. * Emissive (light) color of the material, essentially a solid color
  27608. * unaffected by other lighting.
  27609. *
  27610. * @type {Color}
  27611. * @default (0,0,0)
  27612. */
  27613. this.emissive = new Color( 0x000000 );
  27614. /**
  27615. * Intensity of the emissive light. Modulates the emissive color.
  27616. *
  27617. * @type {number}
  27618. * @default 1
  27619. */
  27620. this.emissiveIntensity = 1.0;
  27621. /**
  27622. * Set emissive (glow) map. The emissive map color is modulated by the
  27623. * emissive color and the emissive intensity. If you have an emissive map,
  27624. * be sure to set the emissive color to something other than black.
  27625. *
  27626. * @type {?Texture}
  27627. * @default null
  27628. */
  27629. this.emissiveMap = null;
  27630. /**
  27631. * The texture to create a bump map. The black and white values map to the
  27632. * perceived depth in relation to the lights. Bump doesn't actually affect
  27633. * the geometry of the object, only the lighting. If a normal map is defined
  27634. * this will be ignored.
  27635. *
  27636. * @type {?Texture}
  27637. * @default null
  27638. */
  27639. this.bumpMap = null;
  27640. /**
  27641. * How much the bump map affects the material. Typical range is `[0,1]`.
  27642. *
  27643. * @type {number}
  27644. * @default 1
  27645. */
  27646. this.bumpScale = 1;
  27647. /**
  27648. * The texture to create a normal map. The RGB values affect the surface
  27649. * normal for each pixel fragment and change the way the color is lit. Normal
  27650. * maps do not change the actual shape of the surface, only the lighting. In
  27651. * case the material has a normal map authored using the left handed
  27652. * convention, the `y` component of `normalScale` should be negated to compensate
  27653. * for the different handedness.
  27654. *
  27655. * @type {?Texture}
  27656. * @default null
  27657. */
  27658. this.normalMap = null;
  27659. /**
  27660. * The type of normal map.
  27661. *
  27662. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  27663. * @default TangentSpaceNormalMap
  27664. */
  27665. this.normalMapType = TangentSpaceNormalMap;
  27666. /**
  27667. * How much the normal map affects the material. Typical value range is `[0,1]`.
  27668. *
  27669. * @type {Vector2}
  27670. * @default (1,1)
  27671. */
  27672. this.normalScale = new Vector2( 1, 1 );
  27673. /**
  27674. * The displacement map affects the position of the mesh's vertices. Unlike
  27675. * other maps which only affect the light and shade of the material the
  27676. * displaced vertices can cast shadows, block other objects, and otherwise
  27677. * act as real geometry. The displacement texture is an image where the value
  27678. * of each pixel (white being the highest) is mapped against, and
  27679. * repositions, the vertices of the mesh.
  27680. *
  27681. * @type {?Texture}
  27682. * @default null
  27683. */
  27684. this.displacementMap = null;
  27685. /**
  27686. * How much the displacement map affects the mesh (where black is no
  27687. * displacement, and white is maximum displacement). Without a displacement
  27688. * map set, this value is not applied.
  27689. *
  27690. * @type {number}
  27691. * @default 0
  27692. */
  27693. this.displacementScale = 1;
  27694. /**
  27695. * The offset of the displacement map's values on the mesh's vertices.
  27696. * The bias is added to the scaled sample of the displacement map.
  27697. * Without a displacement map set, this value is not applied.
  27698. *
  27699. * @type {number}
  27700. * @default 0
  27701. */
  27702. this.displacementBias = 0;
  27703. /**
  27704. * The green channel of this texture is used to alter the roughness of the
  27705. * material.
  27706. *
  27707. * @type {?Texture}
  27708. * @default null
  27709. */
  27710. this.roughnessMap = null;
  27711. /**
  27712. * The blue channel of this texture is used to alter the metalness of the
  27713. * material.
  27714. *
  27715. * @type {?Texture}
  27716. * @default null
  27717. */
  27718. this.metalnessMap = null;
  27719. /**
  27720. * The alpha map is a grayscale texture that controls the opacity across the
  27721. * surface (black: fully transparent; white: fully opaque).
  27722. *
  27723. * Only the color of the texture is used, ignoring the alpha channel if one
  27724. * exists. For RGB and RGBA textures, the renderer will use the green channel
  27725. * when sampling this texture due to the extra bit of precision provided for
  27726. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  27727. * luminance/alpha textures will also still work as expected.
  27728. *
  27729. * @type {?Texture}
  27730. * @default null
  27731. */
  27732. this.alphaMap = null;
  27733. /**
  27734. * The environment map. To ensure a physically correct rendering, environment maps
  27735. * are internally pre-processed with {@link PMREMGenerator}.
  27736. *
  27737. * @type {?Texture}
  27738. * @default null
  27739. */
  27740. this.envMap = null;
  27741. /**
  27742. * The rotation of the environment map in radians.
  27743. *
  27744. * @type {Euler}
  27745. * @default (0,0,0)
  27746. */
  27747. this.envMapRotation = new Euler();
  27748. /**
  27749. * Scales the effect of the environment map by multiplying its color.
  27750. *
  27751. * @type {number}
  27752. * @default 1
  27753. */
  27754. this.envMapIntensity = 1.0;
  27755. /**
  27756. * Renders the geometry as a wireframe.
  27757. *
  27758. * @type {boolean}
  27759. * @default false
  27760. */
  27761. this.wireframe = false;
  27762. /**
  27763. * Controls the thickness of the wireframe.
  27764. *
  27765. * Can only be used with {@link SVGRenderer}.
  27766. *
  27767. * @type {number}
  27768. * @default 1
  27769. */
  27770. this.wireframeLinewidth = 1;
  27771. /**
  27772. * Defines appearance of wireframe ends.
  27773. *
  27774. * Can only be used with {@link SVGRenderer}.
  27775. *
  27776. * @type {('round'|'bevel'|'miter')}
  27777. * @default 'round'
  27778. */
  27779. this.wireframeLinecap = 'round';
  27780. /**
  27781. * Defines appearance of wireframe joints.
  27782. *
  27783. * Can only be used with {@link SVGRenderer}.
  27784. *
  27785. * @type {('round'|'bevel'|'miter')}
  27786. * @default 'round'
  27787. */
  27788. this.wireframeLinejoin = 'round';
  27789. /**
  27790. * Whether the material is rendered with flat shading or not.
  27791. *
  27792. * @type {boolean}
  27793. * @default false
  27794. */
  27795. this.flatShading = false;
  27796. /**
  27797. * Whether the material is affected by fog or not.
  27798. *
  27799. * @type {boolean}
  27800. * @default true
  27801. */
  27802. this.fog = true;
  27803. this.setValues( parameters );
  27804. }
  27805. copy( source ) {
  27806. super.copy( source );
  27807. this.defines = { 'STANDARD': '' };
  27808. this.color.copy( source.color );
  27809. this.roughness = source.roughness;
  27810. this.metalness = source.metalness;
  27811. this.map = source.map;
  27812. this.lightMap = source.lightMap;
  27813. this.lightMapIntensity = source.lightMapIntensity;
  27814. this.aoMap = source.aoMap;
  27815. this.aoMapIntensity = source.aoMapIntensity;
  27816. this.emissive.copy( source.emissive );
  27817. this.emissiveMap = source.emissiveMap;
  27818. this.emissiveIntensity = source.emissiveIntensity;
  27819. this.bumpMap = source.bumpMap;
  27820. this.bumpScale = source.bumpScale;
  27821. this.normalMap = source.normalMap;
  27822. this.normalMapType = source.normalMapType;
  27823. this.normalScale.copy( source.normalScale );
  27824. this.displacementMap = source.displacementMap;
  27825. this.displacementScale = source.displacementScale;
  27826. this.displacementBias = source.displacementBias;
  27827. this.roughnessMap = source.roughnessMap;
  27828. this.metalnessMap = source.metalnessMap;
  27829. this.alphaMap = source.alphaMap;
  27830. this.envMap = source.envMap;
  27831. this.envMapRotation.copy( source.envMapRotation );
  27832. this.envMapIntensity = source.envMapIntensity;
  27833. this.wireframe = source.wireframe;
  27834. this.wireframeLinewidth = source.wireframeLinewidth;
  27835. this.wireframeLinecap = source.wireframeLinecap;
  27836. this.wireframeLinejoin = source.wireframeLinejoin;
  27837. this.flatShading = source.flatShading;
  27838. this.fog = source.fog;
  27839. return this;
  27840. }
  27841. }
  27842. /**
  27843. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  27844. * physically-based rendering properties:
  27845. *
  27846. * - Anisotropy: Ability to represent the anisotropic property of materials
  27847. * as observable with brushed metals.
  27848. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  27849. * a clear, reflective layer on top of another layer that may be irregular or rough.
  27850. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  27851. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  27852. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  27853. * wings of many insects.
  27854. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  27855. * transparent materials are less reflective. Physically-based transmission provides a more
  27856. * realistic option for thin, transparent surfaces like glass.
  27857. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  27858. * - Sheen: Can be used for representing cloth and fabric materials.
  27859. *
  27860. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  27861. * higher performance cost, per pixel, than other three.js materials. Most
  27862. * effects are disabled by default, and add cost as they are enabled. For
  27863. * best results, always specify an environment map when using this material.
  27864. *
  27865. * @augments MeshStandardMaterial
  27866. */
  27867. class MeshPhysicalMaterial extends MeshStandardMaterial {
  27868. /**
  27869. * Constructs a new mesh physical material.
  27870. *
  27871. * @param {Object} [parameters] - An object with one or more properties
  27872. * defining the material's appearance. Any property of the material
  27873. * (including any property from inherited materials) can be passed
  27874. * in here. Color values can be passed any type of value accepted
  27875. * by {@link Color#set}.
  27876. */
  27877. constructor( parameters ) {
  27878. super();
  27879. /**
  27880. * This flag can be used for type testing.
  27881. *
  27882. * @type {boolean}
  27883. * @readonly
  27884. * @default true
  27885. */
  27886. this.isMeshPhysicalMaterial = true;
  27887. this.defines = {
  27888. 'STANDARD': '',
  27889. 'PHYSICAL': ''
  27890. };
  27891. this.type = 'MeshPhysicalMaterial';
  27892. /**
  27893. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  27894. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  27895. * property provides additional rotation to the vectors in the texture.
  27896. *
  27897. * @type {number}
  27898. * @default 1
  27899. */
  27900. this.anisotropyRotation = 0;
  27901. /**
  27902. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  27903. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  27904. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  27905. *
  27906. * @type {?Texture}
  27907. * @default null
  27908. */
  27909. this.anisotropyMap = null;
  27910. /**
  27911. * The red channel of this texture is multiplied against `clearcoat`,
  27912. * for per-pixel control over a coating's intensity.
  27913. *
  27914. * @type {?Texture}
  27915. * @default null
  27916. */
  27917. this.clearcoatMap = null;
  27918. /**
  27919. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  27920. *
  27921. * @type {number}
  27922. * @default 0
  27923. */
  27924. this.clearcoatRoughness = 0.0;
  27925. /**
  27926. * The green channel of this texture is multiplied against
  27927. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  27928. *
  27929. * @type {?Texture}
  27930. * @default null
  27931. */
  27932. this.clearcoatRoughnessMap = null;
  27933. /**
  27934. * How much `clearcoatNormalMap` affects the clear coat layer, from
  27935. * `(0,0)` to `(1,1)`.
  27936. *
  27937. * @type {Vector2}
  27938. * @default (1,1)
  27939. */
  27940. this.clearcoatNormalScale = new Vector2( 1, 1 );
  27941. /**
  27942. * Can be used to enable independent normals for the clear coat layer.
  27943. *
  27944. * @type {?Texture}
  27945. * @default null
  27946. */
  27947. this.clearcoatNormalMap = null;
  27948. /**
  27949. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  27950. *
  27951. * @type {number}
  27952. * @default 1.5
  27953. */
  27954. this.ior = 1.5;
  27955. /**
  27956. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  27957. * corresponds to an index-of-refraction of `1.5`.
  27958. *
  27959. * This models the reflectivity of non-metallic materials. It has no effect
  27960. * when `metalness` is `1.0`
  27961. *
  27962. * @name MeshPhysicalMaterial#reflectivity
  27963. * @type {number}
  27964. * @default 0.5
  27965. */
  27966. Object.defineProperty( this, 'reflectivity', {
  27967. get: function () {
  27968. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  27969. },
  27970. set: function ( reflectivity ) {
  27971. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  27972. }
  27973. } );
  27974. /**
  27975. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  27976. * control over iridescence.
  27977. *
  27978. * @type {?Texture}
  27979. * @default null
  27980. */
  27981. this.iridescenceMap = null;
  27982. /**
  27983. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  27984. * Between `1.0` to `2.333`.
  27985. *
  27986. * @type {number}
  27987. * @default 1.3
  27988. */
  27989. this.iridescenceIOR = 1.3;
  27990. /**
  27991. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  27992. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  27993. *
  27994. * @type {Array<number,number>}
  27995. * @default [100,400]
  27996. */
  27997. this.iridescenceThicknessRange = [ 100, 400 ];
  27998. /**
  27999. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  28000. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  28001. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  28002. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  28003. * - Values in-between will linearly interpolate between the elements of the array.
  28004. *
  28005. * @type {?Texture}
  28006. * @default null
  28007. */
  28008. this.iridescenceThicknessMap = null;
  28009. /**
  28010. * The sheen tint.
  28011. *
  28012. * @type {Color}
  28013. * @default (0,0,0)
  28014. */
  28015. this.sheenColor = new Color( 0x000000 );
  28016. /**
  28017. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  28018. * over sheen tint.
  28019. *
  28020. * @type {?Texture}
  28021. * @default null
  28022. */
  28023. this.sheenColorMap = null;
  28024. /**
  28025. * Roughness of the sheen layer, from `0.0` to `1.0`.
  28026. *
  28027. * @type {number}
  28028. * @default 1
  28029. */
  28030. this.sheenRoughness = 1.0;
  28031. /**
  28032. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28033. * over sheen roughness.
  28034. *
  28035. * @type {?Texture}
  28036. * @default null
  28037. */
  28038. this.sheenRoughnessMap = null;
  28039. /**
  28040. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28041. * optical transparency.
  28042. *
  28043. * @type {?Texture}
  28044. * @default null
  28045. */
  28046. this.transmissionMap = null;
  28047. /**
  28048. * The thickness of the volume beneath the surface. The value is given in the
  28049. * coordinate space of the mesh. If the value is `0` the material is
  28050. * thin-walled. Otherwise the material is a volume boundary.
  28051. *
  28052. * @type {number}
  28053. * @default 0
  28054. */
  28055. this.thickness = 0;
  28056. /**
  28057. * A texture that defines the thickness, stored in the green channel. This will
  28058. * be multiplied by `thickness`.
  28059. *
  28060. * @type {?Texture}
  28061. * @default null
  28062. */
  28063. this.thicknessMap = null;
  28064. /**
  28065. * Density of the medium given as the average distance that light travels in
  28066. * the medium before interacting with a particle. The value is given in world
  28067. * space units, and must be greater than zero.
  28068. *
  28069. * @type {number}
  28070. * @default Infinity
  28071. */
  28072. this.attenuationDistance = Infinity;
  28073. /**
  28074. * The color that white light turns into due to absorption when reaching the
  28075. * attenuation distance.
  28076. *
  28077. * @type {Color}
  28078. * @default (1,1,1)
  28079. */
  28080. this.attenuationColor = new Color( 1, 1, 1 );
  28081. /**
  28082. * A float that scales the amount of specular reflection for non-metals only.
  28083. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28084. *
  28085. * @type {number}
  28086. * @default 1
  28087. */
  28088. this.specularIntensity = 1.0;
  28089. /**
  28090. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28091. * for per-pixel control over specular intensity.
  28092. *
  28093. * @type {?Texture}
  28094. * @default null
  28095. */
  28096. this.specularIntensityMap = null;
  28097. /**
  28098. * Tints the specular reflection at normal incidence for non-metals only.
  28099. *
  28100. * @type {Color}
  28101. * @default (1,1,1)
  28102. */
  28103. this.specularColor = new Color( 1, 1, 1 );
  28104. /**
  28105. * The RGB channels of this texture are multiplied against `specularColor`,
  28106. * for per-pixel control over specular color.
  28107. *
  28108. * @type {?Texture}
  28109. * @default null
  28110. */
  28111. this.specularColorMap = null;
  28112. this._anisotropy = 0;
  28113. this._clearcoat = 0;
  28114. this._dispersion = 0;
  28115. this._iridescence = 0;
  28116. this._sheen = 0.0;
  28117. this._transmission = 0;
  28118. this.setValues( parameters );
  28119. }
  28120. /**
  28121. * The anisotropy strength.
  28122. *
  28123. * @type {number}
  28124. * @default 0
  28125. */
  28126. get anisotropy() {
  28127. return this._anisotropy;
  28128. }
  28129. set anisotropy( value ) {
  28130. if ( this._anisotropy > 0 !== value > 0 ) {
  28131. this.version ++;
  28132. }
  28133. this._anisotropy = value;
  28134. }
  28135. /**
  28136. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28137. * clear coat related properties to enable multilayer materials that have a
  28138. * thin translucent layer over the base layer.
  28139. *
  28140. * @type {number}
  28141. * @default 0
  28142. */
  28143. get clearcoat() {
  28144. return this._clearcoat;
  28145. }
  28146. set clearcoat( value ) {
  28147. if ( this._clearcoat > 0 !== value > 0 ) {
  28148. this.version ++;
  28149. }
  28150. this._clearcoat = value;
  28151. }
  28152. /**
  28153. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28154. * the surface and the viewer, from `0.0` to `1.0`.
  28155. *
  28156. * @type {number}
  28157. * @default 0
  28158. */
  28159. get iridescence() {
  28160. return this._iridescence;
  28161. }
  28162. set iridescence( value ) {
  28163. if ( this._iridescence > 0 !== value > 0 ) {
  28164. this.version ++;
  28165. }
  28166. this._iridescence = value;
  28167. }
  28168. /**
  28169. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28170. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28171. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28172. *
  28173. * @type {number}
  28174. * @default 0
  28175. */
  28176. get dispersion() {
  28177. return this._dispersion;
  28178. }
  28179. set dispersion( value ) {
  28180. if ( this._dispersion > 0 !== value > 0 ) {
  28181. this.version ++;
  28182. }
  28183. this._dispersion = value;
  28184. }
  28185. /**
  28186. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28187. *
  28188. * @type {number}
  28189. * @default 0
  28190. */
  28191. get sheen() {
  28192. return this._sheen;
  28193. }
  28194. set sheen( value ) {
  28195. if ( this._sheen > 0 !== value > 0 ) {
  28196. this.version ++;
  28197. }
  28198. this._sheen = value;
  28199. }
  28200. /**
  28201. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28202. *
  28203. * Thin, transparent or semitransparent, plastic or glass materials remain
  28204. * largely reflective even if they are fully transmissive. The transmission
  28205. * property can be used to model these materials.
  28206. *
  28207. * When transmission is non-zero, `opacity` should be set to `1`.
  28208. *
  28209. * @type {number}
  28210. * @default 0
  28211. */
  28212. get transmission() {
  28213. return this._transmission;
  28214. }
  28215. set transmission( value ) {
  28216. if ( this._transmission > 0 !== value > 0 ) {
  28217. this.version ++;
  28218. }
  28219. this._transmission = value;
  28220. }
  28221. copy( source ) {
  28222. super.copy( source );
  28223. this.defines = {
  28224. 'STANDARD': '',
  28225. 'PHYSICAL': ''
  28226. };
  28227. this.anisotropy = source.anisotropy;
  28228. this.anisotropyRotation = source.anisotropyRotation;
  28229. this.anisotropyMap = source.anisotropyMap;
  28230. this.clearcoat = source.clearcoat;
  28231. this.clearcoatMap = source.clearcoatMap;
  28232. this.clearcoatRoughness = source.clearcoatRoughness;
  28233. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28234. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28235. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28236. this.dispersion = source.dispersion;
  28237. this.ior = source.ior;
  28238. this.iridescence = source.iridescence;
  28239. this.iridescenceMap = source.iridescenceMap;
  28240. this.iridescenceIOR = source.iridescenceIOR;
  28241. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28242. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28243. this.sheen = source.sheen;
  28244. this.sheenColor.copy( source.sheenColor );
  28245. this.sheenColorMap = source.sheenColorMap;
  28246. this.sheenRoughness = source.sheenRoughness;
  28247. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28248. this.transmission = source.transmission;
  28249. this.transmissionMap = source.transmissionMap;
  28250. this.thickness = source.thickness;
  28251. this.thicknessMap = source.thicknessMap;
  28252. this.attenuationDistance = source.attenuationDistance;
  28253. this.attenuationColor.copy( source.attenuationColor );
  28254. this.specularIntensity = source.specularIntensity;
  28255. this.specularIntensityMap = source.specularIntensityMap;
  28256. this.specularColor.copy( source.specularColor );
  28257. this.specularColorMap = source.specularColorMap;
  28258. return this;
  28259. }
  28260. }
  28261. /**
  28262. * A material for shiny surfaces with specular highlights.
  28263. *
  28264. * The material uses a non-physically based [Blinn-Phong]{@link https://en.wikipedia.org/wiki/Blinn-Phong_shading_model}
  28265. * model for calculating reflectance. Unlike the Lambertian model used in the
  28266. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28267. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28268. *
  28269. * Performance will generally be greater when using this material over the
  28270. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28271. * some graphical accuracy.
  28272. *
  28273. * @augments Material
  28274. */
  28275. class MeshPhongMaterial extends Material {
  28276. /**
  28277. * Constructs a new mesh phong material.
  28278. *
  28279. * @param {Object} [parameters] - An object with one or more properties
  28280. * defining the material's appearance. Any property of the material
  28281. * (including any property from inherited materials) can be passed
  28282. * in here. Color values can be passed any type of value accepted
  28283. * by {@link Color#set}.
  28284. */
  28285. constructor( parameters ) {
  28286. super();
  28287. /**
  28288. * This flag can be used for type testing.
  28289. *
  28290. * @type {boolean}
  28291. * @readonly
  28292. * @default true
  28293. */
  28294. this.isMeshPhongMaterial = true;
  28295. this.type = 'MeshPhongMaterial';
  28296. /**
  28297. * Color of the material.
  28298. *
  28299. * @type {Color}
  28300. * @default (1,1,1)
  28301. */
  28302. this.color = new Color( 0xffffff ); // diffuse
  28303. /**
  28304. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28305. *
  28306. * This defines how shiny the material is and the color of its shine.
  28307. *
  28308. * @type {Color}
  28309. */
  28310. this.specular = new Color( 0x111111 );
  28311. /**
  28312. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28313. *
  28314. * @type {number}
  28315. * @default 30
  28316. */
  28317. this.shininess = 30;
  28318. /**
  28319. * The color map. May optionally include an alpha channel, typically combined
  28320. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28321. * color is modulated by the diffuse `color`.
  28322. *
  28323. * @type {?Texture}
  28324. * @default null
  28325. */
  28326. this.map = null;
  28327. /**
  28328. * The light map. Requires a second set of UVs.
  28329. *
  28330. * @type {?Texture}
  28331. * @default null
  28332. */
  28333. this.lightMap = null;
  28334. /**
  28335. * Intensity of the baked light.
  28336. *
  28337. * @type {number}
  28338. * @default 1
  28339. */
  28340. this.lightMapIntensity = 1.0;
  28341. /**
  28342. * The red channel of this texture is used as the ambient occlusion map.
  28343. * Requires a second set of UVs.
  28344. *
  28345. * @type {?Texture}
  28346. * @default null
  28347. */
  28348. this.aoMap = null;
  28349. /**
  28350. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28351. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28352. * red channel is also `1`, ambient light is fully occluded on a surface.
  28353. *
  28354. * @type {number}
  28355. * @default 1
  28356. */
  28357. this.aoMapIntensity = 1.0;
  28358. /**
  28359. * Emissive (light) color of the material, essentially a solid color
  28360. * unaffected by other lighting.
  28361. *
  28362. * @type {Color}
  28363. * @default (0,0,0)
  28364. */
  28365. this.emissive = new Color( 0x000000 );
  28366. /**
  28367. * Intensity of the emissive light. Modulates the emissive color.
  28368. *
  28369. * @type {number}
  28370. * @default 1
  28371. */
  28372. this.emissiveIntensity = 1.0;
  28373. /**
  28374. * Set emissive (glow) map. The emissive map color is modulated by the
  28375. * emissive color and the emissive intensity. If you have an emissive map,
  28376. * be sure to set the emissive color to something other than black.
  28377. *
  28378. * @type {?Texture}
  28379. * @default null
  28380. */
  28381. this.emissiveMap = null;
  28382. /**
  28383. * The texture to create a bump map. The black and white values map to the
  28384. * perceived depth in relation to the lights. Bump doesn't actually affect
  28385. * the geometry of the object, only the lighting. If a normal map is defined
  28386. * this will be ignored.
  28387. *
  28388. * @type {?Texture}
  28389. * @default null
  28390. */
  28391. this.bumpMap = null;
  28392. /**
  28393. * How much the bump map affects the material. Typical range is `[0,1]`.
  28394. *
  28395. * @type {number}
  28396. * @default 1
  28397. */
  28398. this.bumpScale = 1;
  28399. /**
  28400. * The texture to create a normal map. The RGB values affect the surface
  28401. * normal for each pixel fragment and change the way the color is lit. Normal
  28402. * maps do not change the actual shape of the surface, only the lighting. In
  28403. * case the material has a normal map authored using the left handed
  28404. * convention, the `y` component of `normalScale` should be negated to compensate
  28405. * for the different handedness.
  28406. *
  28407. * @type {?Texture}
  28408. * @default null
  28409. */
  28410. this.normalMap = null;
  28411. /**
  28412. * The type of normal map.
  28413. *
  28414. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28415. * @default TangentSpaceNormalMap
  28416. */
  28417. this.normalMapType = TangentSpaceNormalMap;
  28418. /**
  28419. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28420. *
  28421. * @type {Vector2}
  28422. * @default (1,1)
  28423. */
  28424. this.normalScale = new Vector2( 1, 1 );
  28425. /**
  28426. * The displacement map affects the position of the mesh's vertices. Unlike
  28427. * other maps which only affect the light and shade of the material the
  28428. * displaced vertices can cast shadows, block other objects, and otherwise
  28429. * act as real geometry. The displacement texture is an image where the value
  28430. * of each pixel (white being the highest) is mapped against, and
  28431. * repositions, the vertices of the mesh.
  28432. *
  28433. * @type {?Texture}
  28434. * @default null
  28435. */
  28436. this.displacementMap = null;
  28437. /**
  28438. * How much the displacement map affects the mesh (where black is no
  28439. * displacement, and white is maximum displacement). Without a displacement
  28440. * map set, this value is not applied.
  28441. *
  28442. * @type {number}
  28443. * @default 0
  28444. */
  28445. this.displacementScale = 1;
  28446. /**
  28447. * The offset of the displacement map's values on the mesh's vertices.
  28448. * The bias is added to the scaled sample of the displacement map.
  28449. * Without a displacement map set, this value is not applied.
  28450. *
  28451. * @type {number}
  28452. * @default 0
  28453. */
  28454. this.displacementBias = 0;
  28455. /**
  28456. * The specular map value affects both how much the specular surface
  28457. * highlight contributes and how much of the environment map affects the
  28458. * surface.
  28459. *
  28460. * @type {?Texture}
  28461. * @default null
  28462. */
  28463. this.specularMap = null;
  28464. /**
  28465. * The alpha map is a grayscale texture that controls the opacity across the
  28466. * surface (black: fully transparent; white: fully opaque).
  28467. *
  28468. * Only the color of the texture is used, ignoring the alpha channel if one
  28469. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28470. * when sampling this texture due to the extra bit of precision provided for
  28471. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28472. * luminance/alpha textures will also still work as expected.
  28473. *
  28474. * @type {?Texture}
  28475. * @default null
  28476. */
  28477. this.alphaMap = null;
  28478. /**
  28479. * The environment map.
  28480. *
  28481. * @type {?Texture}
  28482. * @default null
  28483. */
  28484. this.envMap = null;
  28485. /**
  28486. * The rotation of the environment map in radians.
  28487. *
  28488. * @type {Euler}
  28489. * @default (0,0,0)
  28490. */
  28491. this.envMapRotation = new Euler();
  28492. /**
  28493. * How to combine the result of the surface's color with the environment map, if any.
  28494. *
  28495. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  28496. * blend between the two colors.
  28497. *
  28498. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  28499. * @default MultiplyOperation
  28500. */
  28501. this.combine = MultiplyOperation;
  28502. /**
  28503. * How much the environment map affects the surface.
  28504. * The valid range is between `0` (no reflections) and `1` (full reflections).
  28505. *
  28506. * @type {number}
  28507. * @default 1
  28508. */
  28509. this.reflectivity = 1;
  28510. /**
  28511. * The index of refraction (IOR) of air (approximately 1) divided by the
  28512. * index of refraction of the material. It is used with environment mapping
  28513. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  28514. * The refraction ratio should not exceed `1`.
  28515. *
  28516. * @type {number}
  28517. * @default 0.98
  28518. */
  28519. this.refractionRatio = 0.98;
  28520. /**
  28521. * Renders the geometry as a wireframe.
  28522. *
  28523. * @type {boolean}
  28524. * @default false
  28525. */
  28526. this.wireframe = false;
  28527. /**
  28528. * Controls the thickness of the wireframe.
  28529. *
  28530. * Can only be used with {@link SVGRenderer}.
  28531. *
  28532. * @type {number}
  28533. * @default 1
  28534. */
  28535. this.wireframeLinewidth = 1;
  28536. /**
  28537. * Defines appearance of wireframe ends.
  28538. *
  28539. * Can only be used with {@link SVGRenderer}.
  28540. *
  28541. * @type {('round'|'bevel'|'miter')}
  28542. * @default 'round'
  28543. */
  28544. this.wireframeLinecap = 'round';
  28545. /**
  28546. * Defines appearance of wireframe joints.
  28547. *
  28548. * Can only be used with {@link SVGRenderer}.
  28549. *
  28550. * @type {('round'|'bevel'|'miter')}
  28551. * @default 'round'
  28552. */
  28553. this.wireframeLinejoin = 'round';
  28554. /**
  28555. * Whether the material is rendered with flat shading or not.
  28556. *
  28557. * @type {boolean}
  28558. * @default false
  28559. */
  28560. this.flatShading = false;
  28561. /**
  28562. * Whether the material is affected by fog or not.
  28563. *
  28564. * @type {boolean}
  28565. * @default true
  28566. */
  28567. this.fog = true;
  28568. this.setValues( parameters );
  28569. }
  28570. copy( source ) {
  28571. super.copy( source );
  28572. this.color.copy( source.color );
  28573. this.specular.copy( source.specular );
  28574. this.shininess = source.shininess;
  28575. this.map = source.map;
  28576. this.lightMap = source.lightMap;
  28577. this.lightMapIntensity = source.lightMapIntensity;
  28578. this.aoMap = source.aoMap;
  28579. this.aoMapIntensity = source.aoMapIntensity;
  28580. this.emissive.copy( source.emissive );
  28581. this.emissiveMap = source.emissiveMap;
  28582. this.emissiveIntensity = source.emissiveIntensity;
  28583. this.bumpMap = source.bumpMap;
  28584. this.bumpScale = source.bumpScale;
  28585. this.normalMap = source.normalMap;
  28586. this.normalMapType = source.normalMapType;
  28587. this.normalScale.copy( source.normalScale );
  28588. this.displacementMap = source.displacementMap;
  28589. this.displacementScale = source.displacementScale;
  28590. this.displacementBias = source.displacementBias;
  28591. this.specularMap = source.specularMap;
  28592. this.alphaMap = source.alphaMap;
  28593. this.envMap = source.envMap;
  28594. this.envMapRotation.copy( source.envMapRotation );
  28595. this.combine = source.combine;
  28596. this.reflectivity = source.reflectivity;
  28597. this.refractionRatio = source.refractionRatio;
  28598. this.wireframe = source.wireframe;
  28599. this.wireframeLinewidth = source.wireframeLinewidth;
  28600. this.wireframeLinecap = source.wireframeLinecap;
  28601. this.wireframeLinejoin = source.wireframeLinejoin;
  28602. this.flatShading = source.flatShading;
  28603. this.fog = source.fog;
  28604. return this;
  28605. }
  28606. }
  28607. /**
  28608. * A material implementing toon shading.
  28609. *
  28610. * @augments Material
  28611. */
  28612. class MeshToonMaterial extends Material {
  28613. /**
  28614. * Constructs a new mesh toon material.
  28615. *
  28616. * @param {Object} [parameters] - An object with one or more properties
  28617. * defining the material's appearance. Any property of the material
  28618. * (including any property from inherited materials) can be passed
  28619. * in here. Color values can be passed any type of value accepted
  28620. * by {@link Color#set}.
  28621. */
  28622. constructor( parameters ) {
  28623. super();
  28624. /**
  28625. * This flag can be used for type testing.
  28626. *
  28627. * @type {boolean}
  28628. * @readonly
  28629. * @default true
  28630. */
  28631. this.isMeshToonMaterial = true;
  28632. this.defines = { 'TOON': '' };
  28633. this.type = 'MeshToonMaterial';
  28634. /**
  28635. * Color of the material.
  28636. *
  28637. * @type {Color}
  28638. * @default (1,1,1)
  28639. */
  28640. this.color = new Color( 0xffffff );
  28641. /**
  28642. * The color map. May optionally include an alpha channel, typically combined
  28643. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28644. * color is modulated by the diffuse `color`.
  28645. *
  28646. * @type {?Texture}
  28647. * @default null
  28648. */
  28649. this.map = null;
  28650. /**
  28651. * Gradient map for toon shading. It's required to set
  28652. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@linkNearestFilter}
  28653. * when using this type of texture.
  28654. *
  28655. * @type {?Texture}
  28656. * @default null
  28657. */
  28658. this.gradientMap = null;
  28659. /**
  28660. * The light map. Requires a second set of UVs.
  28661. *
  28662. * @type {?Texture}
  28663. * @default null
  28664. */
  28665. this.lightMap = null;
  28666. /**
  28667. * Intensity of the baked light.
  28668. *
  28669. * @type {number}
  28670. * @default 1
  28671. */
  28672. this.lightMapIntensity = 1.0;
  28673. /**
  28674. * The red channel of this texture is used as the ambient occlusion map.
  28675. * Requires a second set of UVs.
  28676. *
  28677. * @type {?Texture}
  28678. * @default null
  28679. */
  28680. this.aoMap = null;
  28681. /**
  28682. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28683. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28684. * red channel is also `1`, ambient light is fully occluded on a surface.
  28685. *
  28686. * @type {number}
  28687. * @default 1
  28688. */
  28689. this.aoMapIntensity = 1.0;
  28690. /**
  28691. * Emissive (light) color of the material, essentially a solid color
  28692. * unaffected by other lighting.
  28693. *
  28694. * @type {Color}
  28695. * @default (0,0,0)
  28696. */
  28697. this.emissive = new Color( 0x000000 );
  28698. /**
  28699. * Intensity of the emissive light. Modulates the emissive color.
  28700. *
  28701. * @type {number}
  28702. * @default 1
  28703. */
  28704. this.emissiveIntensity = 1.0;
  28705. /**
  28706. * Set emissive (glow) map. The emissive map color is modulated by the
  28707. * emissive color and the emissive intensity. If you have an emissive map,
  28708. * be sure to set the emissive color to something other than black.
  28709. *
  28710. * @type {?Texture}
  28711. * @default null
  28712. */
  28713. this.emissiveMap = null;
  28714. /**
  28715. * The texture to create a bump map. The black and white values map to the
  28716. * perceived depth in relation to the lights. Bump doesn't actually affect
  28717. * the geometry of the object, only the lighting. If a normal map is defined
  28718. * this will be ignored.
  28719. *
  28720. * @type {?Texture}
  28721. * @default null
  28722. */
  28723. this.bumpMap = null;
  28724. /**
  28725. * How much the bump map affects the material. Typical range is `[0,1]`.
  28726. *
  28727. * @type {number}
  28728. * @default 1
  28729. */
  28730. this.bumpScale = 1;
  28731. /**
  28732. * The texture to create a normal map. The RGB values affect the surface
  28733. * normal for each pixel fragment and change the way the color is lit. Normal
  28734. * maps do not change the actual shape of the surface, only the lighting. In
  28735. * case the material has a normal map authored using the left handed
  28736. * convention, the `y` component of `normalScale` should be negated to compensate
  28737. * for the different handedness.
  28738. *
  28739. * @type {?Texture}
  28740. * @default null
  28741. */
  28742. this.normalMap = null;
  28743. /**
  28744. * The type of normal map.
  28745. *
  28746. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28747. * @default TangentSpaceNormalMap
  28748. */
  28749. this.normalMapType = TangentSpaceNormalMap;
  28750. /**
  28751. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28752. *
  28753. * @type {Vector2}
  28754. * @default (1,1)
  28755. */
  28756. this.normalScale = new Vector2( 1, 1 );
  28757. /**
  28758. * The displacement map affects the position of the mesh's vertices. Unlike
  28759. * other maps which only affect the light and shade of the material the
  28760. * displaced vertices can cast shadows, block other objects, and otherwise
  28761. * act as real geometry. The displacement texture is an image where the value
  28762. * of each pixel (white being the highest) is mapped against, and
  28763. * repositions, the vertices of the mesh.
  28764. *
  28765. * @type {?Texture}
  28766. * @default null
  28767. */
  28768. this.displacementMap = null;
  28769. /**
  28770. * How much the displacement map affects the mesh (where black is no
  28771. * displacement, and white is maximum displacement). Without a displacement
  28772. * map set, this value is not applied.
  28773. *
  28774. * @type {number}
  28775. * @default 0
  28776. */
  28777. this.displacementScale = 1;
  28778. /**
  28779. * The offset of the displacement map's values on the mesh's vertices.
  28780. * The bias is added to the scaled sample of the displacement map.
  28781. * Without a displacement map set, this value is not applied.
  28782. *
  28783. * @type {number}
  28784. * @default 0
  28785. */
  28786. this.displacementBias = 0;
  28787. /**
  28788. * The alpha map is a grayscale texture that controls the opacity across the
  28789. * surface (black: fully transparent; white: fully opaque).
  28790. *
  28791. * Only the color of the texture is used, ignoring the alpha channel if one
  28792. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28793. * when sampling this texture due to the extra bit of precision provided for
  28794. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28795. * luminance/alpha textures will also still work as expected.
  28796. *
  28797. * @type {?Texture}
  28798. * @default null
  28799. */
  28800. this.alphaMap = null;
  28801. /**
  28802. * Renders the geometry as a wireframe.
  28803. *
  28804. * @type {boolean}
  28805. * @default false
  28806. */
  28807. this.wireframe = false;
  28808. /**
  28809. * Controls the thickness of the wireframe.
  28810. *
  28811. * Can only be used with {@link SVGRenderer}.
  28812. *
  28813. * @type {number}
  28814. * @default 1
  28815. */
  28816. this.wireframeLinewidth = 1;
  28817. /**
  28818. * Defines appearance of wireframe ends.
  28819. *
  28820. * Can only be used with {@link SVGRenderer}.
  28821. *
  28822. * @type {('round'|'bevel'|'miter')}
  28823. * @default 'round'
  28824. */
  28825. this.wireframeLinecap = 'round';
  28826. /**
  28827. * Defines appearance of wireframe joints.
  28828. *
  28829. * Can only be used with {@link SVGRenderer}.
  28830. *
  28831. * @type {('round'|'bevel'|'miter')}
  28832. * @default 'round'
  28833. */
  28834. this.wireframeLinejoin = 'round';
  28835. /**
  28836. * Whether the material is affected by fog or not.
  28837. *
  28838. * @type {boolean}
  28839. * @default true
  28840. */
  28841. this.fog = true;
  28842. this.setValues( parameters );
  28843. }
  28844. copy( source ) {
  28845. super.copy( source );
  28846. this.color.copy( source.color );
  28847. this.map = source.map;
  28848. this.gradientMap = source.gradientMap;
  28849. this.lightMap = source.lightMap;
  28850. this.lightMapIntensity = source.lightMapIntensity;
  28851. this.aoMap = source.aoMap;
  28852. this.aoMapIntensity = source.aoMapIntensity;
  28853. this.emissive.copy( source.emissive );
  28854. this.emissiveMap = source.emissiveMap;
  28855. this.emissiveIntensity = source.emissiveIntensity;
  28856. this.bumpMap = source.bumpMap;
  28857. this.bumpScale = source.bumpScale;
  28858. this.normalMap = source.normalMap;
  28859. this.normalMapType = source.normalMapType;
  28860. this.normalScale.copy( source.normalScale );
  28861. this.displacementMap = source.displacementMap;
  28862. this.displacementScale = source.displacementScale;
  28863. this.displacementBias = source.displacementBias;
  28864. this.alphaMap = source.alphaMap;
  28865. this.wireframe = source.wireframe;
  28866. this.wireframeLinewidth = source.wireframeLinewidth;
  28867. this.wireframeLinecap = source.wireframeLinecap;
  28868. this.wireframeLinejoin = source.wireframeLinejoin;
  28869. this.fog = source.fog;
  28870. return this;
  28871. }
  28872. }
  28873. /**
  28874. * A material that maps the normal vectors to RGB colors.
  28875. *
  28876. * @augments Material
  28877. */
  28878. class MeshNormalMaterial extends Material {
  28879. /**
  28880. * Constructs a new mesh normal material.
  28881. *
  28882. * @param {Object} [parameters] - An object with one or more properties
  28883. * defining the material's appearance. Any property of the material
  28884. * (including any property from inherited materials) can be passed
  28885. * in here. Color values can be passed any type of value accepted
  28886. * by {@link Color#set}.
  28887. */
  28888. constructor( parameters ) {
  28889. super();
  28890. /**
  28891. * This flag can be used for type testing.
  28892. *
  28893. * @type {boolean}
  28894. * @readonly
  28895. * @default true
  28896. */
  28897. this.isMeshNormalMaterial = true;
  28898. this.type = 'MeshNormalMaterial';
  28899. /**
  28900. * The texture to create a bump map. The black and white values map to the
  28901. * perceived depth in relation to the lights. Bump doesn't actually affect
  28902. * the geometry of the object, only the lighting. If a normal map is defined
  28903. * this will be ignored.
  28904. *
  28905. * @type {?Texture}
  28906. * @default null
  28907. */
  28908. this.bumpMap = null;
  28909. /**
  28910. * How much the bump map affects the material. Typical range is `[0,1]`.
  28911. *
  28912. * @type {number}
  28913. * @default 1
  28914. */
  28915. this.bumpScale = 1;
  28916. /**
  28917. * The texture to create a normal map. The RGB values affect the surface
  28918. * normal for each pixel fragment and change the way the color is lit. Normal
  28919. * maps do not change the actual shape of the surface, only the lighting. In
  28920. * case the material has a normal map authored using the left handed
  28921. * convention, the `y` component of `normalScale` should be negated to compensate
  28922. * for the different handedness.
  28923. *
  28924. * @type {?Texture}
  28925. * @default null
  28926. */
  28927. this.normalMap = null;
  28928. /**
  28929. * The type of normal map.
  28930. *
  28931. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28932. * @default TangentSpaceNormalMap
  28933. */
  28934. this.normalMapType = TangentSpaceNormalMap;
  28935. /**
  28936. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28937. *
  28938. * @type {Vector2}
  28939. * @default (1,1)
  28940. */
  28941. this.normalScale = new Vector2( 1, 1 );
  28942. /**
  28943. * The displacement map affects the position of the mesh's vertices. Unlike
  28944. * other maps which only affect the light and shade of the material the
  28945. * displaced vertices can cast shadows, block other objects, and otherwise
  28946. * act as real geometry. The displacement texture is an image where the value
  28947. * of each pixel (white being the highest) is mapped against, and
  28948. * repositions, the vertices of the mesh.
  28949. *
  28950. * @type {?Texture}
  28951. * @default null
  28952. */
  28953. this.displacementMap = null;
  28954. /**
  28955. * How much the displacement map affects the mesh (where black is no
  28956. * displacement, and white is maximum displacement). Without a displacement
  28957. * map set, this value is not applied.
  28958. *
  28959. * @type {number}
  28960. * @default 0
  28961. */
  28962. this.displacementScale = 1;
  28963. /**
  28964. * The offset of the displacement map's values on the mesh's vertices.
  28965. * The bias is added to the scaled sample of the displacement map.
  28966. * Without a displacement map set, this value is not applied.
  28967. *
  28968. * @type {number}
  28969. * @default 0
  28970. */
  28971. this.displacementBias = 0;
  28972. /**
  28973. * Renders the geometry as a wireframe.
  28974. *
  28975. * @type {boolean}
  28976. * @default false
  28977. */
  28978. this.wireframe = false;
  28979. /**
  28980. * Controls the thickness of the wireframe.
  28981. *
  28982. * WebGL and WebGPU ignore this property and always render
  28983. * 1 pixel wide lines.
  28984. *
  28985. * @type {number}
  28986. * @default 1
  28987. */
  28988. this.wireframeLinewidth = 1;
  28989. /**
  28990. * Whether the material is rendered with flat shading or not.
  28991. *
  28992. * @type {boolean}
  28993. * @default false
  28994. */
  28995. this.flatShading = false;
  28996. this.setValues( parameters );
  28997. }
  28998. copy( source ) {
  28999. super.copy( source );
  29000. this.bumpMap = source.bumpMap;
  29001. this.bumpScale = source.bumpScale;
  29002. this.normalMap = source.normalMap;
  29003. this.normalMapType = source.normalMapType;
  29004. this.normalScale.copy( source.normalScale );
  29005. this.displacementMap = source.displacementMap;
  29006. this.displacementScale = source.displacementScale;
  29007. this.displacementBias = source.displacementBias;
  29008. this.wireframe = source.wireframe;
  29009. this.wireframeLinewidth = source.wireframeLinewidth;
  29010. this.flatShading = source.flatShading;
  29011. return this;
  29012. }
  29013. }
  29014. /**
  29015. * A material for non-shiny surfaces, without specular highlights.
  29016. *
  29017. * The material uses a non-physically based [Lambertian]{@link https://en.wikipedia.org/wiki/Lambertian_reflectance}
  29018. * model for calculating reflectance. This can simulate some surfaces (such
  29019. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29020. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29021. * shading.
  29022. *
  29023. * Due to the simplicity of the reflectance and illumination models,
  29024. * performance will be greater when using this material over the
  29025. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29026. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29027. *
  29028. * @augments Material
  29029. */
  29030. class MeshLambertMaterial extends Material {
  29031. /**
  29032. * Constructs a new mesh lambert material.
  29033. *
  29034. * @param {Object} [parameters] - An object with one or more properties
  29035. * defining the material's appearance. Any property of the material
  29036. * (including any property from inherited materials) can be passed
  29037. * in here. Color values can be passed any type of value accepted
  29038. * by {@link Color#set}.
  29039. */
  29040. constructor( parameters ) {
  29041. super();
  29042. /**
  29043. * This flag can be used for type testing.
  29044. *
  29045. * @type {boolean}
  29046. * @readonly
  29047. * @default true
  29048. */
  29049. this.isMeshLambertMaterial = true;
  29050. this.type = 'MeshLambertMaterial';
  29051. /**
  29052. * Color of the material.
  29053. *
  29054. * @type {Color}
  29055. * @default (1,1,1)
  29056. */
  29057. this.color = new Color( 0xffffff ); // diffuse
  29058. /**
  29059. * The color map. May optionally include an alpha channel, typically combined
  29060. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29061. * color is modulated by the diffuse `color`.
  29062. *
  29063. * @type {?Texture}
  29064. * @default null
  29065. */
  29066. this.map = null;
  29067. /**
  29068. * The light map. Requires a second set of UVs.
  29069. *
  29070. * @type {?Texture}
  29071. * @default null
  29072. */
  29073. this.lightMap = null;
  29074. /**
  29075. * Intensity of the baked light.
  29076. *
  29077. * @type {number}
  29078. * @default 1
  29079. */
  29080. this.lightMapIntensity = 1.0;
  29081. /**
  29082. * The red channel of this texture is used as the ambient occlusion map.
  29083. * Requires a second set of UVs.
  29084. *
  29085. * @type {?Texture}
  29086. * @default null
  29087. */
  29088. this.aoMap = null;
  29089. /**
  29090. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29091. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29092. * red channel is also `1`, ambient light is fully occluded on a surface.
  29093. *
  29094. * @type {number}
  29095. * @default 1
  29096. */
  29097. this.aoMapIntensity = 1.0;
  29098. /**
  29099. * Emissive (light) color of the material, essentially a solid color
  29100. * unaffected by other lighting.
  29101. *
  29102. * @type {Color}
  29103. * @default (0,0,0)
  29104. */
  29105. this.emissive = new Color( 0x000000 );
  29106. /**
  29107. * Intensity of the emissive light. Modulates the emissive color.
  29108. *
  29109. * @type {number}
  29110. * @default 1
  29111. */
  29112. this.emissiveIntensity = 1.0;
  29113. /**
  29114. * Set emissive (glow) map. The emissive map color is modulated by the
  29115. * emissive color and the emissive intensity. If you have an emissive map,
  29116. * be sure to set the emissive color to something other than black.
  29117. *
  29118. * @type {?Texture}
  29119. * @default null
  29120. */
  29121. this.emissiveMap = null;
  29122. /**
  29123. * The texture to create a bump map. The black and white values map to the
  29124. * perceived depth in relation to the lights. Bump doesn't actually affect
  29125. * the geometry of the object, only the lighting. If a normal map is defined
  29126. * this will be ignored.
  29127. *
  29128. * @type {?Texture}
  29129. * @default null
  29130. */
  29131. this.bumpMap = null;
  29132. /**
  29133. * How much the bump map affects the material. Typical range is `[0,1]`.
  29134. *
  29135. * @type {number}
  29136. * @default 1
  29137. */
  29138. this.bumpScale = 1;
  29139. /**
  29140. * The texture to create a normal map. The RGB values affect the surface
  29141. * normal for each pixel fragment and change the way the color is lit. Normal
  29142. * maps do not change the actual shape of the surface, only the lighting. In
  29143. * case the material has a normal map authored using the left handed
  29144. * convention, the `y` component of `normalScale` should be negated to compensate
  29145. * for the different handedness.
  29146. *
  29147. * @type {?Texture}
  29148. * @default null
  29149. */
  29150. this.normalMap = null;
  29151. /**
  29152. * The type of normal map.
  29153. *
  29154. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29155. * @default TangentSpaceNormalMap
  29156. */
  29157. this.normalMapType = TangentSpaceNormalMap;
  29158. /**
  29159. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29160. *
  29161. * @type {Vector2}
  29162. * @default (1,1)
  29163. */
  29164. this.normalScale = new Vector2( 1, 1 );
  29165. /**
  29166. * The displacement map affects the position of the mesh's vertices. Unlike
  29167. * other maps which only affect the light and shade of the material the
  29168. * displaced vertices can cast shadows, block other objects, and otherwise
  29169. * act as real geometry. The displacement texture is an image where the value
  29170. * of each pixel (white being the highest) is mapped against, and
  29171. * repositions, the vertices of the mesh.
  29172. *
  29173. * @type {?Texture}
  29174. * @default null
  29175. */
  29176. this.displacementMap = null;
  29177. /**
  29178. * How much the displacement map affects the mesh (where black is no
  29179. * displacement, and white is maximum displacement). Without a displacement
  29180. * map set, this value is not applied.
  29181. *
  29182. * @type {number}
  29183. * @default 0
  29184. */
  29185. this.displacementScale = 1;
  29186. /**
  29187. * The offset of the displacement map's values on the mesh's vertices.
  29188. * The bias is added to the scaled sample of the displacement map.
  29189. * Without a displacement map set, this value is not applied.
  29190. *
  29191. * @type {number}
  29192. * @default 0
  29193. */
  29194. this.displacementBias = 0;
  29195. /**
  29196. * Specular map used by the material.
  29197. *
  29198. * @type {?Texture}
  29199. * @default null
  29200. */
  29201. this.specularMap = null;
  29202. /**
  29203. * The alpha map is a grayscale texture that controls the opacity across the
  29204. * surface (black: fully transparent; white: fully opaque).
  29205. *
  29206. * Only the color of the texture is used, ignoring the alpha channel if one
  29207. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29208. * when sampling this texture due to the extra bit of precision provided for
  29209. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29210. * luminance/alpha textures will also still work as expected.
  29211. *
  29212. * @type {?Texture}
  29213. * @default null
  29214. */
  29215. this.alphaMap = null;
  29216. /**
  29217. * The environment map.
  29218. *
  29219. * @type {?Texture}
  29220. * @default null
  29221. */
  29222. this.envMap = null;
  29223. /**
  29224. * The rotation of the environment map in radians.
  29225. *
  29226. * @type {Euler}
  29227. * @default (0,0,0)
  29228. */
  29229. this.envMapRotation = new Euler();
  29230. /**
  29231. * How to combine the result of the surface's color with the environment map, if any.
  29232. *
  29233. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29234. * blend between the two colors.
  29235. *
  29236. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29237. * @default MultiplyOperation
  29238. */
  29239. this.combine = MultiplyOperation;
  29240. /**
  29241. * How much the environment map affects the surface.
  29242. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29243. *
  29244. * @type {number}
  29245. * @default 1
  29246. */
  29247. this.reflectivity = 1;
  29248. /**
  29249. * The index of refraction (IOR) of air (approximately 1) divided by the
  29250. * index of refraction of the material. It is used with environment mapping
  29251. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29252. * The refraction ratio should not exceed `1`.
  29253. *
  29254. * @type {number}
  29255. * @default 0.98
  29256. */
  29257. this.refractionRatio = 0.98;
  29258. /**
  29259. * Renders the geometry as a wireframe.
  29260. *
  29261. * @type {boolean}
  29262. * @default false
  29263. */
  29264. this.wireframe = false;
  29265. /**
  29266. * Controls the thickness of the wireframe.
  29267. *
  29268. * Can only be used with {@link SVGRenderer}.
  29269. *
  29270. * @type {number}
  29271. * @default 1
  29272. */
  29273. this.wireframeLinewidth = 1;
  29274. /**
  29275. * Defines appearance of wireframe ends.
  29276. *
  29277. * Can only be used with {@link SVGRenderer}.
  29278. *
  29279. * @type {('round'|'bevel'|'miter')}
  29280. * @default 'round'
  29281. */
  29282. this.wireframeLinecap = 'round';
  29283. /**
  29284. * Defines appearance of wireframe joints.
  29285. *
  29286. * Can only be used with {@link SVGRenderer}.
  29287. *
  29288. * @type {('round'|'bevel'|'miter')}
  29289. * @default 'round'
  29290. */
  29291. this.wireframeLinejoin = 'round';
  29292. /**
  29293. * Whether the material is rendered with flat shading or not.
  29294. *
  29295. * @type {boolean}
  29296. * @default false
  29297. */
  29298. this.flatShading = false;
  29299. /**
  29300. * Whether the material is affected by fog or not.
  29301. *
  29302. * @type {boolean}
  29303. * @default true
  29304. */
  29305. this.fog = true;
  29306. this.setValues( parameters );
  29307. }
  29308. copy( source ) {
  29309. super.copy( source );
  29310. this.color.copy( source.color );
  29311. this.map = source.map;
  29312. this.lightMap = source.lightMap;
  29313. this.lightMapIntensity = source.lightMapIntensity;
  29314. this.aoMap = source.aoMap;
  29315. this.aoMapIntensity = source.aoMapIntensity;
  29316. this.emissive.copy( source.emissive );
  29317. this.emissiveMap = source.emissiveMap;
  29318. this.emissiveIntensity = source.emissiveIntensity;
  29319. this.bumpMap = source.bumpMap;
  29320. this.bumpScale = source.bumpScale;
  29321. this.normalMap = source.normalMap;
  29322. this.normalMapType = source.normalMapType;
  29323. this.normalScale.copy( source.normalScale );
  29324. this.displacementMap = source.displacementMap;
  29325. this.displacementScale = source.displacementScale;
  29326. this.displacementBias = source.displacementBias;
  29327. this.specularMap = source.specularMap;
  29328. this.alphaMap = source.alphaMap;
  29329. this.envMap = source.envMap;
  29330. this.envMapRotation.copy( source.envMapRotation );
  29331. this.combine = source.combine;
  29332. this.reflectivity = source.reflectivity;
  29333. this.refractionRatio = source.refractionRatio;
  29334. this.wireframe = source.wireframe;
  29335. this.wireframeLinewidth = source.wireframeLinewidth;
  29336. this.wireframeLinecap = source.wireframeLinecap;
  29337. this.wireframeLinejoin = source.wireframeLinejoin;
  29338. this.flatShading = source.flatShading;
  29339. this.fog = source.fog;
  29340. return this;
  29341. }
  29342. }
  29343. /**
  29344. * A material for drawing geometry by depth. Depth is based off of the camera
  29345. * near and far plane. White is nearest, black is farthest.
  29346. *
  29347. * @augments Material
  29348. */
  29349. class MeshDepthMaterial extends Material {
  29350. /**
  29351. * Constructs a new mesh depth material.
  29352. *
  29353. * @param {Object} [parameters] - An object with one or more properties
  29354. * defining the material's appearance. Any property of the material
  29355. * (including any property from inherited materials) can be passed
  29356. * in here. Color values can be passed any type of value accepted
  29357. * by {@link Color#set}.
  29358. */
  29359. constructor( parameters ) {
  29360. super();
  29361. /**
  29362. * This flag can be used for type testing.
  29363. *
  29364. * @type {boolean}
  29365. * @readonly
  29366. * @default true
  29367. */
  29368. this.isMeshDepthMaterial = true;
  29369. this.type = 'MeshDepthMaterial';
  29370. /**
  29371. * Type for depth packing.
  29372. *
  29373. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  29374. * @default BasicDepthPacking
  29375. */
  29376. this.depthPacking = BasicDepthPacking;
  29377. /**
  29378. * The color map. May optionally include an alpha channel, typically combined
  29379. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29380. *
  29381. * @type {?Texture}
  29382. * @default null
  29383. */
  29384. this.map = null;
  29385. /**
  29386. * The alpha map is a grayscale texture that controls the opacity across the
  29387. * surface (black: fully transparent; white: fully opaque).
  29388. *
  29389. * Only the color of the texture is used, ignoring the alpha channel if one
  29390. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29391. * when sampling this texture due to the extra bit of precision provided for
  29392. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29393. * luminance/alpha textures will also still work as expected.
  29394. *
  29395. * @type {?Texture}
  29396. * @default null
  29397. */
  29398. this.alphaMap = null;
  29399. /**
  29400. * The displacement map affects the position of the mesh's vertices. Unlike
  29401. * other maps which only affect the light and shade of the material the
  29402. * displaced vertices can cast shadows, block other objects, and otherwise
  29403. * act as real geometry. The displacement texture is an image where the value
  29404. * of each pixel (white being the highest) is mapped against, and
  29405. * repositions, the vertices of the mesh.
  29406. *
  29407. * @type {?Texture}
  29408. * @default null
  29409. */
  29410. this.displacementMap = null;
  29411. /**
  29412. * How much the displacement map affects the mesh (where black is no
  29413. * displacement, and white is maximum displacement). Without a displacement
  29414. * map set, this value is not applied.
  29415. *
  29416. * @type {number}
  29417. * @default 0
  29418. */
  29419. this.displacementScale = 1;
  29420. /**
  29421. * The offset of the displacement map's values on the mesh's vertices.
  29422. * The bias is added to the scaled sample of the displacement map.
  29423. * Without a displacement map set, this value is not applied.
  29424. *
  29425. * @type {number}
  29426. * @default 0
  29427. */
  29428. this.displacementBias = 0;
  29429. /**
  29430. * Renders the geometry as a wireframe.
  29431. *
  29432. * @type {boolean}
  29433. * @default false
  29434. */
  29435. this.wireframe = false;
  29436. /**
  29437. * Controls the thickness of the wireframe.
  29438. *
  29439. * WebGL and WebGPU ignore this property and always render
  29440. * 1 pixel wide lines.
  29441. *
  29442. * @type {number}
  29443. * @default 1
  29444. */
  29445. this.wireframeLinewidth = 1;
  29446. this.setValues( parameters );
  29447. }
  29448. copy( source ) {
  29449. super.copy( source );
  29450. this.depthPacking = source.depthPacking;
  29451. this.map = source.map;
  29452. this.alphaMap = source.alphaMap;
  29453. this.displacementMap = source.displacementMap;
  29454. this.displacementScale = source.displacementScale;
  29455. this.displacementBias = source.displacementBias;
  29456. this.wireframe = source.wireframe;
  29457. this.wireframeLinewidth = source.wireframeLinewidth;
  29458. return this;
  29459. }
  29460. }
  29461. /**
  29462. * A material used internally for implementing shadow mapping with
  29463. * point lights.
  29464. *
  29465. * Can also be used to customize the shadow casting of an object by assigning
  29466. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  29467. * The following examples demonstrates this approach in order to ensure
  29468. * transparent parts of objects do no cast shadows.
  29469. *
  29470. * @augments Material
  29471. */
  29472. class MeshDistanceMaterial extends Material {
  29473. /**
  29474. * Constructs a new mesh distance material.
  29475. *
  29476. * @param {Object} [parameters] - An object with one or more properties
  29477. * defining the material's appearance. Any property of the material
  29478. * (including any property from inherited materials) can be passed
  29479. * in here. Color values can be passed any type of value accepted
  29480. * by {@link Color#set}.
  29481. */
  29482. constructor( parameters ) {
  29483. super();
  29484. /**
  29485. * This flag can be used for type testing.
  29486. *
  29487. * @type {boolean}
  29488. * @readonly
  29489. * @default true
  29490. */
  29491. this.isMeshDistanceMaterial = true;
  29492. this.type = 'MeshDistanceMaterial';
  29493. /**
  29494. * The color map. May optionally include an alpha channel, typically combined
  29495. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29496. *
  29497. * @type {?Texture}
  29498. * @default null
  29499. */
  29500. this.map = null;
  29501. /**
  29502. * The alpha map is a grayscale texture that controls the opacity across the
  29503. * surface (black: fully transparent; white: fully opaque).
  29504. *
  29505. * Only the color of the texture is used, ignoring the alpha channel if one
  29506. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29507. * when sampling this texture due to the extra bit of precision provided for
  29508. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29509. * luminance/alpha textures will also still work as expected.
  29510. *
  29511. * @type {?Texture}
  29512. * @default null
  29513. */
  29514. this.alphaMap = null;
  29515. /**
  29516. * The displacement map affects the position of the mesh's vertices. Unlike
  29517. * other maps which only affect the light and shade of the material the
  29518. * displaced vertices can cast shadows, block other objects, and otherwise
  29519. * act as real geometry. The displacement texture is an image where the value
  29520. * of each pixel (white being the highest) is mapped against, and
  29521. * repositions, the vertices of the mesh.
  29522. *
  29523. * @type {?Texture}
  29524. * @default null
  29525. */
  29526. this.displacementMap = null;
  29527. /**
  29528. * How much the displacement map affects the mesh (where black is no
  29529. * displacement, and white is maximum displacement). Without a displacement
  29530. * map set, this value is not applied.
  29531. *
  29532. * @type {number}
  29533. * @default 0
  29534. */
  29535. this.displacementScale = 1;
  29536. /**
  29537. * The offset of the displacement map's values on the mesh's vertices.
  29538. * The bias is added to the scaled sample of the displacement map.
  29539. * Without a displacement map set, this value is not applied.
  29540. *
  29541. * @type {number}
  29542. * @default 0
  29543. */
  29544. this.displacementBias = 0;
  29545. this.setValues( parameters );
  29546. }
  29547. copy( source ) {
  29548. super.copy( source );
  29549. this.map = source.map;
  29550. this.alphaMap = source.alphaMap;
  29551. this.displacementMap = source.displacementMap;
  29552. this.displacementScale = source.displacementScale;
  29553. this.displacementBias = source.displacementBias;
  29554. return this;
  29555. }
  29556. }
  29557. /**
  29558. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  29559. * material color and shading.
  29560. *
  29561. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  29562. * baked lighting. It will cast a shadow onto an object that receives shadows
  29563. * (and shadow clipping works), but it will not self-shadow or receive
  29564. * shadows.
  29565. *
  29566. * @augments Material
  29567. */
  29568. class MeshMatcapMaterial extends Material {
  29569. /**
  29570. * Constructs a new mesh matcap material.
  29571. *
  29572. * @param {Object} [parameters] - An object with one or more properties
  29573. * defining the material's appearance. Any property of the material
  29574. * (including any property from inherited materials) can be passed
  29575. * in here. Color values can be passed any type of value accepted
  29576. * by {@link Color#set}.
  29577. */
  29578. constructor( parameters ) {
  29579. super();
  29580. /**
  29581. * This flag can be used for type testing.
  29582. *
  29583. * @type {boolean}
  29584. * @readonly
  29585. * @default true
  29586. */
  29587. this.isMeshMatcapMaterial = true;
  29588. this.defines = { 'MATCAP': '' };
  29589. this.type = 'MeshMatcapMaterial';
  29590. /**
  29591. * Color of the material.
  29592. *
  29593. * @type {Color}
  29594. * @default (1,1,1)
  29595. */
  29596. this.color = new Color( 0xffffff ); // diffuse
  29597. /**
  29598. * The matcap map.
  29599. *
  29600. * @type {?Texture}
  29601. * @default null
  29602. */
  29603. this.matcap = null;
  29604. /**
  29605. * The color map. May optionally include an alpha channel, typically combined
  29606. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29607. * color is modulated by the diffuse `color`.
  29608. *
  29609. * @type {?Texture}
  29610. * @default null
  29611. */
  29612. this.map = null;
  29613. /**
  29614. * The texture to create a bump map. The black and white values map to the
  29615. * perceived depth in relation to the lights. Bump doesn't actually affect
  29616. * the geometry of the object, only the lighting. If a normal map is defined
  29617. * this will be ignored.
  29618. *
  29619. * @type {?Texture}
  29620. * @default null
  29621. */
  29622. this.bumpMap = null;
  29623. /**
  29624. * How much the bump map affects the material. Typical range is `[0,1]`.
  29625. *
  29626. * @type {number}
  29627. * @default 1
  29628. */
  29629. this.bumpScale = 1;
  29630. /**
  29631. * The texture to create a normal map. The RGB values affect the surface
  29632. * normal for each pixel fragment and change the way the color is lit. Normal
  29633. * maps do not change the actual shape of the surface, only the lighting. In
  29634. * case the material has a normal map authored using the left handed
  29635. * convention, the `y` component of `normalScale` should be negated to compensate
  29636. * for the different handedness.
  29637. *
  29638. * @type {?Texture}
  29639. * @default null
  29640. */
  29641. this.normalMap = null;
  29642. /**
  29643. * The type of normal map.
  29644. *
  29645. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29646. * @default TangentSpaceNormalMap
  29647. */
  29648. this.normalMapType = TangentSpaceNormalMap;
  29649. /**
  29650. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29651. *
  29652. * @type {Vector2}
  29653. * @default (1,1)
  29654. */
  29655. this.normalScale = new Vector2( 1, 1 );
  29656. /**
  29657. * The displacement map affects the position of the mesh's vertices. Unlike
  29658. * other maps which only affect the light and shade of the material the
  29659. * displaced vertices can cast shadows, block other objects, and otherwise
  29660. * act as real geometry. The displacement texture is an image where the value
  29661. * of each pixel (white being the highest) is mapped against, and
  29662. * repositions, the vertices of the mesh.
  29663. *
  29664. * @type {?Texture}
  29665. * @default null
  29666. */
  29667. this.displacementMap = null;
  29668. /**
  29669. * How much the displacement map affects the mesh (where black is no
  29670. * displacement, and white is maximum displacement). Without a displacement
  29671. * map set, this value is not applied.
  29672. *
  29673. * @type {number}
  29674. * @default 0
  29675. */
  29676. this.displacementScale = 1;
  29677. /**
  29678. * The offset of the displacement map's values on the mesh's vertices.
  29679. * The bias is added to the scaled sample of the displacement map.
  29680. * Without a displacement map set, this value is not applied.
  29681. *
  29682. * @type {number}
  29683. * @default 0
  29684. */
  29685. this.displacementBias = 0;
  29686. /**
  29687. * The alpha map is a grayscale texture that controls the opacity across the
  29688. * surface (black: fully transparent; white: fully opaque).
  29689. *
  29690. * Only the color of the texture is used, ignoring the alpha channel if one
  29691. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29692. * when sampling this texture due to the extra bit of precision provided for
  29693. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29694. * luminance/alpha textures will also still work as expected.
  29695. *
  29696. * @type {?Texture}
  29697. * @default null
  29698. */
  29699. this.alphaMap = null;
  29700. /**
  29701. * Whether the material is rendered with flat shading or not.
  29702. *
  29703. * @type {boolean}
  29704. * @default false
  29705. */
  29706. this.flatShading = false;
  29707. /**
  29708. * Whether the material is affected by fog or not.
  29709. *
  29710. * @type {boolean}
  29711. * @default true
  29712. */
  29713. this.fog = true;
  29714. this.setValues( parameters );
  29715. }
  29716. copy( source ) {
  29717. super.copy( source );
  29718. this.defines = { 'MATCAP': '' };
  29719. this.color.copy( source.color );
  29720. this.matcap = source.matcap;
  29721. this.map = source.map;
  29722. this.bumpMap = source.bumpMap;
  29723. this.bumpScale = source.bumpScale;
  29724. this.normalMap = source.normalMap;
  29725. this.normalMapType = source.normalMapType;
  29726. this.normalScale.copy( source.normalScale );
  29727. this.displacementMap = source.displacementMap;
  29728. this.displacementScale = source.displacementScale;
  29729. this.displacementBias = source.displacementBias;
  29730. this.alphaMap = source.alphaMap;
  29731. this.flatShading = source.flatShading;
  29732. this.fog = source.fog;
  29733. return this;
  29734. }
  29735. }
  29736. /**
  29737. * A material for rendering line primitives.
  29738. *
  29739. * Materials define the appearance of renderable 3D objects.
  29740. *
  29741. * ```js
  29742. * const material = new THREE.LineDashedMaterial( {
  29743. * color: 0xffffff,
  29744. * scale: 1,
  29745. * dashSize: 3,
  29746. * gapSize: 1,
  29747. * } );
  29748. * ```
  29749. *
  29750. * @augments LineBasicMaterial
  29751. */
  29752. class LineDashedMaterial extends LineBasicMaterial {
  29753. /**
  29754. * Constructs a new line dashed material.
  29755. *
  29756. * @param {Object} [parameters] - An object with one or more properties
  29757. * defining the material's appearance. Any property of the material
  29758. * (including any property from inherited materials) can be passed
  29759. * in here. Color values can be passed any type of value accepted
  29760. * by {@link Color#set}.
  29761. */
  29762. constructor( parameters ) {
  29763. super();
  29764. /**
  29765. * This flag can be used for type testing.
  29766. *
  29767. * @type {boolean}
  29768. * @readonly
  29769. * @default true
  29770. */
  29771. this.isLineDashedMaterial = true;
  29772. this.type = 'LineDashedMaterial';
  29773. /**
  29774. * The scale of the dashed part of a line.
  29775. *
  29776. * @type {number}
  29777. * @default 1
  29778. */
  29779. this.scale = 1;
  29780. /**
  29781. * The size of the dash. This is both the gap with the stroke.
  29782. *
  29783. * @type {number}
  29784. * @default 3
  29785. */
  29786. this.dashSize = 3;
  29787. /**
  29788. * The size of the gap.
  29789. *
  29790. * @type {number}
  29791. * @default 1
  29792. */
  29793. this.gapSize = 1;
  29794. this.setValues( parameters );
  29795. }
  29796. copy( source ) {
  29797. super.copy( source );
  29798. this.scale = source.scale;
  29799. this.dashSize = source.dashSize;
  29800. this.gapSize = source.gapSize;
  29801. return this;
  29802. }
  29803. }
  29804. /**
  29805. * Converts an array to a specific type.
  29806. *
  29807. * @param {TypedArray|Array} array - The array to convert.
  29808. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  29809. * @return {TypedArray} The converted array.
  29810. */
  29811. function convertArray( array, type ) {
  29812. if ( ! array || array.constructor === type ) return array;
  29813. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  29814. return new type( array ); // create typed array
  29815. }
  29816. return Array.prototype.slice.call( array ); // create Array
  29817. }
  29818. /**
  29819. * Returns `true` if the given object is a typed array.
  29820. *
  29821. * @param {any} object - The object to check.
  29822. * @return {boolean} Whether the given object is a typed array.
  29823. */
  29824. function isTypedArray( object ) {
  29825. return ArrayBuffer.isView( object ) && ! ( object instanceof DataView );
  29826. }
  29827. /**
  29828. * Returns an array by which times and values can be sorted.
  29829. *
  29830. * @param {Array<number>} times - The keyframe time values.
  29831. * @return {Array<number>} The array.
  29832. */
  29833. function getKeyframeOrder( times ) {
  29834. function compareTime( i, j ) {
  29835. return times[ i ] - times[ j ];
  29836. }
  29837. const n = times.length;
  29838. const result = new Array( n );
  29839. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  29840. result.sort( compareTime );
  29841. return result;
  29842. }
  29843. /**
  29844. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  29845. *
  29846. * @param {Array<number>} values - The values to sort.
  29847. * @param {number} stride - The stride.
  29848. * @param {Array<number>} order - The sort order.
  29849. * @return {Array<number>} The sorted values.
  29850. */
  29851. function sortedArray( values, stride, order ) {
  29852. const nValues = values.length;
  29853. const result = new values.constructor( nValues );
  29854. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  29855. const srcOffset = order[ i ] * stride;
  29856. for ( let j = 0; j !== stride; ++ j ) {
  29857. result[ dstOffset ++ ] = values[ srcOffset + j ];
  29858. }
  29859. }
  29860. return result;
  29861. }
  29862. /**
  29863. * Used for parsing AOS keyframe formats.
  29864. *
  29865. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  29866. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  29867. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  29868. * @param {string} valuePropertyName - The name of the property to use.
  29869. */
  29870. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  29871. let i = 1, key = jsonKeys[ 0 ];
  29872. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  29873. key = jsonKeys[ i ++ ];
  29874. }
  29875. if ( key === undefined ) return; // no data
  29876. let value = key[ valuePropertyName ];
  29877. if ( value === undefined ) return; // no data
  29878. if ( Array.isArray( value ) ) {
  29879. do {
  29880. value = key[ valuePropertyName ];
  29881. if ( value !== undefined ) {
  29882. times.push( key.time );
  29883. values.push( ...value ); // push all elements
  29884. }
  29885. key = jsonKeys[ i ++ ];
  29886. } while ( key !== undefined );
  29887. } else if ( value.toArray !== undefined ) {
  29888. // ...assume THREE.Math-ish
  29889. do {
  29890. value = key[ valuePropertyName ];
  29891. if ( value !== undefined ) {
  29892. times.push( key.time );
  29893. value.toArray( values, values.length );
  29894. }
  29895. key = jsonKeys[ i ++ ];
  29896. } while ( key !== undefined );
  29897. } else {
  29898. // otherwise push as-is
  29899. do {
  29900. value = key[ valuePropertyName ];
  29901. if ( value !== undefined ) {
  29902. times.push( key.time );
  29903. values.push( value );
  29904. }
  29905. key = jsonKeys[ i ++ ];
  29906. } while ( key !== undefined );
  29907. }
  29908. }
  29909. /**
  29910. * Creates a new clip, containing only the segment of the original clip between the given frames.
  29911. *
  29912. * @param {AnimationClip} sourceClip - The values to sort.
  29913. * @param {string} name - The name of the clip.
  29914. * @param {number} startFrame - The start frame.
  29915. * @param {number} endFrame - The end frame.
  29916. * @param {number} [fps=30] - The FPS.
  29917. * @return {AnimationClip} The new sub clip.
  29918. */
  29919. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  29920. const clip = sourceClip.clone();
  29921. clip.name = name;
  29922. const tracks = [];
  29923. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  29924. const track = clip.tracks[ i ];
  29925. const valueSize = track.getValueSize();
  29926. const times = [];
  29927. const values = [];
  29928. for ( let j = 0; j < track.times.length; ++ j ) {
  29929. const frame = track.times[ j ] * fps;
  29930. if ( frame < startFrame || frame >= endFrame ) continue;
  29931. times.push( track.times[ j ] );
  29932. for ( let k = 0; k < valueSize; ++ k ) {
  29933. values.push( track.values[ j * valueSize + k ] );
  29934. }
  29935. }
  29936. if ( times.length === 0 ) continue;
  29937. track.times = convertArray( times, track.times.constructor );
  29938. track.values = convertArray( values, track.values.constructor );
  29939. tracks.push( track );
  29940. }
  29941. clip.tracks = tracks;
  29942. // find minimum .times value across all tracks in the trimmed clip
  29943. let minStartTime = Infinity;
  29944. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  29945. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  29946. minStartTime = clip.tracks[ i ].times[ 0 ];
  29947. }
  29948. }
  29949. // shift all tracks such that clip begins at t=0
  29950. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  29951. clip.tracks[ i ].shift( -1 * minStartTime );
  29952. }
  29953. clip.resetDuration();
  29954. return clip;
  29955. }
  29956. /**
  29957. * Converts the keyframes of the given animation clip to an additive format.
  29958. *
  29959. * @param {AnimationClip} targetClip - The clip to make additive.
  29960. * @param {number} [referenceFrame=0] - The reference frame.
  29961. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  29962. * @param {number} [fps=30] - The FPS.
  29963. * @return {AnimationClip} The updated clip which is now additive.
  29964. */
  29965. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  29966. if ( fps <= 0 ) fps = 30;
  29967. const numTracks = referenceClip.tracks.length;
  29968. const referenceTime = referenceFrame / fps;
  29969. // Make each track's values relative to the values at the reference frame
  29970. for ( let i = 0; i < numTracks; ++ i ) {
  29971. const referenceTrack = referenceClip.tracks[ i ];
  29972. const referenceTrackType = referenceTrack.ValueTypeName;
  29973. // Skip this track if it's non-numeric
  29974. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  29975. // Find the track in the target clip whose name and type matches the reference track
  29976. const targetTrack = targetClip.tracks.find( function ( track ) {
  29977. return track.name === referenceTrack.name
  29978. && track.ValueTypeName === referenceTrackType;
  29979. } );
  29980. if ( targetTrack === undefined ) continue;
  29981. let referenceOffset = 0;
  29982. const referenceValueSize = referenceTrack.getValueSize();
  29983. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  29984. referenceOffset = referenceValueSize / 3;
  29985. }
  29986. let targetOffset = 0;
  29987. const targetValueSize = targetTrack.getValueSize();
  29988. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  29989. targetOffset = targetValueSize / 3;
  29990. }
  29991. const lastIndex = referenceTrack.times.length - 1;
  29992. let referenceValue;
  29993. // Find the value to subtract out of the track
  29994. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  29995. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  29996. const startIndex = referenceOffset;
  29997. const endIndex = referenceValueSize - referenceOffset;
  29998. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  29999. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30000. // Reference frame is after the last keyframe, so just use the last keyframe
  30001. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30002. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30003. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30004. } else {
  30005. // Interpolate to the reference value
  30006. const interpolant = referenceTrack.createInterpolant();
  30007. const startIndex = referenceOffset;
  30008. const endIndex = referenceValueSize - referenceOffset;
  30009. interpolant.evaluate( referenceTime );
  30010. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30011. }
  30012. // Conjugate the quaternion
  30013. if ( referenceTrackType === 'quaternion' ) {
  30014. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30015. referenceQuat.toArray( referenceValue );
  30016. }
  30017. // Subtract the reference value from all of the track values
  30018. const numTimes = targetTrack.times.length;
  30019. for ( let j = 0; j < numTimes; ++ j ) {
  30020. const valueStart = j * targetValueSize + targetOffset;
  30021. if ( referenceTrackType === 'quaternion' ) {
  30022. // Multiply the conjugate for quaternion track types
  30023. Quaternion.multiplyQuaternionsFlat(
  30024. targetTrack.values,
  30025. valueStart,
  30026. referenceValue,
  30027. 0,
  30028. targetTrack.values,
  30029. valueStart
  30030. );
  30031. } else {
  30032. const valueEnd = targetValueSize - targetOffset * 2;
  30033. // Subtract each value for all other numeric track types
  30034. for ( let k = 0; k < valueEnd; ++ k ) {
  30035. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30036. }
  30037. }
  30038. }
  30039. }
  30040. targetClip.blendMode = AdditiveAnimationBlendMode;
  30041. return targetClip;
  30042. }
  30043. /**
  30044. * A class with various methods to assist with animations.
  30045. *
  30046. * @hideconstructor
  30047. */
  30048. class AnimationUtils {
  30049. /**
  30050. * Converts an array to a specific type
  30051. *
  30052. * @static
  30053. * @param {TypedArray|Array} array - The array to convert.
  30054. * @param {TypedArray.constructor} type - The constructor of a type array.
  30055. * @return {TypedArray} The converted array
  30056. */
  30057. static convertArray( array, type ) {
  30058. return convertArray( array, type );
  30059. }
  30060. /**
  30061. * Returns `true` if the given object is a typed array.
  30062. *
  30063. * @static
  30064. * @param {any} object - The object to check.
  30065. * @return {boolean} Whether the given object is a typed array.
  30066. */
  30067. static isTypedArray( object ) {
  30068. return isTypedArray( object );
  30069. }
  30070. /**
  30071. * Returns an array by which times and values can be sorted.
  30072. *
  30073. * @static
  30074. * @param {Array<number>} times - The keyframe time values.
  30075. * @return {Array<number>} The array.
  30076. */
  30077. static getKeyframeOrder( times ) {
  30078. return getKeyframeOrder( times );
  30079. }
  30080. /**
  30081. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30082. *
  30083. * @static
  30084. * @param {Array<number>} values - The values to sort.
  30085. * @param {number} stride - The stride.
  30086. * @param {Array<number>} order - The sort order.
  30087. * @return {Array<number>} The sorted values.
  30088. */
  30089. static sortedArray( values, stride, order ) {
  30090. return sortedArray( values, stride, order );
  30091. }
  30092. /**
  30093. * Used for parsing AOS keyframe formats.
  30094. *
  30095. * @static
  30096. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30097. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30098. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30099. * @param {string} valuePropertyName - The name of the property to use.
  30100. */
  30101. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30102. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30103. }
  30104. /**
  30105. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30106. *
  30107. * @static
  30108. * @param {AnimationClip} sourceClip - The values to sort.
  30109. * @param {string} name - The name of the clip.
  30110. * @param {number} startFrame - The start frame.
  30111. * @param {number} endFrame - The end frame.
  30112. * @param {number} [fps=30] - The FPS.
  30113. * @return {AnimationClip} The new sub clip.
  30114. */
  30115. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30116. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30117. }
  30118. /**
  30119. * Converts the keyframes of the given animation clip to an additive format.
  30120. *
  30121. * @static
  30122. * @param {AnimationClip} targetClip - The clip to make additive.
  30123. * @param {number} [referenceFrame=0] - The reference frame.
  30124. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30125. * @param {number} [fps=30] - The FPS.
  30126. * @return {AnimationClip} The updated clip which is now additive.
  30127. */
  30128. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30129. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30130. }
  30131. }
  30132. /**
  30133. * Abstract base class of interpolants over parametric samples.
  30134. *
  30135. * The parameter domain is one dimensional, typically the time or a path
  30136. * along a curve defined by the data.
  30137. *
  30138. * The sample values can have any dimensionality and derived classes may
  30139. * apply special interpretations to the data.
  30140. *
  30141. * This class provides the interval seek in a Template Method, deferring
  30142. * the actual interpolation to derived classes.
  30143. *
  30144. * Time complexity is O(1) for linear access crossing at most two points
  30145. * and O(log N) for random access, where N is the number of positions.
  30146. *
  30147. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30148. *
  30149. * @abstract
  30150. */
  30151. class Interpolant {
  30152. /**
  30153. * Constructs a new interpolant.
  30154. *
  30155. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30156. * @param {TypedArray} sampleValues - The sample values.
  30157. * @param {number} sampleSize - The sample size
  30158. * @param {TypedArray} [resultBuffer] - The result buffer.
  30159. */
  30160. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30161. /**
  30162. * The parameter positions.
  30163. *
  30164. * @type {TypedArray}
  30165. */
  30166. this.parameterPositions = parameterPositions;
  30167. /**
  30168. * A cache index.
  30169. *
  30170. * @private
  30171. * @type {number}
  30172. * @default 0
  30173. */
  30174. this._cachedIndex = 0;
  30175. /**
  30176. * The result buffer.
  30177. *
  30178. * @type {TypedArray}
  30179. */
  30180. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30181. /**
  30182. * The sample values.
  30183. *
  30184. * @type {TypedArray}
  30185. */
  30186. this.sampleValues = sampleValues;
  30187. /**
  30188. * The value size.
  30189. *
  30190. * @type {TypedArray}
  30191. */
  30192. this.valueSize = sampleSize;
  30193. /**
  30194. * The interpolation settings.
  30195. *
  30196. * @type {?Object}
  30197. * @default null
  30198. */
  30199. this.settings = null;
  30200. /**
  30201. * The default settings object.
  30202. *
  30203. * @type {Object}
  30204. */
  30205. this.DefaultSettings_ = {};
  30206. }
  30207. /**
  30208. * Evaluate the interpolant at position `t`.
  30209. *
  30210. * @param {number} t - The interpolation factor.
  30211. * @return {TypedArray} The result buffer.
  30212. */
  30213. evaluate( t ) {
  30214. const pp = this.parameterPositions;
  30215. let i1 = this._cachedIndex,
  30216. t1 = pp[ i1 ],
  30217. t0 = pp[ i1 - 1 ];
  30218. validate_interval: {
  30219. seek: {
  30220. let right;
  30221. linear_scan: {
  30222. //- See http://jsperf.com/comparison-to-undefined/3
  30223. //- slower code:
  30224. //-
  30225. //- if ( t >= t1 || t1 === undefined ) {
  30226. forward_scan: if ( ! ( t < t1 ) ) {
  30227. for ( let giveUpAt = i1 + 2; ; ) {
  30228. if ( t1 === undefined ) {
  30229. if ( t < t0 ) break forward_scan;
  30230. // after end
  30231. i1 = pp.length;
  30232. this._cachedIndex = i1;
  30233. return this.copySampleValue_( i1 - 1 );
  30234. }
  30235. if ( i1 === giveUpAt ) break; // this loop
  30236. t0 = t1;
  30237. t1 = pp[ ++ i1 ];
  30238. if ( t < t1 ) {
  30239. // we have arrived at the sought interval
  30240. break seek;
  30241. }
  30242. }
  30243. // prepare binary search on the right side of the index
  30244. right = pp.length;
  30245. break linear_scan;
  30246. }
  30247. //- slower code:
  30248. //- if ( t < t0 || t0 === undefined ) {
  30249. if ( ! ( t >= t0 ) ) {
  30250. // looping?
  30251. const t1global = pp[ 1 ];
  30252. if ( t < t1global ) {
  30253. i1 = 2; // + 1, using the scan for the details
  30254. t0 = t1global;
  30255. }
  30256. // linear reverse scan
  30257. for ( let giveUpAt = i1 - 2; ; ) {
  30258. if ( t0 === undefined ) {
  30259. // before start
  30260. this._cachedIndex = 0;
  30261. return this.copySampleValue_( 0 );
  30262. }
  30263. if ( i1 === giveUpAt ) break; // this loop
  30264. t1 = t0;
  30265. t0 = pp[ -- i1 - 1 ];
  30266. if ( t >= t0 ) {
  30267. // we have arrived at the sought interval
  30268. break seek;
  30269. }
  30270. }
  30271. // prepare binary search on the left side of the index
  30272. right = i1;
  30273. i1 = 0;
  30274. break linear_scan;
  30275. }
  30276. // the interval is valid
  30277. break validate_interval;
  30278. } // linear scan
  30279. // binary search
  30280. while ( i1 < right ) {
  30281. const mid = ( i1 + right ) >>> 1;
  30282. if ( t < pp[ mid ] ) {
  30283. right = mid;
  30284. } else {
  30285. i1 = mid + 1;
  30286. }
  30287. }
  30288. t1 = pp[ i1 ];
  30289. t0 = pp[ i1 - 1 ];
  30290. // check boundary cases, again
  30291. if ( t0 === undefined ) {
  30292. this._cachedIndex = 0;
  30293. return this.copySampleValue_( 0 );
  30294. }
  30295. if ( t1 === undefined ) {
  30296. i1 = pp.length;
  30297. this._cachedIndex = i1;
  30298. return this.copySampleValue_( i1 - 1 );
  30299. }
  30300. } // seek
  30301. this._cachedIndex = i1;
  30302. this.intervalChanged_( i1, t0, t1 );
  30303. } // validate_interval
  30304. return this.interpolate_( i1, t0, t, t1 );
  30305. }
  30306. /**
  30307. * Returns the interpolation settings.
  30308. *
  30309. * @return {Object} The interpolation settings.
  30310. */
  30311. getSettings_() {
  30312. return this.settings || this.DefaultSettings_;
  30313. }
  30314. /**
  30315. * Copies a sample value to the result buffer.
  30316. *
  30317. * @param {number} index - An index into the sample value buffer.
  30318. * @return {TypedArray} The result buffer.
  30319. */
  30320. copySampleValue_( index ) {
  30321. // copies a sample value to the result buffer
  30322. const result = this.resultBuffer,
  30323. values = this.sampleValues,
  30324. stride = this.valueSize,
  30325. offset = index * stride;
  30326. for ( let i = 0; i !== stride; ++ i ) {
  30327. result[ i ] = values[ offset + i ];
  30328. }
  30329. return result;
  30330. }
  30331. /**
  30332. * Copies a sample value to the result buffer.
  30333. *
  30334. * @abstract
  30335. * @param {number} i1 - An index into the sample value buffer.
  30336. * @param {number} t0 - The previous interpolation factor.
  30337. * @param {number} t - The current interpolation factor.
  30338. * @param {number} t1 - The next interpolation factor.
  30339. * @return {TypedArray} The result buffer.
  30340. */
  30341. interpolate_( /* i1, t0, t, t1 */ ) {
  30342. throw new Error( 'call to abstract method' );
  30343. // implementations shall return this.resultBuffer
  30344. }
  30345. /**
  30346. * Optional method that is executed when the interval has changed.
  30347. *
  30348. * @param {number} i1 - An index into the sample value buffer.
  30349. * @param {number} t0 - The previous interpolation factor.
  30350. * @param {number} t - The current interpolation factor.
  30351. */
  30352. intervalChanged_( /* i1, t0, t1 */ ) {
  30353. // empty
  30354. }
  30355. }
  30356. /**
  30357. * Fast and simple cubic spline interpolant.
  30358. *
  30359. * It was derived from a Hermitian construction setting the first derivative
  30360. * at each sample position to the linear slope between neighboring positions
  30361. * over their parameter interval.
  30362. *
  30363. * @augments Interpolant
  30364. */
  30365. class CubicInterpolant extends Interpolant {
  30366. /**
  30367. * Constructs a new cubic interpolant.
  30368. *
  30369. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30370. * @param {TypedArray} sampleValues - The sample values.
  30371. * @param {number} sampleSize - The sample size
  30372. * @param {TypedArray} [resultBuffer] - The result buffer.
  30373. */
  30374. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30375. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30376. this._weightPrev = -0;
  30377. this._offsetPrev = -0;
  30378. this._weightNext = -0;
  30379. this._offsetNext = -0;
  30380. this.DefaultSettings_ = {
  30381. endingStart: ZeroCurvatureEnding,
  30382. endingEnd: ZeroCurvatureEnding
  30383. };
  30384. }
  30385. intervalChanged_( i1, t0, t1 ) {
  30386. const pp = this.parameterPositions;
  30387. let iPrev = i1 - 2,
  30388. iNext = i1 + 1,
  30389. tPrev = pp[ iPrev ],
  30390. tNext = pp[ iNext ];
  30391. if ( tPrev === undefined ) {
  30392. switch ( this.getSettings_().endingStart ) {
  30393. case ZeroSlopeEnding:
  30394. // f'(t0) = 0
  30395. iPrev = i1;
  30396. tPrev = 2 * t0 - t1;
  30397. break;
  30398. case WrapAroundEnding:
  30399. // use the other end of the curve
  30400. iPrev = pp.length - 2;
  30401. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  30402. break;
  30403. default: // ZeroCurvatureEnding
  30404. // f''(t0) = 0 a.k.a. Natural Spline
  30405. iPrev = i1;
  30406. tPrev = t1;
  30407. }
  30408. }
  30409. if ( tNext === undefined ) {
  30410. switch ( this.getSettings_().endingEnd ) {
  30411. case ZeroSlopeEnding:
  30412. // f'(tN) = 0
  30413. iNext = i1;
  30414. tNext = 2 * t1 - t0;
  30415. break;
  30416. case WrapAroundEnding:
  30417. // use the other end of the curve
  30418. iNext = 1;
  30419. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  30420. break;
  30421. default: // ZeroCurvatureEnding
  30422. // f''(tN) = 0, a.k.a. Natural Spline
  30423. iNext = i1 - 1;
  30424. tNext = t0;
  30425. }
  30426. }
  30427. const halfDt = ( t1 - t0 ) * 0.5,
  30428. stride = this.valueSize;
  30429. this._weightPrev = halfDt / ( t0 - tPrev );
  30430. this._weightNext = halfDt / ( tNext - t1 );
  30431. this._offsetPrev = iPrev * stride;
  30432. this._offsetNext = iNext * stride;
  30433. }
  30434. interpolate_( i1, t0, t, t1 ) {
  30435. const result = this.resultBuffer,
  30436. values = this.sampleValues,
  30437. stride = this.valueSize,
  30438. o1 = i1 * stride, o0 = o1 - stride,
  30439. oP = this._offsetPrev, oN = this._offsetNext,
  30440. wP = this._weightPrev, wN = this._weightNext,
  30441. p = ( t - t0 ) / ( t1 - t0 ),
  30442. pp = p * p,
  30443. ppp = pp * p;
  30444. // evaluate polynomials
  30445. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  30446. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  30447. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  30448. const sN = wN * ppp - wN * pp;
  30449. // combine data linearly
  30450. for ( let i = 0; i !== stride; ++ i ) {
  30451. result[ i ] =
  30452. sP * values[ oP + i ] +
  30453. s0 * values[ o0 + i ] +
  30454. s1 * values[ o1 + i ] +
  30455. sN * values[ oN + i ];
  30456. }
  30457. return result;
  30458. }
  30459. }
  30460. /**
  30461. * A basic linear interpolant.
  30462. *
  30463. * @augments Interpolant
  30464. */
  30465. class LinearInterpolant extends Interpolant {
  30466. /**
  30467. * Constructs a new linear interpolant.
  30468. *
  30469. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30470. * @param {TypedArray} sampleValues - The sample values.
  30471. * @param {number} sampleSize - The sample size
  30472. * @param {TypedArray} [resultBuffer] - The result buffer.
  30473. */
  30474. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30475. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30476. }
  30477. interpolate_( i1, t0, t, t1 ) {
  30478. const result = this.resultBuffer,
  30479. values = this.sampleValues,
  30480. stride = this.valueSize,
  30481. offset1 = i1 * stride,
  30482. offset0 = offset1 - stride,
  30483. weight1 = ( t - t0 ) / ( t1 - t0 ),
  30484. weight0 = 1 - weight1;
  30485. for ( let i = 0; i !== stride; ++ i ) {
  30486. result[ i ] =
  30487. values[ offset0 + i ] * weight0 +
  30488. values[ offset1 + i ] * weight1;
  30489. }
  30490. return result;
  30491. }
  30492. }
  30493. /**
  30494. * Interpolant that evaluates to the sample value at the position preceding
  30495. * the parameter.
  30496. *
  30497. * @augments Interpolant
  30498. */
  30499. class DiscreteInterpolant extends Interpolant {
  30500. /**
  30501. * Constructs a new discrete interpolant.
  30502. *
  30503. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30504. * @param {TypedArray} sampleValues - The sample values.
  30505. * @param {number} sampleSize - The sample size
  30506. * @param {TypedArray} [resultBuffer] - The result buffer.
  30507. */
  30508. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30509. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30510. }
  30511. interpolate_( i1 /*, t0, t, t1 */ ) {
  30512. return this.copySampleValue_( i1 - 1 );
  30513. }
  30514. }
  30515. /**
  30516. * Represents s a timed sequence of keyframes, which are composed of lists of
  30517. * times and related values, and which are used to animate a specific property
  30518. * of an object.
  30519. */
  30520. class KeyframeTrack {
  30521. /**
  30522. * Constructs a new keyframe track.
  30523. *
  30524. * @param {string} name - The keyframe track's name.
  30525. * @param {Array<number>} times - A list of keyframe times.
  30526. * @param {Array<number>} values - A list of keyframe values.
  30527. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30528. */
  30529. constructor( name, times, values, interpolation ) {
  30530. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  30531. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  30532. /**
  30533. * The track's name can refer to morph targets or bones or
  30534. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  30535. * for the forms of strings that can be parsed for property binding.
  30536. *
  30537. * @type {string}
  30538. */
  30539. this.name = name;
  30540. /**
  30541. * The keyframe times.
  30542. *
  30543. * @type {Float32Array}
  30544. */
  30545. this.times = convertArray( times, this.TimeBufferType );
  30546. /**
  30547. * The keyframe values.
  30548. *
  30549. * @type {Float32Array}
  30550. */
  30551. this.values = convertArray( values, this.ValueBufferType );
  30552. this.setInterpolation( interpolation || this.DefaultInterpolation );
  30553. }
  30554. /**
  30555. * Converts the keyframe track to JSON.
  30556. *
  30557. * @static
  30558. * @param {KeyframeTrack} track - The keyframe track to serialize.
  30559. * @return {Object} The serialized keyframe track as JSON.
  30560. */
  30561. static toJSON( track ) {
  30562. const trackType = track.constructor;
  30563. let json;
  30564. // derived classes can define a static toJSON method
  30565. if ( trackType.toJSON !== this.toJSON ) {
  30566. json = trackType.toJSON( track );
  30567. } else {
  30568. // by default, we assume the data can be serialized as-is
  30569. json = {
  30570. 'name': track.name,
  30571. 'times': convertArray( track.times, Array ),
  30572. 'values': convertArray( track.values, Array )
  30573. };
  30574. const interpolation = track.getInterpolation();
  30575. if ( interpolation !== track.DefaultInterpolation ) {
  30576. json.interpolation = interpolation;
  30577. }
  30578. }
  30579. json.type = track.ValueTypeName; // mandatory
  30580. return json;
  30581. }
  30582. /**
  30583. * Factory method for creating a new discrete interpolant.
  30584. *
  30585. * @static
  30586. * @param {TypedArray} [result] - The result buffer.
  30587. * @return {DiscreteInterpolant} The new interpolant.
  30588. */
  30589. InterpolantFactoryMethodDiscrete( result ) {
  30590. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  30591. }
  30592. /**
  30593. * Factory method for creating a new linear interpolant.
  30594. *
  30595. * @static
  30596. * @param {TypedArray} [result] - The result buffer.
  30597. * @return {LinearInterpolant} The new interpolant.
  30598. */
  30599. InterpolantFactoryMethodLinear( result ) {
  30600. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  30601. }
  30602. /**
  30603. * Factory method for creating a new smooth interpolant.
  30604. *
  30605. * @static
  30606. * @param {TypedArray} [result] - The result buffer.
  30607. * @return {CubicInterpolant} The new interpolant.
  30608. */
  30609. InterpolantFactoryMethodSmooth( result ) {
  30610. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  30611. }
  30612. /**
  30613. * Defines the interpolation factor method for this keyframe track.
  30614. *
  30615. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} interpolation - The interpolation type.
  30616. * @return {KeyframeTrack} A reference to this keyframe track.
  30617. */
  30618. setInterpolation( interpolation ) {
  30619. let factoryMethod;
  30620. switch ( interpolation ) {
  30621. case InterpolateDiscrete:
  30622. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  30623. break;
  30624. case InterpolateLinear:
  30625. factoryMethod = this.InterpolantFactoryMethodLinear;
  30626. break;
  30627. case InterpolateSmooth:
  30628. factoryMethod = this.InterpolantFactoryMethodSmooth;
  30629. break;
  30630. }
  30631. if ( factoryMethod === undefined ) {
  30632. const message = 'unsupported interpolation for ' +
  30633. this.ValueTypeName + ' keyframe track named ' + this.name;
  30634. if ( this.createInterpolant === undefined ) {
  30635. // fall back to default, unless the default itself is messed up
  30636. if ( interpolation !== this.DefaultInterpolation ) {
  30637. this.setInterpolation( this.DefaultInterpolation );
  30638. } else {
  30639. throw new Error( message ); // fatal, in this case
  30640. }
  30641. }
  30642. console.warn( 'THREE.KeyframeTrack:', message );
  30643. return this;
  30644. }
  30645. this.createInterpolant = factoryMethod;
  30646. return this;
  30647. }
  30648. /**
  30649. * Returns the current interpolation type.
  30650. *
  30651. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} The interpolation type.
  30652. */
  30653. getInterpolation() {
  30654. switch ( this.createInterpolant ) {
  30655. case this.InterpolantFactoryMethodDiscrete:
  30656. return InterpolateDiscrete;
  30657. case this.InterpolantFactoryMethodLinear:
  30658. return InterpolateLinear;
  30659. case this.InterpolantFactoryMethodSmooth:
  30660. return InterpolateSmooth;
  30661. }
  30662. }
  30663. /**
  30664. * Returns the value size.
  30665. *
  30666. * @return {number} The value size.
  30667. */
  30668. getValueSize() {
  30669. return this.values.length / this.times.length;
  30670. }
  30671. /**
  30672. * Moves all keyframes either forward or backward in time.
  30673. *
  30674. * @param {number} timeOffset - The offset to move the time values.
  30675. * @return {KeyframeTrack} A reference to this keyframe track.
  30676. */
  30677. shift( timeOffset ) {
  30678. if ( timeOffset !== 0.0 ) {
  30679. const times = this.times;
  30680. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30681. times[ i ] += timeOffset;
  30682. }
  30683. }
  30684. return this;
  30685. }
  30686. /**
  30687. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  30688. *
  30689. * @param {number} timeScale - The time scale.
  30690. * @return {KeyframeTrack} A reference to this keyframe track.
  30691. */
  30692. scale( timeScale ) {
  30693. if ( timeScale !== 1.0 ) {
  30694. const times = this.times;
  30695. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30696. times[ i ] *= timeScale;
  30697. }
  30698. }
  30699. return this;
  30700. }
  30701. /**
  30702. * Removes keyframes before and after animation without changing any values within the defined time range.
  30703. *
  30704. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  30705. * keys this will change their values
  30706. *
  30707. * @param {number} startTime - The start time.
  30708. * @param {number} endTime - The end time.
  30709. * @return {KeyframeTrack} A reference to this keyframe track.
  30710. */
  30711. trim( startTime, endTime ) {
  30712. const times = this.times,
  30713. nKeys = times.length;
  30714. let from = 0,
  30715. to = nKeys - 1;
  30716. while ( from !== nKeys && times[ from ] < startTime ) {
  30717. ++ from;
  30718. }
  30719. while ( to !== -1 && times[ to ] > endTime ) {
  30720. -- to;
  30721. }
  30722. ++ to; // inclusive -> exclusive bound
  30723. if ( from !== 0 || to !== nKeys ) {
  30724. // empty tracks are forbidden, so keep at least one keyframe
  30725. if ( from >= to ) {
  30726. to = Math.max( to, 1 );
  30727. from = to - 1;
  30728. }
  30729. const stride = this.getValueSize();
  30730. this.times = times.slice( from, to );
  30731. this.values = this.values.slice( from * stride, to * stride );
  30732. }
  30733. return this;
  30734. }
  30735. /**
  30736. * Performs minimal validation on the keyframe track. Returns `true` if the values
  30737. * are valid.
  30738. *
  30739. * @return {boolean} Whether the keyframes are valid or not.
  30740. */
  30741. validate() {
  30742. let valid = true;
  30743. const valueSize = this.getValueSize();
  30744. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  30745. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  30746. valid = false;
  30747. }
  30748. const times = this.times,
  30749. values = this.values,
  30750. nKeys = times.length;
  30751. if ( nKeys === 0 ) {
  30752. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  30753. valid = false;
  30754. }
  30755. let prevTime = null;
  30756. for ( let i = 0; i !== nKeys; i ++ ) {
  30757. const currTime = times[ i ];
  30758. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  30759. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  30760. valid = false;
  30761. break;
  30762. }
  30763. if ( prevTime !== null && prevTime > currTime ) {
  30764. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  30765. valid = false;
  30766. break;
  30767. }
  30768. prevTime = currTime;
  30769. }
  30770. if ( values !== undefined ) {
  30771. if ( isTypedArray( values ) ) {
  30772. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  30773. const value = values[ i ];
  30774. if ( isNaN( value ) ) {
  30775. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  30776. valid = false;
  30777. break;
  30778. }
  30779. }
  30780. }
  30781. }
  30782. return valid;
  30783. }
  30784. /**
  30785. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  30786. * common in morph target sequences).
  30787. *
  30788. * @return {AnimationClip} A reference to this animation clip.
  30789. */
  30790. optimize() {
  30791. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  30792. // times or values may be shared with other tracks, so overwriting is unsafe
  30793. const times = this.times.slice(),
  30794. values = this.values.slice(),
  30795. stride = this.getValueSize(),
  30796. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  30797. lastIndex = times.length - 1;
  30798. let writeIndex = 1;
  30799. for ( let i = 1; i < lastIndex; ++ i ) {
  30800. let keep = false;
  30801. const time = times[ i ];
  30802. const timeNext = times[ i + 1 ];
  30803. // remove adjacent keyframes scheduled at the same time
  30804. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  30805. if ( ! smoothInterpolation ) {
  30806. // remove unnecessary keyframes same as their neighbors
  30807. const offset = i * stride,
  30808. offsetP = offset - stride,
  30809. offsetN = offset + stride;
  30810. for ( let j = 0; j !== stride; ++ j ) {
  30811. const value = values[ offset + j ];
  30812. if ( value !== values[ offsetP + j ] ||
  30813. value !== values[ offsetN + j ] ) {
  30814. keep = true;
  30815. break;
  30816. }
  30817. }
  30818. } else {
  30819. keep = true;
  30820. }
  30821. }
  30822. // in-place compaction
  30823. if ( keep ) {
  30824. if ( i !== writeIndex ) {
  30825. times[ writeIndex ] = times[ i ];
  30826. const readOffset = i * stride,
  30827. writeOffset = writeIndex * stride;
  30828. for ( let j = 0; j !== stride; ++ j ) {
  30829. values[ writeOffset + j ] = values[ readOffset + j ];
  30830. }
  30831. }
  30832. ++ writeIndex;
  30833. }
  30834. }
  30835. // flush last keyframe (compaction looks ahead)
  30836. if ( lastIndex > 0 ) {
  30837. times[ writeIndex ] = times[ lastIndex ];
  30838. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  30839. values[ writeOffset + j ] = values[ readOffset + j ];
  30840. }
  30841. ++ writeIndex;
  30842. }
  30843. if ( writeIndex !== times.length ) {
  30844. this.times = times.slice( 0, writeIndex );
  30845. this.values = values.slice( 0, writeIndex * stride );
  30846. } else {
  30847. this.times = times;
  30848. this.values = values;
  30849. }
  30850. return this;
  30851. }
  30852. /**
  30853. * Returns a new keyframe track with copied values from this instance.
  30854. *
  30855. * @return {KeyframeTrack} A clone of this instance.
  30856. */
  30857. clone() {
  30858. const times = this.times.slice();
  30859. const values = this.values.slice();
  30860. const TypedKeyframeTrack = this.constructor;
  30861. const track = new TypedKeyframeTrack( this.name, times, values );
  30862. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  30863. track.createInterpolant = this.createInterpolant;
  30864. return track;
  30865. }
  30866. }
  30867. /**
  30868. * The value type name.
  30869. *
  30870. * @type {String}
  30871. * @default ''
  30872. */
  30873. KeyframeTrack.prototype.ValueTypeName = '';
  30874. /**
  30875. * The time buffer type of this keyframe track.
  30876. *
  30877. * @type {TypedArray|Array}
  30878. * @default Float32Array.constructor
  30879. */
  30880. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  30881. /**
  30882. * The value buffer type of this keyframe track.
  30883. *
  30884. * @type {TypedArray|Array}
  30885. * @default Float32Array.constructor
  30886. */
  30887. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  30888. /**
  30889. * The default interpolation type of this keyframe track.
  30890. *
  30891. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  30892. * @default InterpolateLinear
  30893. */
  30894. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  30895. /**
  30896. * A track for boolean keyframe values.
  30897. *
  30898. * @augments KeyframeTrack
  30899. */
  30900. class BooleanKeyframeTrack extends KeyframeTrack {
  30901. /**
  30902. * Constructs a new boolean keyframe track.
  30903. *
  30904. * This keyframe track type has no `interpolation` parameter because the
  30905. * interpolation is always discrete.
  30906. *
  30907. * @param {string} name - The keyframe track's name.
  30908. * @param {Array<number>} times - A list of keyframe times.
  30909. * @param {Array<number>} values - A list of keyframe values.
  30910. */
  30911. constructor( name, times, values ) {
  30912. super( name, times, values );
  30913. }
  30914. }
  30915. /**
  30916. * The value type name.
  30917. *
  30918. * @type {String}
  30919. * @default 'bool'
  30920. */
  30921. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  30922. /**
  30923. * The value buffer type of this keyframe track.
  30924. *
  30925. * @type {TypedArray|Array}
  30926. * @default Array.constructor
  30927. */
  30928. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  30929. /**
  30930. * The default interpolation type of this keyframe track.
  30931. *
  30932. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  30933. * @default InterpolateDiscrete
  30934. */
  30935. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  30936. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  30937. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  30938. /**
  30939. * A track for color keyframe values.
  30940. *
  30941. * @augments KeyframeTrack
  30942. */
  30943. class ColorKeyframeTrack extends KeyframeTrack {
  30944. /**
  30945. * Constructs a new color keyframe track.
  30946. *
  30947. * @param {string} name - The keyframe track's name.
  30948. * @param {Array<number>} times - A list of keyframe times.
  30949. * @param {Array<number>} values - A list of keyframe values.
  30950. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30951. */
  30952. constructor( name, times, values, interpolation ) {
  30953. super( name, times, values, interpolation );
  30954. }
  30955. }
  30956. /**
  30957. * The value type name.
  30958. *
  30959. * @type {String}
  30960. * @default 'color'
  30961. */
  30962. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  30963. /**
  30964. * A track for numeric keyframe values.
  30965. *
  30966. * @augments KeyframeTrack
  30967. */
  30968. class NumberKeyframeTrack extends KeyframeTrack {
  30969. /**
  30970. * Constructs a new number keyframe track.
  30971. *
  30972. * @param {string} name - The keyframe track's name.
  30973. * @param {Array<number>} times - A list of keyframe times.
  30974. * @param {Array<number>} values - A list of keyframe values.
  30975. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30976. */
  30977. constructor( name, times, values, interpolation ) {
  30978. super( name, times, values, interpolation );
  30979. }
  30980. }
  30981. /**
  30982. * The value type name.
  30983. *
  30984. * @type {String}
  30985. * @default 'number'
  30986. */
  30987. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  30988. /**
  30989. * Spherical linear unit quaternion interpolant.
  30990. *
  30991. * @augments Interpolant
  30992. */
  30993. class QuaternionLinearInterpolant extends Interpolant {
  30994. /**
  30995. * Constructs a new SLERP interpolant.
  30996. *
  30997. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30998. * @param {TypedArray} sampleValues - The sample values.
  30999. * @param {number} sampleSize - The sample size
  31000. * @param {TypedArray} [resultBuffer] - The result buffer.
  31001. */
  31002. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31003. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31004. }
  31005. interpolate_( i1, t0, t, t1 ) {
  31006. const result = this.resultBuffer,
  31007. values = this.sampleValues,
  31008. stride = this.valueSize,
  31009. alpha = ( t - t0 ) / ( t1 - t0 );
  31010. let offset = i1 * stride;
  31011. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31012. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31013. }
  31014. return result;
  31015. }
  31016. }
  31017. /**
  31018. * A track for Quaternion keyframe values.
  31019. *
  31020. * @augments KeyframeTrack
  31021. */
  31022. class QuaternionKeyframeTrack extends KeyframeTrack {
  31023. /**
  31024. * Constructs a new Quaternion keyframe track.
  31025. *
  31026. * @param {string} name - The keyframe track's name.
  31027. * @param {Array<number>} times - A list of keyframe times.
  31028. * @param {Array<number>} values - A list of keyframe values.
  31029. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31030. */
  31031. constructor( name, times, values, interpolation ) {
  31032. super( name, times, values, interpolation );
  31033. }
  31034. /**
  31035. * Overwritten so the method returns Quaternion based interpolant.
  31036. *
  31037. * @static
  31038. * @param {TypedArray} [result] - The result buffer.
  31039. * @return {QuaternionLinearInterpolant} The new interpolant.
  31040. */
  31041. InterpolantFactoryMethodLinear( result ) {
  31042. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31043. }
  31044. }
  31045. /**
  31046. * The value type name.
  31047. *
  31048. * @type {String}
  31049. * @default 'quaternion'
  31050. */
  31051. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31052. // ValueBufferType is inherited
  31053. // DefaultInterpolation is inherited;
  31054. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31055. /**
  31056. * A track for string keyframe values.
  31057. *
  31058. * @augments KeyframeTrack
  31059. */
  31060. class StringKeyframeTrack extends KeyframeTrack {
  31061. /**
  31062. * Constructs a new string keyframe track.
  31063. *
  31064. * This keyframe track type has no `interpolation` parameter because the
  31065. * interpolation is always discrete.
  31066. *
  31067. * @param {string} name - The keyframe track's name.
  31068. * @param {Array<number>} times - A list of keyframe times.
  31069. * @param {Array<number>} values - A list of keyframe values.
  31070. */
  31071. constructor( name, times, values ) {
  31072. super( name, times, values );
  31073. }
  31074. }
  31075. /**
  31076. * The value type name.
  31077. *
  31078. * @type {String}
  31079. * @default 'string'
  31080. */
  31081. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31082. /**
  31083. * The value buffer type of this keyframe track.
  31084. *
  31085. * @type {TypedArray|Array}
  31086. * @default Array.constructor
  31087. */
  31088. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31089. /**
  31090. * The default interpolation type of this keyframe track.
  31091. *
  31092. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31093. * @default InterpolateDiscrete
  31094. */
  31095. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31096. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31097. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31098. /**
  31099. * A track for vector keyframe values.
  31100. *
  31101. * @augments KeyframeTrack
  31102. */
  31103. class VectorKeyframeTrack extends KeyframeTrack {
  31104. /**
  31105. * Constructs a new vector keyframe track.
  31106. *
  31107. * @param {string} name - The keyframe track's name.
  31108. * @param {Array<number>} times - A list of keyframe times.
  31109. * @param {Array<number>} values - A list of keyframe values.
  31110. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31111. */
  31112. constructor( name, times, values, interpolation ) {
  31113. super( name, times, values, interpolation );
  31114. }
  31115. }
  31116. /**
  31117. * The value type name.
  31118. *
  31119. * @type {String}
  31120. * @default 'vector'
  31121. */
  31122. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31123. /**
  31124. * A reusable set of keyframe tracks which represent an animation.
  31125. */
  31126. class AnimationClip {
  31127. /**
  31128. * Constructs a new animation clip.
  31129. *
  31130. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31131. * use the static interface of this class for creating clips. In most cases though, animation clips
  31132. * will automatically be created by loaders when importing animated 3D assets.
  31133. *
  31134. * @param {string} [name=''] - The clip's name.
  31135. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31136. * the duration will be calculated from the passed keyframes.
  31137. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31138. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31139. * is blended/combined when two or more animations are simultaneously played.
  31140. */
  31141. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31142. /**
  31143. * The clip's name.
  31144. *
  31145. * @type {string}
  31146. */
  31147. this.name = name;
  31148. /**
  31149. * An array of keyframe tracks.
  31150. *
  31151. * @type {Array<KeyframeTrack>}
  31152. */
  31153. this.tracks = tracks;
  31154. /**
  31155. * The clip's duration in seconds.
  31156. *
  31157. * @type {number}
  31158. */
  31159. this.duration = duration;
  31160. /**
  31161. * Defines how the animation is blended/combined when two or more animations
  31162. * are simultaneously played.
  31163. *
  31164. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31165. */
  31166. this.blendMode = blendMode;
  31167. /**
  31168. * The UUID of the animation clip.
  31169. *
  31170. * @type {string}
  31171. * @readonly
  31172. */
  31173. this.uuid = generateUUID();
  31174. // this means it should figure out its duration by scanning the tracks
  31175. if ( this.duration < 0 ) {
  31176. this.resetDuration();
  31177. }
  31178. }
  31179. /**
  31180. * Factory method for creating an animation clip from the given JSON.
  31181. *
  31182. * @static
  31183. * @param {Object} json - The serialized animation clip.
  31184. * @return {AnimationClip} The new animation clip.
  31185. */
  31186. static parse( json ) {
  31187. const tracks = [],
  31188. jsonTracks = json.tracks,
  31189. frameTime = 1.0 / ( json.fps || 1.0 );
  31190. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31191. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31192. }
  31193. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31194. clip.uuid = json.uuid;
  31195. return clip;
  31196. }
  31197. /**
  31198. * Serializes the given animation clip into JSON.
  31199. *
  31200. * @static
  31201. * @param {AnimationClip} clip - The animation clip to serialize.
  31202. * @return {Object} The JSON object.
  31203. */
  31204. static toJSON( clip ) {
  31205. const tracks = [],
  31206. clipTracks = clip.tracks;
  31207. const json = {
  31208. 'name': clip.name,
  31209. 'duration': clip.duration,
  31210. 'tracks': tracks,
  31211. 'uuid': clip.uuid,
  31212. 'blendMode': clip.blendMode
  31213. };
  31214. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31215. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31216. }
  31217. return json;
  31218. }
  31219. /**
  31220. * Returns a new animation clip from the passed morph targets array of a
  31221. * geometry, taking a name and the number of frames per second.
  31222. *
  31223. * Note: The fps parameter is required, but the animation speed can be
  31224. * overridden via {@link AnimationAction#setDuration}.
  31225. *
  31226. * @static
  31227. * @param {string} name - The name of the animation clip.
  31228. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31229. * @param {number} fps - The Frames-Per-Second value.
  31230. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31231. * @return {AnimationClip} The new animation clip.
  31232. */
  31233. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  31234. const numMorphTargets = morphTargetSequence.length;
  31235. const tracks = [];
  31236. for ( let i = 0; i < numMorphTargets; i ++ ) {
  31237. let times = [];
  31238. let values = [];
  31239. times.push(
  31240. ( i + numMorphTargets - 1 ) % numMorphTargets,
  31241. i,
  31242. ( i + 1 ) % numMorphTargets );
  31243. values.push( 0, 1, 0 );
  31244. const order = getKeyframeOrder( times );
  31245. times = sortedArray( times, 1, order );
  31246. values = sortedArray( values, 1, order );
  31247. // if there is a key at the first frame, duplicate it as the
  31248. // last frame as well for perfect loop.
  31249. if ( ! noLoop && times[ 0 ] === 0 ) {
  31250. times.push( numMorphTargets );
  31251. values.push( values[ 0 ] );
  31252. }
  31253. tracks.push(
  31254. new NumberKeyframeTrack(
  31255. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  31256. times, values
  31257. ).scale( 1.0 / fps ) );
  31258. }
  31259. return new this( name, -1, tracks );
  31260. }
  31261. /**
  31262. * Searches for an animation clip by name, taking as its first parameter
  31263. * either an array of clips, or a mesh or geometry that contains an
  31264. * array named "animations" property.
  31265. *
  31266. * @static
  31267. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  31268. * @param {string} name - The name to search for.
  31269. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  31270. */
  31271. static findByName( objectOrClipArray, name ) {
  31272. let clipArray = objectOrClipArray;
  31273. if ( ! Array.isArray( objectOrClipArray ) ) {
  31274. const o = objectOrClipArray;
  31275. clipArray = o.geometry && o.geometry.animations || o.animations;
  31276. }
  31277. for ( let i = 0; i < clipArray.length; i ++ ) {
  31278. if ( clipArray[ i ].name === name ) {
  31279. return clipArray[ i ];
  31280. }
  31281. }
  31282. return null;
  31283. }
  31284. /**
  31285. * Returns an array of new AnimationClips created from the morph target
  31286. * sequences of a geometry, trying to sort morph target names into
  31287. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  31288. *
  31289. * See {@link MD2Loader#parse} as an example for how the method should be used.
  31290. *
  31291. * @static
  31292. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  31293. * @param {number} fps - The Frames-Per-Second value.
  31294. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31295. * @return {Array<AnimationClip>} An array of new animation clips.
  31296. */
  31297. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  31298. const animationToMorphTargets = {};
  31299. // tested with https://regex101.com/ on trick sequences
  31300. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  31301. const pattern = /^([\w-]*?)([\d]+)$/;
  31302. // sort morph target names into animation groups based
  31303. // patterns like Walk_001, Walk_002, Run_001, Run_002
  31304. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  31305. const morphTarget = morphTargets[ i ];
  31306. const parts = morphTarget.name.match( pattern );
  31307. if ( parts && parts.length > 1 ) {
  31308. const name = parts[ 1 ];
  31309. let animationMorphTargets = animationToMorphTargets[ name ];
  31310. if ( ! animationMorphTargets ) {
  31311. animationToMorphTargets[ name ] = animationMorphTargets = [];
  31312. }
  31313. animationMorphTargets.push( morphTarget );
  31314. }
  31315. }
  31316. const clips = [];
  31317. for ( const name in animationToMorphTargets ) {
  31318. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  31319. }
  31320. return clips;
  31321. }
  31322. /**
  31323. * Parses the `animation.hierarchy` format and returns a new animation clip.
  31324. *
  31325. * @static
  31326. * @deprecated since r175.
  31327. * @param {Object} animation - A serialized animation clip as JSON.
  31328. * @param {Array<Bones>} bones - An array of bones.
  31329. * @return {?AnimationClip} The new animation clip.
  31330. */
  31331. static parseAnimation( animation, bones ) {
  31332. console.warn( 'THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  31333. if ( ! animation ) {
  31334. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  31335. return null;
  31336. }
  31337. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  31338. // only return track if there are actually keys.
  31339. if ( animationKeys.length !== 0 ) {
  31340. const times = [];
  31341. const values = [];
  31342. flattenJSON( animationKeys, times, values, propertyName );
  31343. // empty keys are filtered out, so check again
  31344. if ( times.length !== 0 ) {
  31345. destTracks.push( new trackType( trackName, times, values ) );
  31346. }
  31347. }
  31348. };
  31349. const tracks = [];
  31350. const clipName = animation.name || 'default';
  31351. const fps = animation.fps || 30;
  31352. const blendMode = animation.blendMode;
  31353. // automatic length determination in AnimationClip.
  31354. let duration = animation.length || -1;
  31355. const hierarchyTracks = animation.hierarchy || [];
  31356. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  31357. const animationKeys = hierarchyTracks[ h ].keys;
  31358. // skip empty tracks
  31359. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  31360. // process morph targets
  31361. if ( animationKeys[ 0 ].morphTargets ) {
  31362. // figure out all morph targets used in this track
  31363. const morphTargetNames = {};
  31364. let k;
  31365. for ( k = 0; k < animationKeys.length; k ++ ) {
  31366. if ( animationKeys[ k ].morphTargets ) {
  31367. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  31368. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  31369. }
  31370. }
  31371. }
  31372. // create a track for each morph target with all zero
  31373. // morphTargetInfluences except for the keys in which
  31374. // the morphTarget is named.
  31375. for ( const morphTargetName in morphTargetNames ) {
  31376. const times = [];
  31377. const values = [];
  31378. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  31379. const animationKey = animationKeys[ k ];
  31380. times.push( animationKey.time );
  31381. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  31382. }
  31383. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  31384. }
  31385. duration = morphTargetNames.length * fps;
  31386. } else {
  31387. // ...assume skeletal animation
  31388. const boneName = '.bones[' + bones[ h ].name + ']';
  31389. addNonemptyTrack(
  31390. VectorKeyframeTrack, boneName + '.position',
  31391. animationKeys, 'pos', tracks );
  31392. addNonemptyTrack(
  31393. QuaternionKeyframeTrack, boneName + '.quaternion',
  31394. animationKeys, 'rot', tracks );
  31395. addNonemptyTrack(
  31396. VectorKeyframeTrack, boneName + '.scale',
  31397. animationKeys, 'scl', tracks );
  31398. }
  31399. }
  31400. if ( tracks.length === 0 ) {
  31401. return null;
  31402. }
  31403. const clip = new this( clipName, duration, tracks, blendMode );
  31404. return clip;
  31405. }
  31406. /**
  31407. * Sets the duration of this clip to the duration of its longest keyframe track.
  31408. *
  31409. * @return {AnimationClip} A reference to this animation clip.
  31410. */
  31411. resetDuration() {
  31412. const tracks = this.tracks;
  31413. let duration = 0;
  31414. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  31415. const track = this.tracks[ i ];
  31416. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  31417. }
  31418. this.duration = duration;
  31419. return this;
  31420. }
  31421. /**
  31422. * Trims all tracks to the clip's duration.
  31423. *
  31424. * @return {AnimationClip} A reference to this animation clip.
  31425. */
  31426. trim() {
  31427. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31428. this.tracks[ i ].trim( 0, this.duration );
  31429. }
  31430. return this;
  31431. }
  31432. /**
  31433. * Performs minimal validation on each track in the clip. Returns `true` if all
  31434. * tracks are valid.
  31435. *
  31436. * @return {boolean} Whether the clip's keyframes are valid or not.
  31437. */
  31438. validate() {
  31439. let valid = true;
  31440. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31441. valid = valid && this.tracks[ i ].validate();
  31442. }
  31443. return valid;
  31444. }
  31445. /**
  31446. * Optimizes each track by removing equivalent sequential keys (which are
  31447. * common in morph target sequences).
  31448. *
  31449. * @return {AnimationClip} A reference to this animation clip.
  31450. */
  31451. optimize() {
  31452. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31453. this.tracks[ i ].optimize();
  31454. }
  31455. return this;
  31456. }
  31457. /**
  31458. * Returns a new animation clip with copied values from this instance.
  31459. *
  31460. * @return {AnimationClip} A clone of this instance.
  31461. */
  31462. clone() {
  31463. const tracks = [];
  31464. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31465. tracks.push( this.tracks[ i ].clone() );
  31466. }
  31467. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  31468. }
  31469. /**
  31470. * Serializes this animation clip into JSON.
  31471. *
  31472. * @return {Object} The JSON object.
  31473. */
  31474. toJSON() {
  31475. return this.constructor.toJSON( this );
  31476. }
  31477. }
  31478. function getTrackTypeForValueTypeName( typeName ) {
  31479. switch ( typeName.toLowerCase() ) {
  31480. case 'scalar':
  31481. case 'double':
  31482. case 'float':
  31483. case 'number':
  31484. case 'integer':
  31485. return NumberKeyframeTrack;
  31486. case 'vector':
  31487. case 'vector2':
  31488. case 'vector3':
  31489. case 'vector4':
  31490. return VectorKeyframeTrack;
  31491. case 'color':
  31492. return ColorKeyframeTrack;
  31493. case 'quaternion':
  31494. return QuaternionKeyframeTrack;
  31495. case 'bool':
  31496. case 'boolean':
  31497. return BooleanKeyframeTrack;
  31498. case 'string':
  31499. return StringKeyframeTrack;
  31500. }
  31501. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  31502. }
  31503. function parseKeyframeTrack( json ) {
  31504. if ( json.type === undefined ) {
  31505. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  31506. }
  31507. const trackType = getTrackTypeForValueTypeName( json.type );
  31508. if ( json.times === undefined ) {
  31509. const times = [], values = [];
  31510. flattenJSON( json.keys, times, values, 'value' );
  31511. json.times = times;
  31512. json.values = values;
  31513. }
  31514. // derived classes can define a static parse method
  31515. if ( trackType.parse !== undefined ) {
  31516. return trackType.parse( json );
  31517. } else {
  31518. // by default, we assume a constructor compatible with the base
  31519. return new trackType( json.name, json.times, json.values, json.interpolation );
  31520. }
  31521. }
  31522. /**
  31523. * @class
  31524. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  31525. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  31526. * @hideconstructor
  31527. */
  31528. const Cache = {
  31529. /**
  31530. * Whether caching is enabled or not.
  31531. *
  31532. * @static
  31533. * @type {boolean}
  31534. * @default false
  31535. */
  31536. enabled: false,
  31537. /**
  31538. * A dictionary that holds cached files.
  31539. *
  31540. * @static
  31541. * @type {Object<string,Object>}
  31542. */
  31543. files: {},
  31544. /**
  31545. * Adds a cache entry with a key to reference the file. If this key already
  31546. * holds a file, it is overwritten.
  31547. *
  31548. * @static
  31549. * @param {string} key - The key to reference the cached file.
  31550. * @param {Object} file - The file to be cached.
  31551. */
  31552. add: function ( key, file ) {
  31553. if ( this.enabled === false ) return;
  31554. // console.log( 'THREE.Cache', 'Adding key:', key );
  31555. this.files[ key ] = file;
  31556. },
  31557. /**
  31558. * Gets the cached value for the given key.
  31559. *
  31560. * @static
  31561. * @param {string} key - The key to reference the cached file.
  31562. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  31563. */
  31564. get: function ( key ) {
  31565. if ( this.enabled === false ) return;
  31566. // console.log( 'THREE.Cache', 'Checking key:', key );
  31567. return this.files[ key ];
  31568. },
  31569. /**
  31570. * Removes the cached file associated with the given key.
  31571. *
  31572. * @static
  31573. * @param {string} key - The key to reference the cached file.
  31574. */
  31575. remove: function ( key ) {
  31576. delete this.files[ key ];
  31577. },
  31578. /**
  31579. * Remove all values from the cache.
  31580. *
  31581. * @static
  31582. */
  31583. clear: function () {
  31584. this.files = {};
  31585. }
  31586. };
  31587. /**
  31588. * Handles and keeps track of loaded and pending data. A default global
  31589. * instance of this class is created and used by loaders if not supplied
  31590. * manually.
  31591. *
  31592. * In general that should be sufficient, however there are times when it can
  31593. * be useful to have separate loaders - for example if you want to show
  31594. * separate loading bars for objects and textures.
  31595. *
  31596. * ```js
  31597. * const manager = new THREE.LoadingManager();
  31598. * manager.onLoad = () => console.log( 'Loading complete!' );
  31599. *
  31600. * const loader1 = new OBJLoader( manager );
  31601. * const loader2 = new ColladaLoader( manager );
  31602. * ```
  31603. */
  31604. class LoadingManager {
  31605. /**
  31606. * Constructs a new loading manager.
  31607. *
  31608. * @param {Function} [onLoad] - Executes when all items have been loaded.
  31609. * @param {Function} [onProgress] - Executes when single items have been loaded.
  31610. * @param {Function} [onError] - Executes when an error occurs.
  31611. */
  31612. constructor( onLoad, onProgress, onError ) {
  31613. const scope = this;
  31614. let isLoading = false;
  31615. let itemsLoaded = 0;
  31616. let itemsTotal = 0;
  31617. let urlModifier = undefined;
  31618. const handlers = [];
  31619. // Refer to #5689 for the reason why we don't set .onStart
  31620. // in the constructor
  31621. /**
  31622. * Executes when an item starts loading.
  31623. *
  31624. * @type {Function|undefined}
  31625. * @default undefined
  31626. */
  31627. this.onStart = undefined;
  31628. /**
  31629. * Executes when all items have been loaded.
  31630. *
  31631. * @type {Function|undefined}
  31632. * @default undefined
  31633. */
  31634. this.onLoad = onLoad;
  31635. /**
  31636. * Executes when single items have been loaded.
  31637. *
  31638. * @type {Function|undefined}
  31639. * @default undefined
  31640. */
  31641. this.onProgress = onProgress;
  31642. /**
  31643. * Executes when an error occurs.
  31644. *
  31645. * @type {Function|undefined}
  31646. * @default undefined
  31647. */
  31648. this.onError = onError;
  31649. /**
  31650. * This should be called by any loader using the manager when the loader
  31651. * starts loading an item.
  31652. *
  31653. * @param {string} url - The URL to load.
  31654. */
  31655. this.itemStart = function ( url ) {
  31656. itemsTotal ++;
  31657. if ( isLoading === false ) {
  31658. if ( scope.onStart !== undefined ) {
  31659. scope.onStart( url, itemsLoaded, itemsTotal );
  31660. }
  31661. }
  31662. isLoading = true;
  31663. };
  31664. /**
  31665. * This should be called by any loader using the manager when the loader
  31666. * ended loading an item.
  31667. *
  31668. * @param {string} url - The URL of the loaded item.
  31669. */
  31670. this.itemEnd = function ( url ) {
  31671. itemsLoaded ++;
  31672. if ( scope.onProgress !== undefined ) {
  31673. scope.onProgress( url, itemsLoaded, itemsTotal );
  31674. }
  31675. if ( itemsLoaded === itemsTotal ) {
  31676. isLoading = false;
  31677. if ( scope.onLoad !== undefined ) {
  31678. scope.onLoad();
  31679. }
  31680. }
  31681. };
  31682. /**
  31683. * This should be called by any loader using the manager when the loader
  31684. * encounters an error when loading an item.
  31685. *
  31686. * @param {string} url - The URL of the item that produces an error.
  31687. */
  31688. this.itemError = function ( url ) {
  31689. if ( scope.onError !== undefined ) {
  31690. scope.onError( url );
  31691. }
  31692. };
  31693. /**
  31694. * Given a URL, uses the URL modifier callback (if any) and returns a
  31695. * resolved URL. If no URL modifier is set, returns the original URL.
  31696. *
  31697. * @param {string} url - The URL to load.
  31698. * @return {string} The resolved URL.
  31699. */
  31700. this.resolveURL = function ( url ) {
  31701. if ( urlModifier ) {
  31702. return urlModifier( url );
  31703. }
  31704. return url;
  31705. };
  31706. /**
  31707. * If provided, the callback will be passed each resource URL before a
  31708. * request is sent. The callback may return the original URL, or a new URL to
  31709. * override loading behavior. This behavior can be used to load assets from
  31710. * .ZIP files, drag-and-drop APIs, and Data URIs.
  31711. *
  31712. * ```js
  31713. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  31714. *
  31715. * const manager = new THREE.LoadingManager();
  31716. *
  31717. * // Initialize loading manager with URL callback.
  31718. * const objectURLs = [];
  31719. * manager.setURLModifier( ( url ) => {
  31720. *
  31721. * url = URL.createObjectURL( blobs[ url ] );
  31722. * objectURLs.push( url );
  31723. * return url;
  31724. *
  31725. * } );
  31726. *
  31727. * // Load as usual, then revoke the blob URLs.
  31728. * const loader = new GLTFLoader( manager );
  31729. * loader.load( 'fish.gltf', (gltf) => {
  31730. *
  31731. * scene.add( gltf.scene );
  31732. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  31733. *
  31734. * } );
  31735. * ```
  31736. *
  31737. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  31738. * @return {LoadingManager} A reference to this loading manager.
  31739. */
  31740. this.setURLModifier = function ( transform ) {
  31741. urlModifier = transform;
  31742. return this;
  31743. };
  31744. /**
  31745. * Registers a loader with the given regular expression. Can be used to
  31746. * define what loader should be used in order to load specific files. A
  31747. * typical use case is to overwrite the default loader for textures.
  31748. *
  31749. * ```js
  31750. * // add handler for TGA textures
  31751. * manager.addHandler( /\.tga$/i, new TGALoader() );
  31752. * ```
  31753. *
  31754. * @param {string} regex - A regular expression.
  31755. * @param {Loader} loader - A loader that should handle matched cases.
  31756. * @return {LoadingManager} A reference to this loading manager.
  31757. */
  31758. this.addHandler = function ( regex, loader ) {
  31759. handlers.push( regex, loader );
  31760. return this;
  31761. };
  31762. /**
  31763. * Removes the loader for the given regular expression.
  31764. *
  31765. * @param {string} regex - A regular expression.
  31766. * @return {LoadingManager} A reference to this loading manager.
  31767. */
  31768. this.removeHandler = function ( regex ) {
  31769. const index = handlers.indexOf( regex );
  31770. if ( index !== -1 ) {
  31771. handlers.splice( index, 2 );
  31772. }
  31773. return this;
  31774. };
  31775. /**
  31776. * Can be used to retrieve the registered loader for the given file path.
  31777. *
  31778. * @param {string} file - The file path.
  31779. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  31780. */
  31781. this.getHandler = function ( file ) {
  31782. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  31783. const regex = handlers[ i ];
  31784. const loader = handlers[ i + 1 ];
  31785. if ( regex.global ) regex.lastIndex = 0; // see #17920
  31786. if ( regex.test( file ) ) {
  31787. return loader;
  31788. }
  31789. }
  31790. return null;
  31791. };
  31792. }
  31793. }
  31794. /**
  31795. * The global default loading manager.
  31796. *
  31797. * @constant
  31798. * @type {LoadingManager}
  31799. */
  31800. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  31801. /**
  31802. * Abstract base class for loaders.
  31803. *
  31804. * @abstract
  31805. */
  31806. class Loader {
  31807. /**
  31808. * Constructs a new loader.
  31809. *
  31810. * @param {LoadingManager} [manager] - The loading manager.
  31811. */
  31812. constructor( manager ) {
  31813. /**
  31814. * The loading manager.
  31815. *
  31816. * @type {LoadingManager}
  31817. * @default DefaultLoadingManager
  31818. */
  31819. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  31820. /**
  31821. * The crossOrigin string to implement CORS for loading the url from a
  31822. * different domain that allows CORS.
  31823. *
  31824. * @type {string}
  31825. * @default 'anonymous'
  31826. */
  31827. this.crossOrigin = 'anonymous';
  31828. /**
  31829. * Whether the XMLHttpRequest uses credentials.
  31830. *
  31831. * @type {boolean}
  31832. * @default false
  31833. */
  31834. this.withCredentials = false;
  31835. /**
  31836. * The base path from which the asset will be loaded.
  31837. *
  31838. * @type {string}
  31839. */
  31840. this.path = '';
  31841. /**
  31842. * The base path from which additional resources like textures will be loaded.
  31843. *
  31844. * @type {string}
  31845. */
  31846. this.resourcePath = '';
  31847. /**
  31848. * The [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  31849. * used in HTTP request.
  31850. *
  31851. * @type {Object<string, any>}
  31852. */
  31853. this.requestHeader = {};
  31854. }
  31855. /**
  31856. * This method needs to be implemented by all concrete loaders. It holds the
  31857. * logic for loading assets from the backend.
  31858. *
  31859. * @param {string} url - The path/URL of the file to be loaded.
  31860. * @param {Function} onLoad - Executed when the loading process has been finished.
  31861. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  31862. * @param {onErrorCallback} [onError] - Executed when errors occur.
  31863. */
  31864. load( /* url, onLoad, onProgress, onError */ ) {}
  31865. /**
  31866. * A async version of {@link Loader#load}.
  31867. *
  31868. * @param {string} url - The path/URL of the file to be loaded.
  31869. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  31870. * @return {Promise} A Promise that resolves when the asset has been loaded.
  31871. */
  31872. loadAsync( url, onProgress ) {
  31873. const scope = this;
  31874. return new Promise( function ( resolve, reject ) {
  31875. scope.load( url, resolve, onProgress, reject );
  31876. } );
  31877. }
  31878. /**
  31879. * This method needs to be implemented by all concrete loaders. It holds the
  31880. * logic for parsing the asset into three.js entities.
  31881. *
  31882. * @param {any} data - The data to parse.
  31883. */
  31884. parse( /* data */ ) {}
  31885. /**
  31886. * Sets the `crossOrigin` String to implement CORS for loading the URL
  31887. * from a different domain that allows CORS.
  31888. *
  31889. * @param {string} crossOrigin - The `crossOrigin` value.
  31890. * @return {Loader} A reference to this instance.
  31891. */
  31892. setCrossOrigin( crossOrigin ) {
  31893. this.crossOrigin = crossOrigin;
  31894. return this;
  31895. }
  31896. /**
  31897. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  31898. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials}.
  31899. *
  31900. * Note: This setting has no effect if you are loading files locally or from the same domain.
  31901. *
  31902. * @param {boolean} value - The `withCredentials` value.
  31903. * @return {Loader} A reference to this instance.
  31904. */
  31905. setWithCredentials( value ) {
  31906. this.withCredentials = value;
  31907. return this;
  31908. }
  31909. /**
  31910. * Sets the base path for the asset.
  31911. *
  31912. * @param {string} path - The base path.
  31913. * @return {Loader} A reference to this instance.
  31914. */
  31915. setPath( path ) {
  31916. this.path = path;
  31917. return this;
  31918. }
  31919. /**
  31920. * Sets the base path for dependent resources like textures.
  31921. *
  31922. * @param {string} resourcePath - The resource path.
  31923. * @return {Loader} A reference to this instance.
  31924. */
  31925. setResourcePath( resourcePath ) {
  31926. this.resourcePath = resourcePath;
  31927. return this;
  31928. }
  31929. /**
  31930. * Sets the given request header.
  31931. *
  31932. * @param {Object} requestHeader - A [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  31933. * for configuring the HTTP request.
  31934. * @return {Loader} A reference to this instance.
  31935. */
  31936. setRequestHeader( requestHeader ) {
  31937. this.requestHeader = requestHeader;
  31938. return this;
  31939. }
  31940. }
  31941. /**
  31942. * Callback for onProgress in loaders.
  31943. *
  31944. * @callback onProgressCallback
  31945. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  31946. */
  31947. /**
  31948. * Callback for onError in loaders.
  31949. *
  31950. * @callback onErrorCallback
  31951. * @param {Error} error - The error which occurred during the loading process.
  31952. */
  31953. /**
  31954. * The default material name that is used by loaders
  31955. * when creating materials for loaded 3D objects.
  31956. *
  31957. * Note: Not all loaders might honor this setting.
  31958. *
  31959. * @static
  31960. * @type {string}
  31961. * @default '__DEFAULT'
  31962. */
  31963. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  31964. const loading = {};
  31965. class HttpError extends Error {
  31966. constructor( message, response ) {
  31967. super( message );
  31968. this.response = response;
  31969. }
  31970. }
  31971. /**
  31972. * A low level class for loading resources with the Fetch API, used internally by
  31973. * most loaders. It can also be used directly to load any file type that does
  31974. * not have a loader.
  31975. *
  31976. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  31977. * once to your application.
  31978. *
  31979. * ```js
  31980. * const loader = new THREE.FileLoader();
  31981. * const data = await loader.loadAsync( 'example.txt' );
  31982. * ```
  31983. *
  31984. * @augments Loader
  31985. */
  31986. class FileLoader extends Loader {
  31987. /**
  31988. * Constructs a new file loader.
  31989. *
  31990. * @param {LoadingManager} [manager] - The loading manager.
  31991. */
  31992. constructor( manager ) {
  31993. super( manager );
  31994. /**
  31995. * The expected mime type.
  31996. *
  31997. * @type {string}
  31998. */
  31999. this.mimeType = '';
  32000. /**
  32001. * The expected response type.
  32002. *
  32003. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32004. * @default ''
  32005. */
  32006. this.responseType = '';
  32007. }
  32008. /**
  32009. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32010. *
  32011. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32012. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32013. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32014. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32015. * @return {any|undefined} The cached resource if available.
  32016. */
  32017. load( url, onLoad, onProgress, onError ) {
  32018. if ( url === undefined ) url = '';
  32019. if ( this.path !== undefined ) url = this.path + url;
  32020. url = this.manager.resolveURL( url );
  32021. const cached = Cache.get( url );
  32022. if ( cached !== undefined ) {
  32023. this.manager.itemStart( url );
  32024. setTimeout( () => {
  32025. if ( onLoad ) onLoad( cached );
  32026. this.manager.itemEnd( url );
  32027. }, 0 );
  32028. return cached;
  32029. }
  32030. // Check if request is duplicate
  32031. if ( loading[ url ] !== undefined ) {
  32032. loading[ url ].push( {
  32033. onLoad: onLoad,
  32034. onProgress: onProgress,
  32035. onError: onError
  32036. } );
  32037. return;
  32038. }
  32039. // Initialise array for duplicate requests
  32040. loading[ url ] = [];
  32041. loading[ url ].push( {
  32042. onLoad: onLoad,
  32043. onProgress: onProgress,
  32044. onError: onError,
  32045. } );
  32046. // create request
  32047. const req = new Request( url, {
  32048. headers: new Headers( this.requestHeader ),
  32049. credentials: this.withCredentials ? 'include' : 'same-origin',
  32050. // An abort controller could be added within a future PR
  32051. } );
  32052. // record states ( avoid data race )
  32053. const mimeType = this.mimeType;
  32054. const responseType = this.responseType;
  32055. // start the fetch
  32056. fetch( req )
  32057. .then( response => {
  32058. if ( response.status === 200 || response.status === 0 ) {
  32059. // Some browsers return HTTP Status 0 when using non-http protocol
  32060. // e.g. 'file://' or 'data://'. Handle as success.
  32061. if ( response.status === 0 ) {
  32062. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  32063. }
  32064. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32065. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32066. return response;
  32067. }
  32068. const callbacks = loading[ url ];
  32069. const reader = response.body.getReader();
  32070. // Nginx needs X-File-Size check
  32071. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32072. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32073. const total = contentLength ? parseInt( contentLength ) : 0;
  32074. const lengthComputable = total !== 0;
  32075. let loaded = 0;
  32076. // periodically read data into the new stream tracking while download progress
  32077. const stream = new ReadableStream( {
  32078. start( controller ) {
  32079. readData();
  32080. function readData() {
  32081. reader.read().then( ( { done, value } ) => {
  32082. if ( done ) {
  32083. controller.close();
  32084. } else {
  32085. loaded += value.byteLength;
  32086. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32087. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32088. const callback = callbacks[ i ];
  32089. if ( callback.onProgress ) callback.onProgress( event );
  32090. }
  32091. controller.enqueue( value );
  32092. readData();
  32093. }
  32094. }, ( e ) => {
  32095. controller.error( e );
  32096. } );
  32097. }
  32098. }
  32099. } );
  32100. return new Response( stream );
  32101. } else {
  32102. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32103. }
  32104. } )
  32105. .then( response => {
  32106. switch ( responseType ) {
  32107. case 'arraybuffer':
  32108. return response.arrayBuffer();
  32109. case 'blob':
  32110. return response.blob();
  32111. case 'document':
  32112. return response.text()
  32113. .then( text => {
  32114. const parser = new DOMParser();
  32115. return parser.parseFromString( text, mimeType );
  32116. } );
  32117. case 'json':
  32118. return response.json();
  32119. default:
  32120. if ( mimeType === '' ) {
  32121. return response.text();
  32122. } else {
  32123. // sniff encoding
  32124. const re = /charset="?([^;"\s]*)"?/i;
  32125. const exec = re.exec( mimeType );
  32126. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32127. const decoder = new TextDecoder( label );
  32128. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32129. }
  32130. }
  32131. } )
  32132. .then( data => {
  32133. // Add to cache only on HTTP success, so that we do not cache
  32134. // error response bodies as proper responses to requests.
  32135. Cache.add( url, data );
  32136. const callbacks = loading[ url ];
  32137. delete loading[ url ];
  32138. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32139. const callback = callbacks[ i ];
  32140. if ( callback.onLoad ) callback.onLoad( data );
  32141. }
  32142. } )
  32143. .catch( err => {
  32144. // Abort errors and other errors are handled the same
  32145. const callbacks = loading[ url ];
  32146. if ( callbacks === undefined ) {
  32147. // When onLoad was called and url was deleted in `loading`
  32148. this.manager.itemError( url );
  32149. throw err;
  32150. }
  32151. delete loading[ url ];
  32152. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32153. const callback = callbacks[ i ];
  32154. if ( callback.onError ) callback.onError( err );
  32155. }
  32156. this.manager.itemError( url );
  32157. } )
  32158. .finally( () => {
  32159. this.manager.itemEnd( url );
  32160. } );
  32161. this.manager.itemStart( url );
  32162. }
  32163. /**
  32164. * Sets the expected response type.
  32165. *
  32166. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32167. * @return {FileLoader} A reference to this file loader.
  32168. */
  32169. setResponseType( value ) {
  32170. this.responseType = value;
  32171. return this;
  32172. }
  32173. /**
  32174. * Sets the expected mime type of the loaded file.
  32175. *
  32176. * @param {string} value - The mime type.
  32177. * @return {FileLoader} A reference to this file loader.
  32178. */
  32179. setMimeType( value ) {
  32180. this.mimeType = value;
  32181. return this;
  32182. }
  32183. }
  32184. /**
  32185. * Class for loading animation clips in the JSON format. The files are internally
  32186. * loaded via {@link FileLoader}.
  32187. *
  32188. * ```js
  32189. * const loader = new THREE.AnimationLoader();
  32190. * const animations = await loader.loadAsync( 'animations/animation.js' );
  32191. * ```
  32192. *
  32193. * @augments Loader
  32194. */
  32195. class AnimationLoader extends Loader {
  32196. /**
  32197. * Constructs a new animation loader.
  32198. *
  32199. * @param {LoadingManager} [manager] - The loading manager.
  32200. */
  32201. constructor( manager ) {
  32202. super( manager );
  32203. }
  32204. /**
  32205. * Starts loading from the given URL and pass the loaded animations as an array
  32206. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  32207. *
  32208. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32209. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  32210. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32211. * @param {onErrorCallback} onError - Executed when errors occur.
  32212. */
  32213. load( url, onLoad, onProgress, onError ) {
  32214. const scope = this;
  32215. const loader = new FileLoader( this.manager );
  32216. loader.setPath( this.path );
  32217. loader.setRequestHeader( this.requestHeader );
  32218. loader.setWithCredentials( this.withCredentials );
  32219. loader.load( url, function ( text ) {
  32220. try {
  32221. onLoad( scope.parse( JSON.parse( text ) ) );
  32222. } catch ( e ) {
  32223. if ( onError ) {
  32224. onError( e );
  32225. } else {
  32226. console.error( e );
  32227. }
  32228. scope.manager.itemError( url );
  32229. }
  32230. }, onProgress, onError );
  32231. }
  32232. /**
  32233. * Parses the given JSON object and returns an array of animation clips.
  32234. *
  32235. * @param {Object} json - The serialized animation clips.
  32236. * @return {Array<AnimationClip>} The parsed animation clips.
  32237. */
  32238. parse( json ) {
  32239. const animations = [];
  32240. for ( let i = 0; i < json.length; i ++ ) {
  32241. const clip = AnimationClip.parse( json[ i ] );
  32242. animations.push( clip );
  32243. }
  32244. return animations;
  32245. }
  32246. }
  32247. /**
  32248. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  32249. * Textures are internally loaded via {@link FileLoader}.
  32250. *
  32251. * Derived classes have to implement the `parse()` method which holds the parsing
  32252. * for the respective format.
  32253. *
  32254. * @abstract
  32255. * @augments Loader
  32256. */
  32257. class CompressedTextureLoader extends Loader {
  32258. /**
  32259. * Constructs a new compressed texture loader.
  32260. *
  32261. * @param {LoadingManager} [manager] - The loading manager.
  32262. */
  32263. constructor( manager ) {
  32264. super( manager );
  32265. }
  32266. /**
  32267. * Starts loading from the given URL and passes the loaded compressed texture
  32268. * to the `onLoad()` callback. The method also returns a new texture object which can
  32269. * directly be used for material creation. If you do it this way, the texture
  32270. * may pop up in your scene once the respective loading process is finished.
  32271. *
  32272. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32273. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  32274. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32275. * @param {onErrorCallback} onError - Executed when errors occur.
  32276. * @return {CompressedTexture} The compressed texture.
  32277. */
  32278. load( url, onLoad, onProgress, onError ) {
  32279. const scope = this;
  32280. const images = [];
  32281. const texture = new CompressedTexture();
  32282. const loader = new FileLoader( this.manager );
  32283. loader.setPath( this.path );
  32284. loader.setResponseType( 'arraybuffer' );
  32285. loader.setRequestHeader( this.requestHeader );
  32286. loader.setWithCredentials( scope.withCredentials );
  32287. let loaded = 0;
  32288. function loadTexture( i ) {
  32289. loader.load( url[ i ], function ( buffer ) {
  32290. const texDatas = scope.parse( buffer, true );
  32291. images[ i ] = {
  32292. width: texDatas.width,
  32293. height: texDatas.height,
  32294. format: texDatas.format,
  32295. mipmaps: texDatas.mipmaps
  32296. };
  32297. loaded += 1;
  32298. if ( loaded === 6 ) {
  32299. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  32300. texture.image = images;
  32301. texture.format = texDatas.format;
  32302. texture.needsUpdate = true;
  32303. if ( onLoad ) onLoad( texture );
  32304. }
  32305. }, onProgress, onError );
  32306. }
  32307. if ( Array.isArray( url ) ) {
  32308. for ( let i = 0, il = url.length; i < il; ++ i ) {
  32309. loadTexture( i );
  32310. }
  32311. } else {
  32312. // compressed cubemap texture stored in a single DDS file
  32313. loader.load( url, function ( buffer ) {
  32314. const texDatas = scope.parse( buffer, true );
  32315. if ( texDatas.isCubemap ) {
  32316. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  32317. for ( let f = 0; f < faces; f ++ ) {
  32318. images[ f ] = { mipmaps: [] };
  32319. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  32320. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  32321. images[ f ].format = texDatas.format;
  32322. images[ f ].width = texDatas.width;
  32323. images[ f ].height = texDatas.height;
  32324. }
  32325. }
  32326. texture.image = images;
  32327. } else {
  32328. texture.image.width = texDatas.width;
  32329. texture.image.height = texDatas.height;
  32330. texture.mipmaps = texDatas.mipmaps;
  32331. }
  32332. if ( texDatas.mipmapCount === 1 ) {
  32333. texture.minFilter = LinearFilter;
  32334. }
  32335. texture.format = texDatas.format;
  32336. texture.needsUpdate = true;
  32337. if ( onLoad ) onLoad( texture );
  32338. }, onProgress, onError );
  32339. }
  32340. return texture;
  32341. }
  32342. }
  32343. /**
  32344. * A loader for loading images. The class loads images with the HTML `Image` API.
  32345. *
  32346. * ```js
  32347. * const loader = new THREE.ImageLoader();
  32348. * const image = await loader.loadAsync( 'image.png' );
  32349. * ```
  32350. * Please note that `ImageLoader` has dropped support for progress
  32351. * events in `r84`. For an `ImageLoader` that supports progress events, see
  32352. * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639}.
  32353. *
  32354. * @augments Loader
  32355. */
  32356. class ImageLoader extends Loader {
  32357. /**
  32358. * Constructs a new image loader.
  32359. *
  32360. * @param {LoadingManager} [manager] - The loading manager.
  32361. */
  32362. constructor( manager ) {
  32363. super( manager );
  32364. }
  32365. /**
  32366. * Starts loading from the given URL and passes the loaded image
  32367. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  32368. * directly be used for texture creation. If you do it this way, the texture
  32369. * may pop up in your scene once the respective loading process is finished.
  32370. *
  32371. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32372. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  32373. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32374. * @param {onErrorCallback} onError - Executed when errors occur.
  32375. * @return {Image} The image.
  32376. */
  32377. load( url, onLoad, onProgress, onError ) {
  32378. if ( this.path !== undefined ) url = this.path + url;
  32379. url = this.manager.resolveURL( url );
  32380. const scope = this;
  32381. const cached = Cache.get( url );
  32382. if ( cached !== undefined ) {
  32383. scope.manager.itemStart( url );
  32384. setTimeout( function () {
  32385. if ( onLoad ) onLoad( cached );
  32386. scope.manager.itemEnd( url );
  32387. }, 0 );
  32388. return cached;
  32389. }
  32390. const image = createElementNS( 'img' );
  32391. function onImageLoad() {
  32392. removeEventListeners();
  32393. Cache.add( url, this );
  32394. if ( onLoad ) onLoad( this );
  32395. scope.manager.itemEnd( url );
  32396. }
  32397. function onImageError( event ) {
  32398. removeEventListeners();
  32399. if ( onError ) onError( event );
  32400. scope.manager.itemError( url );
  32401. scope.manager.itemEnd( url );
  32402. }
  32403. function removeEventListeners() {
  32404. image.removeEventListener( 'load', onImageLoad, false );
  32405. image.removeEventListener( 'error', onImageError, false );
  32406. }
  32407. image.addEventListener( 'load', onImageLoad, false );
  32408. image.addEventListener( 'error', onImageError, false );
  32409. if ( url.slice( 0, 5 ) !== 'data:' ) {
  32410. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  32411. }
  32412. scope.manager.itemStart( url );
  32413. image.src = url;
  32414. return image;
  32415. }
  32416. }
  32417. /**
  32418. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  32419. *
  32420. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  32421. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  32422. * like vertical and horizontal cross, column and row layouts are not supported.
  32423. *
  32424. * Note that, by convention, cube maps are specified in a coordinate system
  32425. * in which positive-x is to the right when looking up the positive-z axis --
  32426. * in other words, using a left-handed coordinate system. Since three.js uses
  32427. * a right-handed coordinate system, environment maps used in three.js will
  32428. * have pos-x and neg-x swapped.
  32429. *
  32430. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  32431. * is set to `SRGBColorSpace` by default.
  32432. *
  32433. * ```js
  32434. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  32435. * const cubeTexture = await loader.loadAsync( [
  32436. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  32437. * ] );
  32438. * scene.background = cubeTexture;
  32439. * ```
  32440. *
  32441. * @augments Loader
  32442. */
  32443. class CubeTextureLoader extends Loader {
  32444. /**
  32445. * Constructs a new cube texture loader.
  32446. *
  32447. * @param {LoadingManager} [manager] - The loading manager.
  32448. */
  32449. constructor( manager ) {
  32450. super( manager );
  32451. }
  32452. /**
  32453. * Starts loading from the given URL and pass the fully loaded cube texture
  32454. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  32455. * directly be used for material creation. If you do it this way, the cube texture
  32456. * may pop up in your scene once the respective loading process is finished.
  32457. *
  32458. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  32459. * cube texture. The urls should be specified in the following order: pos-x,
  32460. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  32461. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  32462. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32463. * @param {onErrorCallback} onError - Executed when errors occur.
  32464. * @return {CubeTexture} The cube texture.
  32465. */
  32466. load( urls, onLoad, onProgress, onError ) {
  32467. const texture = new CubeTexture();
  32468. texture.colorSpace = SRGBColorSpace;
  32469. const loader = new ImageLoader( this.manager );
  32470. loader.setCrossOrigin( this.crossOrigin );
  32471. loader.setPath( this.path );
  32472. let loaded = 0;
  32473. function loadTexture( i ) {
  32474. loader.load( urls[ i ], function ( image ) {
  32475. texture.images[ i ] = image;
  32476. loaded ++;
  32477. if ( loaded === 6 ) {
  32478. texture.needsUpdate = true;
  32479. if ( onLoad ) onLoad( texture );
  32480. }
  32481. }, undefined, onError );
  32482. }
  32483. for ( let i = 0; i < urls.length; ++ i ) {
  32484. loadTexture( i );
  32485. }
  32486. return texture;
  32487. }
  32488. }
  32489. /**
  32490. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  32491. * Textures are internally loaded via {@link FileLoader}.
  32492. *
  32493. * Derived classes have to implement the `parse()` method which holds the parsing
  32494. * for the respective format.
  32495. *
  32496. * @abstract
  32497. * @augments Loader
  32498. */
  32499. class DataTextureLoader extends Loader {
  32500. /**
  32501. * Constructs a new data texture loader.
  32502. *
  32503. * @param {LoadingManager} [manager] - The loading manager.
  32504. */
  32505. constructor( manager ) {
  32506. super( manager );
  32507. }
  32508. /**
  32509. * Starts loading from the given URL and passes the loaded data texture
  32510. * to the `onLoad()` callback. The method also returns a new texture object which can
  32511. * directly be used for material creation. If you do it this way, the texture
  32512. * may pop up in your scene once the respective loading process is finished.
  32513. *
  32514. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32515. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  32516. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32517. * @param {onErrorCallback} onError - Executed when errors occur.
  32518. * @return {DataTexture} The data texture.
  32519. */
  32520. load( url, onLoad, onProgress, onError ) {
  32521. const scope = this;
  32522. const texture = new DataTexture();
  32523. const loader = new FileLoader( this.manager );
  32524. loader.setResponseType( 'arraybuffer' );
  32525. loader.setRequestHeader( this.requestHeader );
  32526. loader.setPath( this.path );
  32527. loader.setWithCredentials( scope.withCredentials );
  32528. loader.load( url, function ( buffer ) {
  32529. let texData;
  32530. try {
  32531. texData = scope.parse( buffer );
  32532. } catch ( error ) {
  32533. if ( onError !== undefined ) {
  32534. onError( error );
  32535. } else {
  32536. console.error( error );
  32537. return;
  32538. }
  32539. }
  32540. if ( texData.image !== undefined ) {
  32541. texture.image = texData.image;
  32542. } else if ( texData.data !== undefined ) {
  32543. texture.image.width = texData.width;
  32544. texture.image.height = texData.height;
  32545. texture.image.data = texData.data;
  32546. }
  32547. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  32548. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  32549. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  32550. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  32551. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  32552. if ( texData.colorSpace !== undefined ) {
  32553. texture.colorSpace = texData.colorSpace;
  32554. }
  32555. if ( texData.flipY !== undefined ) {
  32556. texture.flipY = texData.flipY;
  32557. }
  32558. if ( texData.format !== undefined ) {
  32559. texture.format = texData.format;
  32560. }
  32561. if ( texData.type !== undefined ) {
  32562. texture.type = texData.type;
  32563. }
  32564. if ( texData.mipmaps !== undefined ) {
  32565. texture.mipmaps = texData.mipmaps;
  32566. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  32567. }
  32568. if ( texData.mipmapCount === 1 ) {
  32569. texture.minFilter = LinearFilter;
  32570. }
  32571. if ( texData.generateMipmaps !== undefined ) {
  32572. texture.generateMipmaps = texData.generateMipmaps;
  32573. }
  32574. texture.needsUpdate = true;
  32575. if ( onLoad ) onLoad( texture, texData );
  32576. }, onProgress, onError );
  32577. return texture;
  32578. }
  32579. }
  32580. /**
  32581. * Class for loading textures. Images are internally
  32582. * loaded via {@link ImageLoader}.
  32583. *
  32584. * ```js
  32585. * const loader = new THREE.TextureLoader();
  32586. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  32587. *
  32588. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  32589. * ```
  32590. * Please note that `TextureLoader` has dropped support for progress
  32591. * events in `r84`. For a `TextureLoader` that supports progress events, see
  32592. * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145}.
  32593. *
  32594. * @augments Loader
  32595. */
  32596. class TextureLoader extends Loader {
  32597. /**
  32598. * Constructs a new texture loader.
  32599. *
  32600. * @param {LoadingManager} [manager] - The loading manager.
  32601. */
  32602. constructor( manager ) {
  32603. super( manager );
  32604. }
  32605. /**
  32606. * Starts loading from the given URL and pass the fully loaded texture
  32607. * to the `onLoad()` callback. The method also returns a new texture object which can
  32608. * directly be used for material creation. If you do it this way, the texture
  32609. * may pop up in your scene once the respective loading process is finished.
  32610. *
  32611. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32612. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  32613. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32614. * @param {onErrorCallback} onError - Executed when errors occur.
  32615. * @return {Texture} The texture.
  32616. */
  32617. load( url, onLoad, onProgress, onError ) {
  32618. const texture = new Texture();
  32619. const loader = new ImageLoader( this.manager );
  32620. loader.setCrossOrigin( this.crossOrigin );
  32621. loader.setPath( this.path );
  32622. loader.load( url, function ( image ) {
  32623. texture.image = image;
  32624. texture.needsUpdate = true;
  32625. if ( onLoad !== undefined ) {
  32626. onLoad( texture );
  32627. }
  32628. }, onProgress, onError );
  32629. return texture;
  32630. }
  32631. }
  32632. /**
  32633. * Abstract base class for lights - all other light types inherit the
  32634. * properties and methods described here.
  32635. *
  32636. * @abstract
  32637. * @augments Object3D
  32638. */
  32639. class Light extends Object3D {
  32640. /**
  32641. * Constructs a new light.
  32642. *
  32643. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  32644. * @param {number} [intensity=1] - The light's strength/intensity.
  32645. */
  32646. constructor( color, intensity = 1 ) {
  32647. super();
  32648. /**
  32649. * This flag can be used for type testing.
  32650. *
  32651. * @type {boolean}
  32652. * @readonly
  32653. * @default true
  32654. */
  32655. this.isLight = true;
  32656. this.type = 'Light';
  32657. /**
  32658. * The light's color.
  32659. *
  32660. * @type {Color}
  32661. */
  32662. this.color = new Color( color );
  32663. /**
  32664. * The light's intensity.
  32665. *
  32666. * @type {number}
  32667. * @default 1
  32668. */
  32669. this.intensity = intensity;
  32670. }
  32671. /**
  32672. * Frees the GPU-related resources allocated by this instance. Call this
  32673. * method whenever this instance is no longer used in your app.
  32674. */
  32675. dispose() {
  32676. // Empty here in base class; some subclasses override.
  32677. }
  32678. copy( source, recursive ) {
  32679. super.copy( source, recursive );
  32680. this.color.copy( source.color );
  32681. this.intensity = source.intensity;
  32682. return this;
  32683. }
  32684. toJSON( meta ) {
  32685. const data = super.toJSON( meta );
  32686. data.object.color = this.color.getHex();
  32687. data.object.intensity = this.intensity;
  32688. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  32689. if ( this.distance !== undefined ) data.object.distance = this.distance;
  32690. if ( this.angle !== undefined ) data.object.angle = this.angle;
  32691. if ( this.decay !== undefined ) data.object.decay = this.decay;
  32692. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  32693. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  32694. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  32695. return data;
  32696. }
  32697. }
  32698. /**
  32699. * A light source positioned directly above the scene, with color fading from
  32700. * the sky color to the ground color.
  32701. *
  32702. * This light cannot be used to cast shadows.
  32703. *
  32704. * ```js
  32705. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  32706. * scene.add( light );
  32707. * ```
  32708. *
  32709. * @augments Light
  32710. */
  32711. class HemisphereLight extends Light {
  32712. /**
  32713. * Constructs a new hemisphere light.
  32714. *
  32715. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  32716. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  32717. * @param {number} [intensity=1] - The light's strength/intensity.
  32718. */
  32719. constructor( skyColor, groundColor, intensity ) {
  32720. super( skyColor, intensity );
  32721. /**
  32722. * This flag can be used for type testing.
  32723. *
  32724. * @type {boolean}
  32725. * @readonly
  32726. * @default true
  32727. */
  32728. this.isHemisphereLight = true;
  32729. this.type = 'HemisphereLight';
  32730. this.position.copy( Object3D.DEFAULT_UP );
  32731. this.updateMatrix();
  32732. /**
  32733. * The light's ground color.
  32734. *
  32735. * @type {Color}
  32736. */
  32737. this.groundColor = new Color( groundColor );
  32738. }
  32739. copy( source, recursive ) {
  32740. super.copy( source, recursive );
  32741. this.groundColor.copy( source.groundColor );
  32742. return this;
  32743. }
  32744. }
  32745. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  32746. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  32747. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  32748. /**
  32749. * Abstract base class for light shadow classes. These classes
  32750. * represent the shadow configuration for different light types.
  32751. *
  32752. * @abstract
  32753. */
  32754. class LightShadow {
  32755. /**
  32756. * Constructs a new light shadow.
  32757. *
  32758. * @param {Camera} camera - The light's view of the world.
  32759. */
  32760. constructor( camera ) {
  32761. /**
  32762. * The light's view of the world.
  32763. *
  32764. * @type {Camera}
  32765. */
  32766. this.camera = camera;
  32767. /**
  32768. * The intensity of the shadow. The default is `1`.
  32769. * Valid values are in the range `[0, 1]`.
  32770. *
  32771. * @type {number}
  32772. * @default 1
  32773. */
  32774. this.intensity = 1;
  32775. /**
  32776. * Shadow map bias, how much to add or subtract from the normalized depth
  32777. * when deciding whether a surface is in shadow.
  32778. *
  32779. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  32780. * may help reduce artifacts in shadows.
  32781. *
  32782. * @type {number}
  32783. * @default 0
  32784. */
  32785. this.bias = 0;
  32786. /**
  32787. * Defines how much the position used to query the shadow map is offset along
  32788. * the object normal. The default is `0`. Increasing this value can be used to
  32789. * reduce shadow acne especially in large scenes where light shines onto
  32790. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  32791. *
  32792. * @type {number}
  32793. * @default 0
  32794. */
  32795. this.normalBias = 0;
  32796. /**
  32797. * Setting this to values greater than 1 will blur the edges of the shadow.
  32798. * High values will cause unwanted banding effects in the shadows - a greater
  32799. * map size will allow for a higher value to be used here before these effects
  32800. * become visible.
  32801. *
  32802. * The property has no effect when the shadow map type is `PCFSoftShadowMap` and
  32803. * and it is recommended to increase softness by decreasing the shadow map size instead.
  32804. *
  32805. * The property has no effect when the shadow map type is `BasicShadowMap`.
  32806. *
  32807. * @type {number}
  32808. * @default 1
  32809. */
  32810. this.radius = 1;
  32811. /**
  32812. * The amount of samples to use when blurring a VSM shadow map.
  32813. *
  32814. * @type {number}
  32815. * @default 8
  32816. */
  32817. this.blurSamples = 8;
  32818. /**
  32819. * Defines the width and height of the shadow map. Higher values give better quality
  32820. * shadows at the cost of computation time. Values must be powers of two.
  32821. *
  32822. * @type {Vector2}
  32823. * @default (512,512)
  32824. */
  32825. this.mapSize = new Vector2( 512, 512 );
  32826. /**
  32827. * The type of shadow texture. The default is `UnsignedByteType`.
  32828. *
  32829. * @type {number}
  32830. * @default UnsignedByteType
  32831. */
  32832. this.mapType = UnsignedByteType;
  32833. /**
  32834. * The depth map generated using the internal camera; a location beyond a
  32835. * pixel's depth is in shadow. Computed internally during rendering.
  32836. *
  32837. * @type {?RenderTarget}
  32838. * @default null
  32839. */
  32840. this.map = null;
  32841. /**
  32842. * The distribution map generated using the internal camera; an occlusion is
  32843. * calculated based on the distribution of depths. Computed internally during
  32844. * rendering.
  32845. *
  32846. * @type {?RenderTarget}
  32847. * @default null
  32848. */
  32849. this.mapPass = null;
  32850. /**
  32851. * Model to shadow camera space, to compute location and depth in shadow map.
  32852. * This is computed internally during rendering.
  32853. *
  32854. * @type {Matrix4}
  32855. */
  32856. this.matrix = new Matrix4();
  32857. /**
  32858. * Enables automatic updates of the light's shadow. If you do not require dynamic
  32859. * lighting / shadows, you may set this to `false`.
  32860. *
  32861. * @type {boolean}
  32862. * @default true
  32863. */
  32864. this.autoUpdate = true;
  32865. /**
  32866. * When set to `true`, shadow maps will be updated in the next `render` call.
  32867. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  32868. * set this property to `true` and then make a render call to update the light's shadow.
  32869. *
  32870. * @type {boolean}
  32871. * @default false
  32872. */
  32873. this.needsUpdate = false;
  32874. this._frustum = new Frustum();
  32875. this._frameExtents = new Vector2( 1, 1 );
  32876. this._viewportCount = 1;
  32877. this._viewports = [
  32878. new Vector4( 0, 0, 1, 1 )
  32879. ];
  32880. }
  32881. /**
  32882. * Used internally by the renderer to get the number of viewports that need
  32883. * to be rendered for this shadow.
  32884. *
  32885. * @return {number} The viewport count.
  32886. */
  32887. getViewportCount() {
  32888. return this._viewportCount;
  32889. }
  32890. /**
  32891. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  32892. *
  32893. * @return {Frustum} The shadow camera frustum.
  32894. */
  32895. getFrustum() {
  32896. return this._frustum;
  32897. }
  32898. /**
  32899. * Update the matrices for the camera and shadow, used internally by the renderer.
  32900. *
  32901. * @param {Light} light - The light for which the shadow is being rendered.
  32902. */
  32903. updateMatrices( light ) {
  32904. const shadowCamera = this.camera;
  32905. const shadowMatrix = this.matrix;
  32906. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  32907. shadowCamera.position.copy( _lightPositionWorld$1 );
  32908. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  32909. shadowCamera.lookAt( _lookTarget$1 );
  32910. shadowCamera.updateMatrixWorld();
  32911. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  32912. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  32913. shadowMatrix.set(
  32914. 0.5, 0.0, 0.0, 0.5,
  32915. 0.0, 0.5, 0.0, 0.5,
  32916. 0.0, 0.0, 0.5, 0.5,
  32917. 0.0, 0.0, 0.0, 1.0
  32918. );
  32919. shadowMatrix.multiply( _projScreenMatrix$1 );
  32920. }
  32921. /**
  32922. * Returns a viewport definition for the given viewport index.
  32923. *
  32924. * @param {number} viewportIndex - The viewport index.
  32925. * @return {Vector4} The viewport.
  32926. */
  32927. getViewport( viewportIndex ) {
  32928. return this._viewports[ viewportIndex ];
  32929. }
  32930. /**
  32931. * Returns the frame extends.
  32932. *
  32933. * @return {Vector2} The frame extends.
  32934. */
  32935. getFrameExtents() {
  32936. return this._frameExtents;
  32937. }
  32938. /**
  32939. * Frees the GPU-related resources allocated by this instance. Call this
  32940. * method whenever this instance is no longer used in your app.
  32941. */
  32942. dispose() {
  32943. if ( this.map ) {
  32944. this.map.dispose();
  32945. }
  32946. if ( this.mapPass ) {
  32947. this.mapPass.dispose();
  32948. }
  32949. }
  32950. /**
  32951. * Copies the values of the given light shadow instance to this instance.
  32952. *
  32953. * @param {LightShadow} source - The light shadow to copy.
  32954. * @return {LightShadow} A reference to this light shadow instance.
  32955. */
  32956. copy( source ) {
  32957. this.camera = source.camera.clone();
  32958. this.intensity = source.intensity;
  32959. this.bias = source.bias;
  32960. this.radius = source.radius;
  32961. this.autoUpdate = source.autoUpdate;
  32962. this.needsUpdate = source.needsUpdate;
  32963. this.normalBias = source.normalBias;
  32964. this.blurSamples = source.blurSamples;
  32965. this.mapSize.copy( source.mapSize );
  32966. return this;
  32967. }
  32968. /**
  32969. * Returns a new light shadow instance with copied values from this instance.
  32970. *
  32971. * @return {LightShadow} A clone of this instance.
  32972. */
  32973. clone() {
  32974. return new this.constructor().copy( this );
  32975. }
  32976. /**
  32977. * Serializes the light shadow into JSON.
  32978. *
  32979. * @return {Object} A JSON object representing the serialized light shadow.
  32980. * @see {@link ObjectLoader#parse}
  32981. */
  32982. toJSON() {
  32983. const object = {};
  32984. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  32985. if ( this.bias !== 0 ) object.bias = this.bias;
  32986. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  32987. if ( this.radius !== 1 ) object.radius = this.radius;
  32988. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  32989. object.camera = this.camera.toJSON( false ).object;
  32990. delete object.camera.matrix;
  32991. return object;
  32992. }
  32993. }
  32994. /**
  32995. * Represents the shadow configuration of directional lights.
  32996. *
  32997. * @augments LightShadow
  32998. */
  32999. class SpotLightShadow extends LightShadow {
  33000. /**
  33001. * Constructs a new spot light shadow.
  33002. */
  33003. constructor() {
  33004. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  33005. /**
  33006. * This flag can be used for type testing.
  33007. *
  33008. * @type {boolean}
  33009. * @readonly
  33010. * @default true
  33011. */
  33012. this.isSpotLightShadow = true;
  33013. /**
  33014. * Used to focus the shadow camera. The camera's field of view is set as a
  33015. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  33016. *
  33017. * @type {number}
  33018. * @default 1
  33019. */
  33020. this.focus = 1;
  33021. }
  33022. updateMatrices( light ) {
  33023. const camera = this.camera;
  33024. const fov = RAD2DEG * 2 * light.angle * this.focus;
  33025. const aspect = this.mapSize.width / this.mapSize.height;
  33026. const far = light.distance || camera.far;
  33027. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  33028. camera.fov = fov;
  33029. camera.aspect = aspect;
  33030. camera.far = far;
  33031. camera.updateProjectionMatrix();
  33032. }
  33033. super.updateMatrices( light );
  33034. }
  33035. copy( source ) {
  33036. super.copy( source );
  33037. this.focus = source.focus;
  33038. return this;
  33039. }
  33040. }
  33041. /**
  33042. * This light gets emitted from a single point in one direction, along a cone
  33043. * that increases in size the further from the light it gets.
  33044. *
  33045. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  33046. *
  33047. * ```js
  33048. * // white spotlight shining from the side, modulated by a texture
  33049. * const spotLight = new THREE.SpotLight( 0xffffff );
  33050. * spotLight.position.set( 100, 1000, 100 );
  33051. * spotLight.map = new THREE.TextureLoader().load( url );
  33052. *
  33053. * spotLight.castShadow = true;
  33054. * spotLight.shadow.mapSize.width = 1024;
  33055. * spotLight.shadow.mapSize.height = 1024;
  33056. * spotLight.shadow.camera.near = 500;
  33057. * spotLight.shadow.camera.far = 4000;
  33058. * spotLight.shadow.camera.fov = 30;s
  33059. * ```
  33060. *
  33061. * @augments Light
  33062. */
  33063. class SpotLight extends Light {
  33064. /**
  33065. * Constructs a new spot light.
  33066. *
  33067. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33068. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33069. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33070. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33071. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  33072. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33073. */
  33074. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  33075. super( color, intensity );
  33076. /**
  33077. * This flag can be used for type testing.
  33078. *
  33079. * @type {boolean}
  33080. * @readonly
  33081. * @default true
  33082. */
  33083. this.isSpotLight = true;
  33084. this.type = 'SpotLight';
  33085. this.position.copy( Object3D.DEFAULT_UP );
  33086. this.updateMatrix();
  33087. /**
  33088. * The spot light points from its position to the
  33089. * target's position.
  33090. *
  33091. * For the target's position to be changed to anything other
  33092. * than the default, it must be added to the scene.
  33093. *
  33094. * It is also possible to set the target to be another 3D object
  33095. * in the scene. The light will now track the target object.
  33096. *
  33097. * @type {Object3D}
  33098. */
  33099. this.target = new Object3D();
  33100. /**
  33101. * Maximum range of the light. `0` means no limit.
  33102. *
  33103. * @type {number}
  33104. * @default 0
  33105. */
  33106. this.distance = distance;
  33107. /**
  33108. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33109. *
  33110. * @type {number}
  33111. * @default Math.PI/3
  33112. */
  33113. this.angle = angle;
  33114. /**
  33115. * Percent of the spotlight cone that is attenuated due to penumbra.
  33116. * Value range is `[0,1]`.
  33117. *
  33118. * @type {number}
  33119. * @default 0
  33120. */
  33121. this.penumbra = penumbra;
  33122. /**
  33123. * The amount the light dims along the distance of the light. In context of
  33124. * physically-correct rendering the default value should not be changed.
  33125. *
  33126. * @type {number}
  33127. * @default 2
  33128. */
  33129. this.decay = decay;
  33130. /**
  33131. * A texture used to modulate the color of the light. The spot light
  33132. * color is mixed with the RGB value of this texture, with a ratio
  33133. * corresponding to its alpha value. The cookie-like masking effect is
  33134. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  33135. *
  33136. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  33137. *
  33138. * @type {?Texture}
  33139. * @default null
  33140. */
  33141. this.map = null;
  33142. /**
  33143. * This property holds the light's shadow configuration.
  33144. *
  33145. * @type {SpotLightShadow}
  33146. */
  33147. this.shadow = new SpotLightShadow();
  33148. }
  33149. /**
  33150. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33151. * Changing the power will also change the light's intensity.
  33152. *
  33153. * @type {number}
  33154. */
  33155. get power() {
  33156. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33157. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  33158. return this.intensity * Math.PI;
  33159. }
  33160. set power( power ) {
  33161. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33162. this.intensity = power / Math.PI;
  33163. }
  33164. dispose() {
  33165. this.shadow.dispose();
  33166. }
  33167. copy( source, recursive ) {
  33168. super.copy( source, recursive );
  33169. this.distance = source.distance;
  33170. this.angle = source.angle;
  33171. this.penumbra = source.penumbra;
  33172. this.decay = source.decay;
  33173. this.target = source.target.clone();
  33174. this.shadow = source.shadow.clone();
  33175. return this;
  33176. }
  33177. }
  33178. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  33179. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  33180. const _lookTarget = /*@__PURE__*/ new Vector3();
  33181. /**
  33182. * Represents the shadow configuration of point lights.
  33183. *
  33184. * @augments LightShadow
  33185. */
  33186. class PointLightShadow extends LightShadow {
  33187. /**
  33188. * Constructs a new point light shadow.
  33189. */
  33190. constructor() {
  33191. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  33192. /**
  33193. * This flag can be used for type testing.
  33194. *
  33195. * @type {boolean}
  33196. * @readonly
  33197. * @default true
  33198. */
  33199. this.isPointLightShadow = true;
  33200. this._frameExtents = new Vector2( 4, 2 );
  33201. this._viewportCount = 6;
  33202. this._viewports = [
  33203. // These viewports map a cube-map onto a 2D texture with the
  33204. // following orientation:
  33205. //
  33206. // xzXZ
  33207. // y Y
  33208. //
  33209. // X - Positive x direction
  33210. // x - Negative x direction
  33211. // Y - Positive y direction
  33212. // y - Negative y direction
  33213. // Z - Positive z direction
  33214. // z - Negative z direction
  33215. // positive X
  33216. new Vector4( 2, 1, 1, 1 ),
  33217. // negative X
  33218. new Vector4( 0, 1, 1, 1 ),
  33219. // positive Z
  33220. new Vector4( 3, 1, 1, 1 ),
  33221. // negative Z
  33222. new Vector4( 1, 1, 1, 1 ),
  33223. // positive Y
  33224. new Vector4( 3, 0, 1, 1 ),
  33225. // negative Y
  33226. new Vector4( 1, 0, 1, 1 )
  33227. ];
  33228. this._cubeDirections = [
  33229. new Vector3( 1, 0, 0 ), new Vector3( -1, 0, 0 ), new Vector3( 0, 0, 1 ),
  33230. new Vector3( 0, 0, -1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, -1, 0 )
  33231. ];
  33232. this._cubeUps = [
  33233. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  33234. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, -1 )
  33235. ];
  33236. }
  33237. /**
  33238. * Update the matrices for the camera and shadow, used internally by the renderer.
  33239. *
  33240. * @param {Light} light - The light for which the shadow is being rendered.
  33241. * @param {number} [viewportIndex=0] - The viewport index.
  33242. */
  33243. updateMatrices( light, viewportIndex = 0 ) {
  33244. const camera = this.camera;
  33245. const shadowMatrix = this.matrix;
  33246. const far = light.distance || camera.far;
  33247. if ( far !== camera.far ) {
  33248. camera.far = far;
  33249. camera.updateProjectionMatrix();
  33250. }
  33251. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  33252. camera.position.copy( _lightPositionWorld );
  33253. _lookTarget.copy( camera.position );
  33254. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  33255. camera.up.copy( this._cubeUps[ viewportIndex ] );
  33256. camera.lookAt( _lookTarget );
  33257. camera.updateMatrixWorld();
  33258. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  33259. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  33260. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  33261. }
  33262. }
  33263. /**
  33264. * A light that gets emitted from a single point in all directions. A common
  33265. * use case for this is to replicate the light emitted from a bare
  33266. * lightbulb.
  33267. *
  33268. * This light can cast shadows - see the {@link PointLightShadow} for details.
  33269. *
  33270. * ```js
  33271. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  33272. * light.position.set( 50, 50, 50 );
  33273. * scene.add( light );
  33274. * ```
  33275. *
  33276. * @augments Light
  33277. */
  33278. class PointLight extends Light {
  33279. /**
  33280. * Constructs a new point light.
  33281. *
  33282. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33283. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33284. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33285. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33286. */
  33287. constructor( color, intensity, distance = 0, decay = 2 ) {
  33288. super( color, intensity );
  33289. /**
  33290. * This flag can be used for type testing.
  33291. *
  33292. * @type {boolean}
  33293. * @readonly
  33294. * @default true
  33295. */
  33296. this.isPointLight = true;
  33297. this.type = 'PointLight';
  33298. /**
  33299. * When distance is zero, light will attenuate according to inverse-square
  33300. * law to infinite distance. When distance is non-zero, light will attenuate
  33301. * according to inverse-square law until near the distance cutoff, where it
  33302. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  33303. * physically correct.
  33304. *
  33305. * @type {number}
  33306. * @default 0
  33307. */
  33308. this.distance = distance;
  33309. /**
  33310. * The amount the light dims along the distance of the light. In context of
  33311. * physically-correct rendering the default value should not be changed.
  33312. *
  33313. * @type {number}
  33314. * @default 2
  33315. */
  33316. this.decay = decay;
  33317. /**
  33318. * This property holds the light's shadow configuration.
  33319. *
  33320. * @type {PointLightShadow}
  33321. */
  33322. this.shadow = new PointLightShadow();
  33323. }
  33324. /**
  33325. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33326. * Changing the power will also change the light's intensity.
  33327. *
  33328. * @type {number}
  33329. */
  33330. get power() {
  33331. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33332. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  33333. return this.intensity * 4 * Math.PI;
  33334. }
  33335. set power( power ) {
  33336. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33337. this.intensity = power / ( 4 * Math.PI );
  33338. }
  33339. dispose() {
  33340. this.shadow.dispose();
  33341. }
  33342. copy( source, recursive ) {
  33343. super.copy( source, recursive );
  33344. this.distance = source.distance;
  33345. this.decay = source.decay;
  33346. this.shadow = source.shadow.clone();
  33347. return this;
  33348. }
  33349. }
  33350. /**
  33351. * Camera that uses [orthographic projection]{@link https://en.wikipedia.org/wiki/Orthographic_projection}.
  33352. *
  33353. * In this projection mode, an object's size in the rendered image stays
  33354. * constant regardless of its distance from the camera. This can be useful
  33355. * for rendering 2D scenes and UI elements, amongst other things.
  33356. *
  33357. * ```js
  33358. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  33359. * scene.add( camera );
  33360. * ```
  33361. *
  33362. * @augments Camera
  33363. */
  33364. class OrthographicCamera extends Camera {
  33365. /**
  33366. * Constructs a new orthographic camera.
  33367. *
  33368. * @param {number} [left=-1] - The left plane of the camera's frustum.
  33369. * @param {number} [right=1] - The right plane of the camera's frustum.
  33370. * @param {number} [top=1] - The top plane of the camera's frustum.
  33371. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  33372. * @param {number} [near=0.1] - The camera's near plane.
  33373. * @param {number} [far=2000] - The camera's far plane.
  33374. */
  33375. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  33376. super();
  33377. /**
  33378. * This flag can be used for type testing.
  33379. *
  33380. * @type {boolean}
  33381. * @readonly
  33382. * @default true
  33383. */
  33384. this.isOrthographicCamera = true;
  33385. this.type = 'OrthographicCamera';
  33386. /**
  33387. * The zoom factor of the camera.
  33388. *
  33389. * @type {number}
  33390. * @default 1
  33391. */
  33392. this.zoom = 1;
  33393. /**
  33394. * Represents the frustum window specification. This property should not be edited
  33395. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  33396. *
  33397. * @type {?Object}
  33398. * @default null
  33399. */
  33400. this.view = null;
  33401. /**
  33402. * The left plane of the camera's frustum.
  33403. *
  33404. * @type {number}
  33405. * @default -1
  33406. */
  33407. this.left = left;
  33408. /**
  33409. * The right plane of the camera's frustum.
  33410. *
  33411. * @type {number}
  33412. * @default 1
  33413. */
  33414. this.right = right;
  33415. /**
  33416. * The top plane of the camera's frustum.
  33417. *
  33418. * @type {number}
  33419. * @default 1
  33420. */
  33421. this.top = top;
  33422. /**
  33423. * The bottom plane of the camera's frustum.
  33424. *
  33425. * @type {number}
  33426. * @default -1
  33427. */
  33428. this.bottom = bottom;
  33429. /**
  33430. * The camera's near plane. The valid range is greater than `0`
  33431. * and less than the current value of {@link OrthographicCamera#far}.
  33432. *
  33433. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  33434. * valid value for an orthographic camera's near plane.
  33435. *
  33436. * @type {number}
  33437. * @default 0.1
  33438. */
  33439. this.near = near;
  33440. /**
  33441. * The camera's far plane. Must be greater than the
  33442. * current value of {@link OrthographicCamera#near}.
  33443. *
  33444. * @type {number}
  33445. * @default 2000
  33446. */
  33447. this.far = far;
  33448. this.updateProjectionMatrix();
  33449. }
  33450. copy( source, recursive ) {
  33451. super.copy( source, recursive );
  33452. this.left = source.left;
  33453. this.right = source.right;
  33454. this.top = source.top;
  33455. this.bottom = source.bottom;
  33456. this.near = source.near;
  33457. this.far = source.far;
  33458. this.zoom = source.zoom;
  33459. this.view = source.view === null ? null : Object.assign( {}, source.view );
  33460. return this;
  33461. }
  33462. /**
  33463. * Sets an offset in a larger frustum. This is useful for multi-window or
  33464. * multi-monitor/multi-machine setups.
  33465. *
  33466. * @param {number} fullWidth - The full width of multiview setup.
  33467. * @param {number} fullHeight - The full height of multiview setup.
  33468. * @param {number} x - The horizontal offset of the subcamera.
  33469. * @param {number} y - The vertical offset of the subcamera.
  33470. * @param {number} width - The width of subcamera.
  33471. * @param {number} height - The height of subcamera.
  33472. * @see {@link PerspectiveCamera#setViewOffset}
  33473. */
  33474. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  33475. if ( this.view === null ) {
  33476. this.view = {
  33477. enabled: true,
  33478. fullWidth: 1,
  33479. fullHeight: 1,
  33480. offsetX: 0,
  33481. offsetY: 0,
  33482. width: 1,
  33483. height: 1
  33484. };
  33485. }
  33486. this.view.enabled = true;
  33487. this.view.fullWidth = fullWidth;
  33488. this.view.fullHeight = fullHeight;
  33489. this.view.offsetX = x;
  33490. this.view.offsetY = y;
  33491. this.view.width = width;
  33492. this.view.height = height;
  33493. this.updateProjectionMatrix();
  33494. }
  33495. /**
  33496. * Removes the view offset from the projection matrix.
  33497. */
  33498. clearViewOffset() {
  33499. if ( this.view !== null ) {
  33500. this.view.enabled = false;
  33501. }
  33502. this.updateProjectionMatrix();
  33503. }
  33504. /**
  33505. * Updates the camera's projection matrix. Must be called after any change of
  33506. * camera properties.
  33507. */
  33508. updateProjectionMatrix() {
  33509. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  33510. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  33511. const cx = ( this.right + this.left ) / 2;
  33512. const cy = ( this.top + this.bottom ) / 2;
  33513. let left = cx - dx;
  33514. let right = cx + dx;
  33515. let top = cy + dy;
  33516. let bottom = cy - dy;
  33517. if ( this.view !== null && this.view.enabled ) {
  33518. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  33519. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  33520. left += scaleW * this.view.offsetX;
  33521. right = left + scaleW * this.view.width;
  33522. top -= scaleH * this.view.offsetY;
  33523. bottom = top - scaleH * this.view.height;
  33524. }
  33525. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  33526. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  33527. }
  33528. toJSON( meta ) {
  33529. const data = super.toJSON( meta );
  33530. data.object.zoom = this.zoom;
  33531. data.object.left = this.left;
  33532. data.object.right = this.right;
  33533. data.object.top = this.top;
  33534. data.object.bottom = this.bottom;
  33535. data.object.near = this.near;
  33536. data.object.far = this.far;
  33537. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  33538. return data;
  33539. }
  33540. }
  33541. /**
  33542. * Represents the shadow configuration of directional lights.
  33543. *
  33544. * @augments LightShadow
  33545. */
  33546. class DirectionalLightShadow extends LightShadow {
  33547. /**
  33548. * Constructs a new directional light shadow.
  33549. */
  33550. constructor() {
  33551. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  33552. /**
  33553. * This flag can be used for type testing.
  33554. *
  33555. * @type {boolean}
  33556. * @readonly
  33557. * @default true
  33558. */
  33559. this.isDirectionalLightShadow = true;
  33560. }
  33561. }
  33562. /**
  33563. * A light that gets emitted in a specific direction. This light will behave
  33564. * as though it is infinitely far away and the rays produced from it are all
  33565. * parallel. The common use case for this is to simulate daylight; the sun is
  33566. * far enough away that its position can be considered to be infinite, and
  33567. * all light rays coming from it are parallel.
  33568. *
  33569. * A common point of confusion for directional lights is that setting the
  33570. * rotation has no effect. This is because three.js's DirectionalLight is the
  33571. * equivalent to what is often called a 'Target Direct Light' in other
  33572. * applications.
  33573. *
  33574. * This means that its direction is calculated as pointing from the light's
  33575. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  33576. * (as opposed to a 'Free Direct Light' that just has a rotation
  33577. * component).
  33578. *
  33579. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  33580. *
  33581. * ```js
  33582. * // White directional light at half intensity shining from the top.
  33583. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  33584. * scene.add( directionalLight );
  33585. * ```
  33586. *
  33587. * @augments Light
  33588. */
  33589. class DirectionalLight extends Light {
  33590. /**
  33591. * Constructs a new directional light.
  33592. *
  33593. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33594. * @param {number} [intensity=1] - The light's strength/intensity.
  33595. */
  33596. constructor( color, intensity ) {
  33597. super( color, intensity );
  33598. /**
  33599. * This flag can be used for type testing.
  33600. *
  33601. * @type {boolean}
  33602. * @readonly
  33603. * @default true
  33604. */
  33605. this.isDirectionalLight = true;
  33606. this.type = 'DirectionalLight';
  33607. this.position.copy( Object3D.DEFAULT_UP );
  33608. this.updateMatrix();
  33609. /**
  33610. * The directional light points from its position to the
  33611. * target's position.
  33612. *
  33613. * For the target's position to be changed to anything other
  33614. * than the default, it must be added to the scene.
  33615. *
  33616. * It is also possible to set the target to be another 3D object
  33617. * in the scene. The light will now track the target object.
  33618. *
  33619. * @type {Object3D}
  33620. */
  33621. this.target = new Object3D();
  33622. /**
  33623. * This property holds the light's shadow configuration.
  33624. *
  33625. * @type {DirectionalLightShadow}
  33626. */
  33627. this.shadow = new DirectionalLightShadow();
  33628. }
  33629. dispose() {
  33630. this.shadow.dispose();
  33631. }
  33632. copy( source ) {
  33633. super.copy( source );
  33634. this.target = source.target.clone();
  33635. this.shadow = source.shadow.clone();
  33636. return this;
  33637. }
  33638. }
  33639. /**
  33640. * This light globally illuminates all objects in the scene equally.
  33641. *
  33642. * It cannot be used to cast shadows as it does not have a direction.
  33643. *
  33644. * ```js
  33645. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  33646. * scene.add( light );
  33647. * ```
  33648. *
  33649. * @augments Light
  33650. */
  33651. class AmbientLight extends Light {
  33652. /**
  33653. * Constructs a new ambient light.
  33654. *
  33655. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33656. * @param {number} [intensity=1] - The light's strength/intensity.
  33657. */
  33658. constructor( color, intensity ) {
  33659. super( color, intensity );
  33660. /**
  33661. * This flag can be used for type testing.
  33662. *
  33663. * @type {boolean}
  33664. * @readonly
  33665. * @default true
  33666. */
  33667. this.isAmbientLight = true;
  33668. this.type = 'AmbientLight';
  33669. }
  33670. }
  33671. /**
  33672. * This class emits light uniformly across the face a rectangular plane.
  33673. * This light type can be used to simulate light sources such as bright
  33674. * windows or strip lighting.
  33675. *
  33676. * Important Notes:
  33677. *
  33678. * - There is no shadow support.
  33679. * - Only PBR materials are supported.
  33680. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  33681. * into your app and init the uniforms/textures.
  33682. *
  33683. * ```js
  33684. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  33685. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  33686. *
  33687. * const intensity = 1; const width = 10; const height = 10;
  33688. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  33689. * rectLight.position.set( 5, 5, 0 );
  33690. * rectLight.lookAt( 0, 0, 0 );
  33691. * scene.add( rectLight )
  33692. * ```
  33693. *
  33694. * @augments Light
  33695. */
  33696. class RectAreaLight extends Light {
  33697. /**
  33698. * Constructs a new area light.
  33699. *
  33700. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33701. * @param {number} [intensity=1] - The light's strength/intensity.
  33702. * @param {number} [width=10] - The width of the light.
  33703. * @param {number} [height=10] - The height of the light.
  33704. */
  33705. constructor( color, intensity, width = 10, height = 10 ) {
  33706. super( color, intensity );
  33707. /**
  33708. * This flag can be used for type testing.
  33709. *
  33710. * @type {boolean}
  33711. * @readonly
  33712. * @default true
  33713. */
  33714. this.isRectAreaLight = true;
  33715. this.type = 'RectAreaLight';
  33716. /**
  33717. * The width of the light.
  33718. *
  33719. * @type {number}
  33720. * @default 10
  33721. */
  33722. this.width = width;
  33723. /**
  33724. * The height of the light.
  33725. *
  33726. * @type {number}
  33727. * @default 10
  33728. */
  33729. this.height = height;
  33730. }
  33731. /**
  33732. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33733. * Changing the power will also change the light's intensity.
  33734. *
  33735. * @type {number}
  33736. */
  33737. get power() {
  33738. // compute the light's luminous power (in lumens) from its intensity (in nits)
  33739. return this.intensity * this.width * this.height * Math.PI;
  33740. }
  33741. set power( power ) {
  33742. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  33743. this.intensity = power / ( this.width * this.height * Math.PI );
  33744. }
  33745. copy( source ) {
  33746. super.copy( source );
  33747. this.width = source.width;
  33748. this.height = source.height;
  33749. return this;
  33750. }
  33751. toJSON( meta ) {
  33752. const data = super.toJSON( meta );
  33753. data.object.width = this.width;
  33754. data.object.height = this.height;
  33755. return data;
  33756. }
  33757. }
  33758. /**
  33759. * Represents a third-order spherical harmonics (SH). Light probes use this class
  33760. * to encode lighting information.
  33761. *
  33762. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  33763. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  33764. */
  33765. class SphericalHarmonics3 {
  33766. /**
  33767. * Constructs a new spherical harmonics.
  33768. */
  33769. constructor() {
  33770. /**
  33771. * This flag can be used for type testing.
  33772. *
  33773. * @type {boolean}
  33774. * @readonly
  33775. * @default true
  33776. */
  33777. this.isSphericalHarmonics3 = true;
  33778. /**
  33779. * An array holding the (9) SH coefficients.
  33780. *
  33781. * @type {Array<Vector3>}
  33782. */
  33783. this.coefficients = [];
  33784. for ( let i = 0; i < 9; i ++ ) {
  33785. this.coefficients.push( new Vector3() );
  33786. }
  33787. }
  33788. /**
  33789. * Sets the given SH coefficients to this instance by copying
  33790. * the values.
  33791. *
  33792. * @param {Array<Vector3>} coefficients - The SH coefficients.
  33793. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33794. */
  33795. set( coefficients ) {
  33796. for ( let i = 0; i < 9; i ++ ) {
  33797. this.coefficients[ i ].copy( coefficients[ i ] );
  33798. }
  33799. return this;
  33800. }
  33801. /**
  33802. * Sets all SH coefficients to `0`.
  33803. *
  33804. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33805. */
  33806. zero() {
  33807. for ( let i = 0; i < 9; i ++ ) {
  33808. this.coefficients[ i ].set( 0, 0, 0 );
  33809. }
  33810. return this;
  33811. }
  33812. /**
  33813. * Returns the radiance in the direction of the given normal.
  33814. *
  33815. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  33816. * @param {Vector3} target - The target vector that is used to store the method's result.
  33817. * @return {Vector3} The radiance.
  33818. */
  33819. getAt( normal, target ) {
  33820. // normal is assumed to be unit length
  33821. const x = normal.x, y = normal.y, z = normal.z;
  33822. const coeff = this.coefficients;
  33823. // band 0
  33824. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  33825. // band 1
  33826. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  33827. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  33828. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  33829. // band 2
  33830. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  33831. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  33832. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  33833. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  33834. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  33835. return target;
  33836. }
  33837. /**
  33838. * Returns the irradiance (radiance convolved with cosine lobe) in the
  33839. * direction of the given normal.
  33840. *
  33841. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  33842. * @param {Vector3} target - The target vector that is used to store the method's result.
  33843. * @return {Vector3} The irradiance.
  33844. */
  33845. getIrradianceAt( normal, target ) {
  33846. // normal is assumed to be unit length
  33847. const x = normal.x, y = normal.y, z = normal.z;
  33848. const coeff = this.coefficients;
  33849. // band 0
  33850. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  33851. // band 1
  33852. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  33853. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  33854. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  33855. // band 2
  33856. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  33857. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  33858. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  33859. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  33860. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  33861. return target;
  33862. }
  33863. /**
  33864. * Adds the given SH to this instance.
  33865. *
  33866. * @param {SphericalHarmonics3} sh - The SH to add.
  33867. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33868. */
  33869. add( sh ) {
  33870. for ( let i = 0; i < 9; i ++ ) {
  33871. this.coefficients[ i ].add( sh.coefficients[ i ] );
  33872. }
  33873. return this;
  33874. }
  33875. /**
  33876. * A convenience method for performing {@link SphericalHarmonics3#add} and
  33877. * {@link SphericalHarmonics3#scale} at once.
  33878. *
  33879. * @param {SphericalHarmonics3} sh - The SH to add.
  33880. * @param {number} s - The scale factor.
  33881. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33882. */
  33883. addScaledSH( sh, s ) {
  33884. for ( let i = 0; i < 9; i ++ ) {
  33885. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  33886. }
  33887. return this;
  33888. }
  33889. /**
  33890. * Scales this SH by the given scale factor.
  33891. *
  33892. * @param {number} s - The scale factor.
  33893. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33894. */
  33895. scale( s ) {
  33896. for ( let i = 0; i < 9; i ++ ) {
  33897. this.coefficients[ i ].multiplyScalar( s );
  33898. }
  33899. return this;
  33900. }
  33901. /**
  33902. * Linear interpolates between the given SH and this instance by the given
  33903. * alpha factor.
  33904. *
  33905. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  33906. * @param {number} alpha - The alpha factor.
  33907. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33908. */
  33909. lerp( sh, alpha ) {
  33910. for ( let i = 0; i < 9; i ++ ) {
  33911. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  33912. }
  33913. return this;
  33914. }
  33915. /**
  33916. * Returns `true` if this spherical harmonics is equal with the given one.
  33917. *
  33918. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  33919. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  33920. */
  33921. equals( sh ) {
  33922. for ( let i = 0; i < 9; i ++ ) {
  33923. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  33924. return false;
  33925. }
  33926. }
  33927. return true;
  33928. }
  33929. /**
  33930. * Copies the values of the given spherical harmonics to this instance.
  33931. *
  33932. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  33933. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33934. */
  33935. copy( sh ) {
  33936. return this.set( sh.coefficients );
  33937. }
  33938. /**
  33939. * Returns a new spherical harmonics with copied values from this instance.
  33940. *
  33941. * @return {SphericalHarmonics3} A clone of this instance.
  33942. */
  33943. clone() {
  33944. return new this.constructor().copy( this );
  33945. }
  33946. /**
  33947. * Sets the SH coefficients of this instance from the given array.
  33948. *
  33949. * @param {Array<number>} array - An array holding the SH coefficients.
  33950. * @param {number} [offset=0] - The array offset where to start copying.
  33951. * @return {SphericalHarmonics3} A clone of this instance.
  33952. */
  33953. fromArray( array, offset = 0 ) {
  33954. const coefficients = this.coefficients;
  33955. for ( let i = 0; i < 9; i ++ ) {
  33956. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  33957. }
  33958. return this;
  33959. }
  33960. /**
  33961. * Returns an array with the SH coefficients, or copies them into the provided
  33962. * array. The coefficients are represented as numbers.
  33963. *
  33964. * @param {Array<number>} [array=[]] - The target array.
  33965. * @param {number} [offset=0] - The array offset where to start copying.
  33966. * @return {Array<number>} An array with flat SH coefficients.
  33967. */
  33968. toArray( array = [], offset = 0 ) {
  33969. const coefficients = this.coefficients;
  33970. for ( let i = 0; i < 9; i ++ ) {
  33971. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  33972. }
  33973. return array;
  33974. }
  33975. /**
  33976. * Computes the SH basis for the given normal vector.
  33977. *
  33978. * @param {Vector3} normal - The normal.
  33979. * @param {Array<number>} shBasis - The target array holding the SH basis.
  33980. */
  33981. static getBasisAt( normal, shBasis ) {
  33982. // normal is assumed to be unit length
  33983. const x = normal.x, y = normal.y, z = normal.z;
  33984. // band 0
  33985. shBasis[ 0 ] = 0.282095;
  33986. // band 1
  33987. shBasis[ 1 ] = 0.488603 * y;
  33988. shBasis[ 2 ] = 0.488603 * z;
  33989. shBasis[ 3 ] = 0.488603 * x;
  33990. // band 2
  33991. shBasis[ 4 ] = 1.092548 * x * y;
  33992. shBasis[ 5 ] = 1.092548 * y * z;
  33993. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  33994. shBasis[ 7 ] = 1.092548 * x * z;
  33995. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  33996. }
  33997. }
  33998. /**
  33999. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  34000. * classical light sources (e.g. directional, point or spot lights), light
  34001. * probes do not emit light. Instead they store information about light
  34002. * passing through 3D space. During rendering, the light that hits a 3D
  34003. * object is approximated by using the data from the light probe.
  34004. *
  34005. * Light probes are usually created from (radiance) environment maps. The
  34006. * class {@link LightProbeGenerator} can be used to create light probes from
  34007. * cube textures or render targets. However, light estimation data could also
  34008. * be provided in other forms e.g. by WebXR. This enables the rendering of
  34009. * augmented reality content that reacts to real world lighting.
  34010. *
  34011. * The current probe implementation in three.js supports so-called diffuse
  34012. * light probes. This type of light probe is functionally equivalent to an
  34013. * irradiance environment map.
  34014. *
  34015. * @augments Light
  34016. */
  34017. class LightProbe extends Light {
  34018. /**
  34019. * Constructs a new light probe.
  34020. *
  34021. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  34022. * @param {number} [intensity=1] - The light's strength/intensity.
  34023. */
  34024. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  34025. super( undefined, intensity );
  34026. /**
  34027. * This flag can be used for type testing.
  34028. *
  34029. * @type {boolean}
  34030. * @readonly
  34031. * @default true
  34032. */
  34033. this.isLightProbe = true;
  34034. /**
  34035. * A light probe uses spherical harmonics to encode lighting information.
  34036. *
  34037. * @type {SphericalHarmonics3}
  34038. */
  34039. this.sh = sh;
  34040. }
  34041. copy( source ) {
  34042. super.copy( source );
  34043. this.sh.copy( source.sh );
  34044. return this;
  34045. }
  34046. /**
  34047. * Deserializes the light prove from the given JSON.
  34048. *
  34049. * @param {Object} json - The JSON holding the serialized light probe.
  34050. * @return {LightProbe} A reference to this light probe.
  34051. */
  34052. fromJSON( json ) {
  34053. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  34054. this.sh.fromArray( json.sh );
  34055. return this;
  34056. }
  34057. toJSON( meta ) {
  34058. const data = super.toJSON( meta );
  34059. data.object.sh = this.sh.toArray();
  34060. return data;
  34061. }
  34062. }
  34063. /**
  34064. * Class for loading geometries. The files are internally
  34065. * loaded via {@link FileLoader}.
  34066. *
  34067. * ```js
  34068. * const loader = new THREE.MaterialLoader();
  34069. * const material = await loader.loadAsync( 'material.json' );
  34070. * ```
  34071. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  34072. *
  34073. * @augments Loader
  34074. */
  34075. class MaterialLoader extends Loader {
  34076. /**
  34077. * Constructs a new material loader.
  34078. *
  34079. * @param {LoadingManager} [manager] - The loading manager.
  34080. */
  34081. constructor( manager ) {
  34082. super( manager );
  34083. /**
  34084. * A dictionary holding textures used by the material.
  34085. *
  34086. * @type {Object<string,Texture>}
  34087. */
  34088. this.textures = {};
  34089. }
  34090. /**
  34091. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  34092. *
  34093. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34094. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  34095. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34096. * @param {onErrorCallback} onError - Executed when errors occur.
  34097. */
  34098. load( url, onLoad, onProgress, onError ) {
  34099. const scope = this;
  34100. const loader = new FileLoader( scope.manager );
  34101. loader.setPath( scope.path );
  34102. loader.setRequestHeader( scope.requestHeader );
  34103. loader.setWithCredentials( scope.withCredentials );
  34104. loader.load( url, function ( text ) {
  34105. try {
  34106. onLoad( scope.parse( JSON.parse( text ) ) );
  34107. } catch ( e ) {
  34108. if ( onError ) {
  34109. onError( e );
  34110. } else {
  34111. console.error( e );
  34112. }
  34113. scope.manager.itemError( url );
  34114. }
  34115. }, onProgress, onError );
  34116. }
  34117. /**
  34118. * Parses the given JSON object and returns a material.
  34119. *
  34120. * @param {Object} json - The serialized material.
  34121. * @return {Material} The parsed material.
  34122. */
  34123. parse( json ) {
  34124. const textures = this.textures;
  34125. function getTexture( name ) {
  34126. if ( textures[ name ] === undefined ) {
  34127. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  34128. }
  34129. return textures[ name ];
  34130. }
  34131. const material = this.createMaterialFromType( json.type );
  34132. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  34133. if ( json.name !== undefined ) material.name = json.name;
  34134. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  34135. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  34136. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  34137. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  34138. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  34139. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  34140. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  34141. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  34142. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  34143. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  34144. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  34145. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  34146. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  34147. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  34148. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  34149. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  34150. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  34151. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  34152. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  34153. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  34154. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  34155. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  34156. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  34157. if ( json.fog !== undefined ) material.fog = json.fog;
  34158. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  34159. if ( json.blending !== undefined ) material.blending = json.blending;
  34160. if ( json.combine !== undefined ) material.combine = json.combine;
  34161. if ( json.side !== undefined ) material.side = json.side;
  34162. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  34163. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  34164. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  34165. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  34166. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  34167. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  34168. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  34169. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  34170. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  34171. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  34172. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  34173. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  34174. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  34175. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  34176. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  34177. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  34178. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  34179. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  34180. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  34181. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  34182. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  34183. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  34184. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  34185. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  34186. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  34187. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  34188. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  34189. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  34190. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  34191. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  34192. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  34193. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  34194. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  34195. if ( json.scale !== undefined ) material.scale = json.scale;
  34196. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  34197. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  34198. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  34199. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  34200. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  34201. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  34202. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  34203. if ( json.visible !== undefined ) material.visible = json.visible;
  34204. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  34205. if ( json.userData !== undefined ) material.userData = json.userData;
  34206. if ( json.vertexColors !== undefined ) {
  34207. if ( typeof json.vertexColors === 'number' ) {
  34208. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  34209. } else {
  34210. material.vertexColors = json.vertexColors;
  34211. }
  34212. }
  34213. // Shader Material
  34214. if ( json.uniforms !== undefined ) {
  34215. for ( const name in json.uniforms ) {
  34216. const uniform = json.uniforms[ name ];
  34217. material.uniforms[ name ] = {};
  34218. switch ( uniform.type ) {
  34219. case 't':
  34220. material.uniforms[ name ].value = getTexture( uniform.value );
  34221. break;
  34222. case 'c':
  34223. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  34224. break;
  34225. case 'v2':
  34226. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  34227. break;
  34228. case 'v3':
  34229. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  34230. break;
  34231. case 'v4':
  34232. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  34233. break;
  34234. case 'm3':
  34235. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  34236. break;
  34237. case 'm4':
  34238. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  34239. break;
  34240. default:
  34241. material.uniforms[ name ].value = uniform.value;
  34242. }
  34243. }
  34244. }
  34245. if ( json.defines !== undefined ) material.defines = json.defines;
  34246. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  34247. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  34248. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  34249. if ( json.extensions !== undefined ) {
  34250. for ( const key in json.extensions ) {
  34251. material.extensions[ key ] = json.extensions[ key ];
  34252. }
  34253. }
  34254. if ( json.lights !== undefined ) material.lights = json.lights;
  34255. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  34256. // for PointsMaterial
  34257. if ( json.size !== undefined ) material.size = json.size;
  34258. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  34259. // maps
  34260. if ( json.map !== undefined ) material.map = getTexture( json.map );
  34261. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  34262. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  34263. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  34264. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  34265. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  34266. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  34267. if ( json.normalScale !== undefined ) {
  34268. let normalScale = json.normalScale;
  34269. if ( Array.isArray( normalScale ) === false ) {
  34270. // Blender exporter used to export a scalar. See #7459
  34271. normalScale = [ normalScale, normalScale ];
  34272. }
  34273. material.normalScale = new Vector2().fromArray( normalScale );
  34274. }
  34275. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  34276. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  34277. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  34278. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  34279. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  34280. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  34281. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  34282. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  34283. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  34284. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  34285. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  34286. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  34287. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  34288. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  34289. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  34290. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  34291. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  34292. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  34293. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  34294. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  34295. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  34296. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  34297. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  34298. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  34299. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  34300. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  34301. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  34302. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  34303. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  34304. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  34305. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  34306. return material;
  34307. }
  34308. /**
  34309. * Textures are not embedded in the material JSON so they have
  34310. * to be injected before the loading process starts.
  34311. *
  34312. * @param {Object} value - A dictionary holding textures for material properties.
  34313. * @return {MaterialLoader} A reference to this material loader.
  34314. */
  34315. setTextures( value ) {
  34316. this.textures = value;
  34317. return this;
  34318. }
  34319. /**
  34320. * Creates a material for the given type.
  34321. *
  34322. * @param {string} type - The material type.
  34323. * @return {Material} The new material.
  34324. */
  34325. createMaterialFromType( type ) {
  34326. return MaterialLoader.createMaterialFromType( type );
  34327. }
  34328. /**
  34329. * Creates a material for the given type.
  34330. *
  34331. * @static
  34332. * @param {string} type - The material type.
  34333. * @return {Material} The new material.
  34334. */
  34335. static createMaterialFromType( type ) {
  34336. const materialLib = {
  34337. ShadowMaterial,
  34338. SpriteMaterial,
  34339. RawShaderMaterial,
  34340. ShaderMaterial,
  34341. PointsMaterial,
  34342. MeshPhysicalMaterial,
  34343. MeshStandardMaterial,
  34344. MeshPhongMaterial,
  34345. MeshToonMaterial,
  34346. MeshNormalMaterial,
  34347. MeshLambertMaterial,
  34348. MeshDepthMaterial,
  34349. MeshDistanceMaterial,
  34350. MeshBasicMaterial,
  34351. MeshMatcapMaterial,
  34352. LineDashedMaterial,
  34353. LineBasicMaterial,
  34354. Material
  34355. };
  34356. return new materialLib[ type ]();
  34357. }
  34358. }
  34359. /**
  34360. * A class with loader utility functions.
  34361. */
  34362. class LoaderUtils {
  34363. /**
  34364. * Extracts the base URL from the given URL.
  34365. *
  34366. * @param {string} url -The URL to extract the base URL from.
  34367. * @return {string} The extracted base URL.
  34368. */
  34369. static extractUrlBase( url ) {
  34370. const index = url.lastIndexOf( '/' );
  34371. if ( index === -1 ) return './';
  34372. return url.slice( 0, index + 1 );
  34373. }
  34374. /**
  34375. * Resolves relative URLs against the given path. Absolute paths, data urls,
  34376. * and blob URLs will be returned as is. Invalid URLs will return an empty
  34377. * string.
  34378. *
  34379. * @param {string} url -The URL to resolve.
  34380. * @param {string} path - The base path for relative URLs to be resolved against.
  34381. * @return {string} The resolved URL.
  34382. */
  34383. static resolveURL( url, path ) {
  34384. // Invalid URL
  34385. if ( typeof url !== 'string' || url === '' ) return '';
  34386. // Host Relative URL
  34387. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  34388. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  34389. }
  34390. // Absolute URL http://,https://,//
  34391. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  34392. // Data URI
  34393. if ( /^data:.*,.*$/i.test( url ) ) return url;
  34394. // Blob URL
  34395. if ( /^blob:.*$/i.test( url ) ) return url;
  34396. // Relative URL
  34397. return path + url;
  34398. }
  34399. }
  34400. /**
  34401. * An instanced version of a geometry.
  34402. */
  34403. class InstancedBufferGeometry extends BufferGeometry {
  34404. /**
  34405. * Constructs a new instanced buffer geometry.
  34406. */
  34407. constructor() {
  34408. super();
  34409. /**
  34410. * This flag can be used for type testing.
  34411. *
  34412. * @type {boolean}
  34413. * @readonly
  34414. * @default true
  34415. */
  34416. this.isInstancedBufferGeometry = true;
  34417. this.type = 'InstancedBufferGeometry';
  34418. /**
  34419. * The instance count.
  34420. *
  34421. * @type {number}
  34422. * @default Infinity
  34423. */
  34424. this.instanceCount = Infinity;
  34425. }
  34426. copy( source ) {
  34427. super.copy( source );
  34428. this.instanceCount = source.instanceCount;
  34429. return this;
  34430. }
  34431. toJSON() {
  34432. const data = super.toJSON();
  34433. data.instanceCount = this.instanceCount;
  34434. data.isInstancedBufferGeometry = true;
  34435. return data;
  34436. }
  34437. }
  34438. /**
  34439. * Class for loading geometries. The files are internally
  34440. * loaded via {@link FileLoader}.
  34441. *
  34442. * ```js
  34443. * const loader = new THREE.BufferGeometryLoader();
  34444. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  34445. *
  34446. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  34447. * const object = new THREE.Mesh( geometry, material );
  34448. * scene.add( object );
  34449. * ```
  34450. *
  34451. * @augments Loader
  34452. */
  34453. class BufferGeometryLoader extends Loader {
  34454. /**
  34455. * Constructs a new geometry loader.
  34456. *
  34457. * @param {LoadingManager} [manager] - The loading manager.
  34458. */
  34459. constructor( manager ) {
  34460. super( manager );
  34461. }
  34462. /**
  34463. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  34464. *
  34465. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34466. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  34467. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34468. * @param {onErrorCallback} onError - Executed when errors occur.
  34469. */
  34470. load( url, onLoad, onProgress, onError ) {
  34471. const scope = this;
  34472. const loader = new FileLoader( scope.manager );
  34473. loader.setPath( scope.path );
  34474. loader.setRequestHeader( scope.requestHeader );
  34475. loader.setWithCredentials( scope.withCredentials );
  34476. loader.load( url, function ( text ) {
  34477. try {
  34478. onLoad( scope.parse( JSON.parse( text ) ) );
  34479. } catch ( e ) {
  34480. if ( onError ) {
  34481. onError( e );
  34482. } else {
  34483. console.error( e );
  34484. }
  34485. scope.manager.itemError( url );
  34486. }
  34487. }, onProgress, onError );
  34488. }
  34489. /**
  34490. * Parses the given JSON object and returns a geometry.
  34491. *
  34492. * @param {Object} json - The serialized geometry.
  34493. * @return {BufferGeometry} The parsed geometry.
  34494. */
  34495. parse( json ) {
  34496. const interleavedBufferMap = {};
  34497. const arrayBufferMap = {};
  34498. function getInterleavedBuffer( json, uuid ) {
  34499. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  34500. const interleavedBuffers = json.interleavedBuffers;
  34501. const interleavedBuffer = interleavedBuffers[ uuid ];
  34502. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  34503. const array = getTypedArray( interleavedBuffer.type, buffer );
  34504. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  34505. ib.uuid = interleavedBuffer.uuid;
  34506. interleavedBufferMap[ uuid ] = ib;
  34507. return ib;
  34508. }
  34509. function getArrayBuffer( json, uuid ) {
  34510. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  34511. const arrayBuffers = json.arrayBuffers;
  34512. const arrayBuffer = arrayBuffers[ uuid ];
  34513. const ab = new Uint32Array( arrayBuffer ).buffer;
  34514. arrayBufferMap[ uuid ] = ab;
  34515. return ab;
  34516. }
  34517. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  34518. const index = json.data.index;
  34519. if ( index !== undefined ) {
  34520. const typedArray = getTypedArray( index.type, index.array );
  34521. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  34522. }
  34523. const attributes = json.data.attributes;
  34524. for ( const key in attributes ) {
  34525. const attribute = attributes[ key ];
  34526. let bufferAttribute;
  34527. if ( attribute.isInterleavedBufferAttribute ) {
  34528. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34529. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34530. } else {
  34531. const typedArray = getTypedArray( attribute.type, attribute.array );
  34532. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  34533. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  34534. }
  34535. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  34536. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  34537. geometry.setAttribute( key, bufferAttribute );
  34538. }
  34539. const morphAttributes = json.data.morphAttributes;
  34540. if ( morphAttributes ) {
  34541. for ( const key in morphAttributes ) {
  34542. const attributeArray = morphAttributes[ key ];
  34543. const array = [];
  34544. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  34545. const attribute = attributeArray[ i ];
  34546. let bufferAttribute;
  34547. if ( attribute.isInterleavedBufferAttribute ) {
  34548. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34549. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34550. } else {
  34551. const typedArray = getTypedArray( attribute.type, attribute.array );
  34552. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  34553. }
  34554. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  34555. array.push( bufferAttribute );
  34556. }
  34557. geometry.morphAttributes[ key ] = array;
  34558. }
  34559. }
  34560. const morphTargetsRelative = json.data.morphTargetsRelative;
  34561. if ( morphTargetsRelative ) {
  34562. geometry.morphTargetsRelative = true;
  34563. }
  34564. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  34565. if ( groups !== undefined ) {
  34566. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  34567. const group = groups[ i ];
  34568. geometry.addGroup( group.start, group.count, group.materialIndex );
  34569. }
  34570. }
  34571. const boundingSphere = json.data.boundingSphere;
  34572. if ( boundingSphere !== undefined ) {
  34573. const center = new Vector3();
  34574. if ( boundingSphere.center !== undefined ) {
  34575. center.fromArray( boundingSphere.center );
  34576. }
  34577. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  34578. }
  34579. if ( json.name ) geometry.name = json.name;
  34580. if ( json.userData ) geometry.userData = json.userData;
  34581. return geometry;
  34582. }
  34583. }
  34584. /**
  34585. * 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}.
  34586. * The files are internally loaded via {@link FileLoader}.
  34587. *
  34588. * ```js
  34589. * const loader = new THREE.ObjectLoader();
  34590. * const obj = await loader.loadAsync( 'models/json/example.json' );
  34591. * scene.add( obj );
  34592. *
  34593. * // Alternatively, to parse a previously loaded JSON structure
  34594. * const object = await loader.parseAsync( a_json_object );
  34595. * scene.add( object );
  34596. * ```
  34597. *
  34598. * @augments Loader
  34599. */
  34600. class ObjectLoader extends Loader {
  34601. /**
  34602. * Constructs a new object loader.
  34603. *
  34604. * @param {LoadingManager} [manager] - The loading manager.
  34605. */
  34606. constructor( manager ) {
  34607. super( manager );
  34608. }
  34609. /**
  34610. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  34611. *
  34612. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34613. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  34614. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34615. * @param {onErrorCallback} onError - Executed when errors occur.
  34616. */
  34617. load( url, onLoad, onProgress, onError ) {
  34618. const scope = this;
  34619. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  34620. this.resourcePath = this.resourcePath || path;
  34621. const loader = new FileLoader( this.manager );
  34622. loader.setPath( this.path );
  34623. loader.setRequestHeader( this.requestHeader );
  34624. loader.setWithCredentials( this.withCredentials );
  34625. loader.load( url, function ( text ) {
  34626. let json = null;
  34627. try {
  34628. json = JSON.parse( text );
  34629. } catch ( error ) {
  34630. if ( onError !== undefined ) onError( error );
  34631. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  34632. return;
  34633. }
  34634. const metadata = json.metadata;
  34635. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  34636. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  34637. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  34638. return;
  34639. }
  34640. scope.parse( json, onLoad );
  34641. }, onProgress, onError );
  34642. }
  34643. /**
  34644. * Async version of {@link ObjectLoader#load}.
  34645. *
  34646. * @async
  34647. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34648. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34649. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  34650. */
  34651. async loadAsync( url, onProgress ) {
  34652. const scope = this;
  34653. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  34654. this.resourcePath = this.resourcePath || path;
  34655. const loader = new FileLoader( this.manager );
  34656. loader.setPath( this.path );
  34657. loader.setRequestHeader( this.requestHeader );
  34658. loader.setWithCredentials( this.withCredentials );
  34659. const text = await loader.loadAsync( url, onProgress );
  34660. const json = JSON.parse( text );
  34661. const metadata = json.metadata;
  34662. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  34663. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  34664. }
  34665. return await scope.parseAsync( json );
  34666. }
  34667. /**
  34668. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  34669. * but can also be used directly to parse a previously loaded JSON structure.
  34670. *
  34671. * @param {Object} json - The serialized 3D object.
  34672. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  34673. * @return {Object3D} The parsed 3D object.
  34674. */
  34675. parse( json, onLoad ) {
  34676. const animations = this.parseAnimations( json.animations );
  34677. const shapes = this.parseShapes( json.shapes );
  34678. const geometries = this.parseGeometries( json.geometries, shapes );
  34679. const images = this.parseImages( json.images, function () {
  34680. if ( onLoad !== undefined ) onLoad( object );
  34681. } );
  34682. const textures = this.parseTextures( json.textures, images );
  34683. const materials = this.parseMaterials( json.materials, textures );
  34684. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  34685. const skeletons = this.parseSkeletons( json.skeletons, object );
  34686. this.bindSkeletons( object, skeletons );
  34687. this.bindLightTargets( object );
  34688. //
  34689. if ( onLoad !== undefined ) {
  34690. let hasImages = false;
  34691. for ( const uuid in images ) {
  34692. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  34693. hasImages = true;
  34694. break;
  34695. }
  34696. }
  34697. if ( hasImages === false ) onLoad( object );
  34698. }
  34699. return object;
  34700. }
  34701. /**
  34702. * Async version of {@link ObjectLoader#parse}.
  34703. *
  34704. * @param {Object} json - The serialized 3D object.
  34705. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  34706. */
  34707. async parseAsync( json ) {
  34708. const animations = this.parseAnimations( json.animations );
  34709. const shapes = this.parseShapes( json.shapes );
  34710. const geometries = this.parseGeometries( json.geometries, shapes );
  34711. const images = await this.parseImagesAsync( json.images );
  34712. const textures = this.parseTextures( json.textures, images );
  34713. const materials = this.parseMaterials( json.materials, textures );
  34714. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  34715. const skeletons = this.parseSkeletons( json.skeletons, object );
  34716. this.bindSkeletons( object, skeletons );
  34717. this.bindLightTargets( object );
  34718. return object;
  34719. }
  34720. // internals
  34721. parseShapes( json ) {
  34722. const shapes = {};
  34723. if ( json !== undefined ) {
  34724. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34725. const shape = new Shape().fromJSON( json[ i ] );
  34726. shapes[ shape.uuid ] = shape;
  34727. }
  34728. }
  34729. return shapes;
  34730. }
  34731. parseSkeletons( json, object ) {
  34732. const skeletons = {};
  34733. const bones = {};
  34734. // generate bone lookup table
  34735. object.traverse( function ( child ) {
  34736. if ( child.isBone ) bones[ child.uuid ] = child;
  34737. } );
  34738. // create skeletons
  34739. if ( json !== undefined ) {
  34740. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34741. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  34742. skeletons[ skeleton.uuid ] = skeleton;
  34743. }
  34744. }
  34745. return skeletons;
  34746. }
  34747. parseGeometries( json, shapes ) {
  34748. const geometries = {};
  34749. if ( json !== undefined ) {
  34750. const bufferGeometryLoader = new BufferGeometryLoader();
  34751. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34752. let geometry;
  34753. const data = json[ i ];
  34754. switch ( data.type ) {
  34755. case 'BufferGeometry':
  34756. case 'InstancedBufferGeometry':
  34757. geometry = bufferGeometryLoader.parse( data );
  34758. break;
  34759. default:
  34760. if ( data.type in Geometries ) {
  34761. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  34762. } else {
  34763. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  34764. }
  34765. }
  34766. geometry.uuid = data.uuid;
  34767. if ( data.name !== undefined ) geometry.name = data.name;
  34768. if ( data.userData !== undefined ) geometry.userData = data.userData;
  34769. geometries[ data.uuid ] = geometry;
  34770. }
  34771. }
  34772. return geometries;
  34773. }
  34774. parseMaterials( json, textures ) {
  34775. const cache = {}; // MultiMaterial
  34776. const materials = {};
  34777. if ( json !== undefined ) {
  34778. const loader = new MaterialLoader();
  34779. loader.setTextures( textures );
  34780. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34781. const data = json[ i ];
  34782. if ( cache[ data.uuid ] === undefined ) {
  34783. cache[ data.uuid ] = loader.parse( data );
  34784. }
  34785. materials[ data.uuid ] = cache[ data.uuid ];
  34786. }
  34787. }
  34788. return materials;
  34789. }
  34790. parseAnimations( json ) {
  34791. const animations = {};
  34792. if ( json !== undefined ) {
  34793. for ( let i = 0; i < json.length; i ++ ) {
  34794. const data = json[ i ];
  34795. const clip = AnimationClip.parse( data );
  34796. animations[ clip.uuid ] = clip;
  34797. }
  34798. }
  34799. return animations;
  34800. }
  34801. parseImages( json, onLoad ) {
  34802. const scope = this;
  34803. const images = {};
  34804. let loader;
  34805. function loadImage( url ) {
  34806. scope.manager.itemStart( url );
  34807. return loader.load( url, function () {
  34808. scope.manager.itemEnd( url );
  34809. }, undefined, function () {
  34810. scope.manager.itemError( url );
  34811. scope.manager.itemEnd( url );
  34812. } );
  34813. }
  34814. function deserializeImage( image ) {
  34815. if ( typeof image === 'string' ) {
  34816. const url = image;
  34817. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  34818. return loadImage( path );
  34819. } else {
  34820. if ( image.data ) {
  34821. return {
  34822. data: getTypedArray( image.type, image.data ),
  34823. width: image.width,
  34824. height: image.height
  34825. };
  34826. } else {
  34827. return null;
  34828. }
  34829. }
  34830. }
  34831. if ( json !== undefined && json.length > 0 ) {
  34832. const manager = new LoadingManager( onLoad );
  34833. loader = new ImageLoader( manager );
  34834. loader.setCrossOrigin( this.crossOrigin );
  34835. for ( let i = 0, il = json.length; i < il; i ++ ) {
  34836. const image = json[ i ];
  34837. const url = image.url;
  34838. if ( Array.isArray( url ) ) {
  34839. // load array of images e.g CubeTexture
  34840. const imageArray = [];
  34841. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  34842. const currentUrl = url[ j ];
  34843. const deserializedImage = deserializeImage( currentUrl );
  34844. if ( deserializedImage !== null ) {
  34845. if ( deserializedImage instanceof HTMLImageElement ) {
  34846. imageArray.push( deserializedImage );
  34847. } else {
  34848. // special case: handle array of data textures for cube textures
  34849. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  34850. }
  34851. }
  34852. }
  34853. images[ image.uuid ] = new Source( imageArray );
  34854. } else {
  34855. // load single image
  34856. const deserializedImage = deserializeImage( image.url );
  34857. images[ image.uuid ] = new Source( deserializedImage );
  34858. }
  34859. }
  34860. }
  34861. return images;
  34862. }
  34863. async parseImagesAsync( json ) {
  34864. const scope = this;
  34865. const images = {};
  34866. let loader;
  34867. async function deserializeImage( image ) {
  34868. if ( typeof image === 'string' ) {
  34869. const url = image;
  34870. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  34871. return await loader.loadAsync( path );
  34872. } else {
  34873. if ( image.data ) {
  34874. return {
  34875. data: getTypedArray( image.type, image.data ),
  34876. width: image.width,
  34877. height: image.height
  34878. };
  34879. } else {
  34880. return null;
  34881. }
  34882. }
  34883. }
  34884. if ( json !== undefined && json.length > 0 ) {
  34885. loader = new ImageLoader( this.manager );
  34886. loader.setCrossOrigin( this.crossOrigin );
  34887. for ( let i = 0, il = json.length; i < il; i ++ ) {
  34888. const image = json[ i ];
  34889. const url = image.url;
  34890. if ( Array.isArray( url ) ) {
  34891. // load array of images e.g CubeTexture
  34892. const imageArray = [];
  34893. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  34894. const currentUrl = url[ j ];
  34895. const deserializedImage = await deserializeImage( currentUrl );
  34896. if ( deserializedImage !== null ) {
  34897. if ( deserializedImage instanceof HTMLImageElement ) {
  34898. imageArray.push( deserializedImage );
  34899. } else {
  34900. // special case: handle array of data textures for cube textures
  34901. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  34902. }
  34903. }
  34904. }
  34905. images[ image.uuid ] = new Source( imageArray );
  34906. } else {
  34907. // load single image
  34908. const deserializedImage = await deserializeImage( image.url );
  34909. images[ image.uuid ] = new Source( deserializedImage );
  34910. }
  34911. }
  34912. }
  34913. return images;
  34914. }
  34915. parseTextures( json, images ) {
  34916. function parseConstant( value, type ) {
  34917. if ( typeof value === 'number' ) return value;
  34918. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  34919. return type[ value ];
  34920. }
  34921. const textures = {};
  34922. if ( json !== undefined ) {
  34923. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34924. const data = json[ i ];
  34925. if ( data.image === undefined ) {
  34926. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  34927. }
  34928. if ( images[ data.image ] === undefined ) {
  34929. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  34930. }
  34931. const source = images[ data.image ];
  34932. const image = source.data;
  34933. let texture;
  34934. if ( Array.isArray( image ) ) {
  34935. texture = new CubeTexture();
  34936. if ( image.length === 6 ) texture.needsUpdate = true;
  34937. } else {
  34938. if ( image && image.data ) {
  34939. texture = new DataTexture();
  34940. } else {
  34941. texture = new Texture();
  34942. }
  34943. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  34944. }
  34945. texture.source = source;
  34946. texture.uuid = data.uuid;
  34947. if ( data.name !== undefined ) texture.name = data.name;
  34948. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  34949. if ( data.channel !== undefined ) texture.channel = data.channel;
  34950. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  34951. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  34952. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  34953. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  34954. if ( data.wrap !== undefined ) {
  34955. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  34956. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  34957. }
  34958. if ( data.format !== undefined ) texture.format = data.format;
  34959. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  34960. if ( data.type !== undefined ) texture.type = data.type;
  34961. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  34962. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  34963. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  34964. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  34965. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  34966. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  34967. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  34968. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  34969. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  34970. if ( data.userData !== undefined ) texture.userData = data.userData;
  34971. textures[ data.uuid ] = texture;
  34972. }
  34973. }
  34974. return textures;
  34975. }
  34976. parseObject( data, geometries, materials, textures, animations ) {
  34977. let object;
  34978. function getGeometry( name ) {
  34979. if ( geometries[ name ] === undefined ) {
  34980. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  34981. }
  34982. return geometries[ name ];
  34983. }
  34984. function getMaterial( name ) {
  34985. if ( name === undefined ) return undefined;
  34986. if ( Array.isArray( name ) ) {
  34987. const array = [];
  34988. for ( let i = 0, l = name.length; i < l; i ++ ) {
  34989. const uuid = name[ i ];
  34990. if ( materials[ uuid ] === undefined ) {
  34991. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  34992. }
  34993. array.push( materials[ uuid ] );
  34994. }
  34995. return array;
  34996. }
  34997. if ( materials[ name ] === undefined ) {
  34998. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  34999. }
  35000. return materials[ name ];
  35001. }
  35002. function getTexture( uuid ) {
  35003. if ( textures[ uuid ] === undefined ) {
  35004. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  35005. }
  35006. return textures[ uuid ];
  35007. }
  35008. let geometry, material;
  35009. switch ( data.type ) {
  35010. case 'Scene':
  35011. object = new Scene();
  35012. if ( data.background !== undefined ) {
  35013. if ( Number.isInteger( data.background ) ) {
  35014. object.background = new Color( data.background );
  35015. } else {
  35016. object.background = getTexture( data.background );
  35017. }
  35018. }
  35019. if ( data.environment !== undefined ) {
  35020. object.environment = getTexture( data.environment );
  35021. }
  35022. if ( data.fog !== undefined ) {
  35023. if ( data.fog.type === 'Fog' ) {
  35024. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  35025. } else if ( data.fog.type === 'FogExp2' ) {
  35026. object.fog = new FogExp2( data.fog.color, data.fog.density );
  35027. }
  35028. if ( data.fog.name !== '' ) {
  35029. object.fog.name = data.fog.name;
  35030. }
  35031. }
  35032. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  35033. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  35034. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  35035. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  35036. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  35037. break;
  35038. case 'PerspectiveCamera':
  35039. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  35040. if ( data.focus !== undefined ) object.focus = data.focus;
  35041. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35042. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  35043. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  35044. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35045. break;
  35046. case 'OrthographicCamera':
  35047. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  35048. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35049. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35050. break;
  35051. case 'AmbientLight':
  35052. object = new AmbientLight( data.color, data.intensity );
  35053. break;
  35054. case 'DirectionalLight':
  35055. object = new DirectionalLight( data.color, data.intensity );
  35056. object.target = data.target || '';
  35057. break;
  35058. case 'PointLight':
  35059. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  35060. break;
  35061. case 'RectAreaLight':
  35062. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  35063. break;
  35064. case 'SpotLight':
  35065. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  35066. object.target = data.target || '';
  35067. break;
  35068. case 'HemisphereLight':
  35069. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  35070. break;
  35071. case 'LightProbe':
  35072. object = new LightProbe().fromJSON( data );
  35073. break;
  35074. case 'SkinnedMesh':
  35075. geometry = getGeometry( data.geometry );
  35076. material = getMaterial( data.material );
  35077. object = new SkinnedMesh( geometry, material );
  35078. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  35079. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  35080. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  35081. break;
  35082. case 'Mesh':
  35083. geometry = getGeometry( data.geometry );
  35084. material = getMaterial( data.material );
  35085. object = new Mesh( geometry, material );
  35086. break;
  35087. case 'InstancedMesh':
  35088. geometry = getGeometry( data.geometry );
  35089. material = getMaterial( data.material );
  35090. const count = data.count;
  35091. const instanceMatrix = data.instanceMatrix;
  35092. const instanceColor = data.instanceColor;
  35093. object = new InstancedMesh( geometry, material, count );
  35094. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  35095. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  35096. break;
  35097. case 'BatchedMesh':
  35098. geometry = getGeometry( data.geometry );
  35099. material = getMaterial( data.material );
  35100. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  35101. object.geometry = geometry;
  35102. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  35103. object.sortObjects = data.sortObjects;
  35104. object._drawRanges = data.drawRanges;
  35105. object._reservedRanges = data.reservedRanges;
  35106. object._geometryInfo = data.geometryInfo.map( info => {
  35107. let box = null;
  35108. let sphere = null;
  35109. if ( info.boundingBox !== undefined ) {
  35110. box = new Box3();
  35111. box.min.fromArray( info.boundingBox.min );
  35112. box.max.fromArray( info.boundingBox.max );
  35113. }
  35114. if ( info.boundingSphere !== undefined ) {
  35115. sphere = new Sphere();
  35116. sphere.radius = info.boundingSphere.radius;
  35117. sphere.center.fromArray( info.boundingSphere.center );
  35118. }
  35119. return {
  35120. ...info,
  35121. boundingBox: box,
  35122. boundingSphere: sphere
  35123. };
  35124. } );
  35125. object._instanceInfo = data.instanceInfo;
  35126. object._availableInstanceIds = data._availableInstanceIds;
  35127. object._availableGeometryIds = data._availableGeometryIds;
  35128. object._nextIndexStart = data.nextIndexStart;
  35129. object._nextVertexStart = data.nextVertexStart;
  35130. object._geometryCount = data.geometryCount;
  35131. object._maxInstanceCount = data.maxInstanceCount;
  35132. object._maxVertexCount = data.maxVertexCount;
  35133. object._maxIndexCount = data.maxIndexCount;
  35134. object._geometryInitialized = data.geometryInitialized;
  35135. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  35136. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  35137. if ( data.colorsTexture !== undefined ) {
  35138. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  35139. }
  35140. if ( data.boundingSphere !== undefined ) {
  35141. object.boundingSphere = new Sphere();
  35142. object.boundingSphere.center.fromArray( data.boundingSphere.center );
  35143. object.boundingSphere.radius = data.boundingSphere.radius;
  35144. }
  35145. if ( data.boundingBox !== undefined ) {
  35146. object.boundingBox = new Box3();
  35147. object.boundingBox.min.fromArray( data.boundingBox.min );
  35148. object.boundingBox.max.fromArray( data.boundingBox.max );
  35149. }
  35150. break;
  35151. case 'LOD':
  35152. object = new LOD();
  35153. break;
  35154. case 'Line':
  35155. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  35156. break;
  35157. case 'LineLoop':
  35158. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  35159. break;
  35160. case 'LineSegments':
  35161. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  35162. break;
  35163. case 'PointCloud':
  35164. case 'Points':
  35165. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  35166. break;
  35167. case 'Sprite':
  35168. object = new Sprite( getMaterial( data.material ) );
  35169. break;
  35170. case 'Group':
  35171. object = new Group();
  35172. break;
  35173. case 'Bone':
  35174. object = new Bone();
  35175. break;
  35176. default:
  35177. object = new Object3D();
  35178. }
  35179. object.uuid = data.uuid;
  35180. if ( data.name !== undefined ) object.name = data.name;
  35181. if ( data.matrix !== undefined ) {
  35182. object.matrix.fromArray( data.matrix );
  35183. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  35184. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  35185. } else {
  35186. if ( data.position !== undefined ) object.position.fromArray( data.position );
  35187. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  35188. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  35189. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  35190. }
  35191. if ( data.up !== undefined ) object.up.fromArray( data.up );
  35192. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  35193. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  35194. if ( data.shadow ) {
  35195. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  35196. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  35197. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  35198. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  35199. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  35200. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  35201. }
  35202. if ( data.visible !== undefined ) object.visible = data.visible;
  35203. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  35204. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  35205. if ( data.userData !== undefined ) object.userData = data.userData;
  35206. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  35207. if ( data.children !== undefined ) {
  35208. const children = data.children;
  35209. for ( let i = 0; i < children.length; i ++ ) {
  35210. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  35211. }
  35212. }
  35213. if ( data.animations !== undefined ) {
  35214. const objectAnimations = data.animations;
  35215. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  35216. const uuid = objectAnimations[ i ];
  35217. object.animations.push( animations[ uuid ] );
  35218. }
  35219. }
  35220. if ( data.type === 'LOD' ) {
  35221. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  35222. const levels = data.levels;
  35223. for ( let l = 0; l < levels.length; l ++ ) {
  35224. const level = levels[ l ];
  35225. const child = object.getObjectByProperty( 'uuid', level.object );
  35226. if ( child !== undefined ) {
  35227. object.addLevel( child, level.distance, level.hysteresis );
  35228. }
  35229. }
  35230. }
  35231. return object;
  35232. }
  35233. bindSkeletons( object, skeletons ) {
  35234. if ( Object.keys( skeletons ).length === 0 ) return;
  35235. object.traverse( function ( child ) {
  35236. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  35237. const skeleton = skeletons[ child.skeleton ];
  35238. if ( skeleton === undefined ) {
  35239. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  35240. } else {
  35241. child.bind( skeleton, child.bindMatrix );
  35242. }
  35243. }
  35244. } );
  35245. }
  35246. bindLightTargets( object ) {
  35247. object.traverse( function ( child ) {
  35248. if ( child.isDirectionalLight || child.isSpotLight ) {
  35249. const uuid = child.target;
  35250. const target = object.getObjectByProperty( 'uuid', uuid );
  35251. if ( target !== undefined ) {
  35252. child.target = target;
  35253. } else {
  35254. child.target = new Object3D();
  35255. }
  35256. }
  35257. } );
  35258. }
  35259. }
  35260. const TEXTURE_MAPPING = {
  35261. UVMapping: UVMapping,
  35262. CubeReflectionMapping: CubeReflectionMapping,
  35263. CubeRefractionMapping: CubeRefractionMapping,
  35264. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  35265. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  35266. CubeUVReflectionMapping: CubeUVReflectionMapping
  35267. };
  35268. const TEXTURE_WRAPPING = {
  35269. RepeatWrapping: RepeatWrapping,
  35270. ClampToEdgeWrapping: ClampToEdgeWrapping,
  35271. MirroredRepeatWrapping: MirroredRepeatWrapping
  35272. };
  35273. const TEXTURE_FILTER = {
  35274. NearestFilter: NearestFilter,
  35275. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  35276. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  35277. LinearFilter: LinearFilter,
  35278. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  35279. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  35280. };
  35281. /**
  35282. * A loader for loading images as an [ImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap}.
  35283. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  35284. * textures for rendering.
  35285. *
  35286. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  35287. * They needs these configuration on bitmap creation unlike regular images need them on uploading to GPU.
  35288. *
  35289. * You need to set the equivalent options via {@link ImageBitmapLoader#setOptions} instead.
  35290. *
  35291. * Also note that unlike {@link FileLoader}, this loader does not avoid multiple concurrent requests to the same URL.
  35292. *
  35293. * ```js
  35294. * const loader = new THREE.ImageBitmapLoader();
  35295. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  35296. * const imageBitmap = await loader.loadAsync( 'image.png' );
  35297. *
  35298. * const texture = new THREE.Texture( imageBitmap );
  35299. * texture.needsUpdate = true;
  35300. * ```
  35301. *
  35302. * @augments Loader
  35303. */
  35304. class ImageBitmapLoader extends Loader {
  35305. /**
  35306. * Constructs a new image bitmap loader.
  35307. *
  35308. * @param {LoadingManager} [manager] - The loading manager.
  35309. */
  35310. constructor( manager ) {
  35311. super( manager );
  35312. /**
  35313. * This flag can be used for type testing.
  35314. *
  35315. * @type {boolean}
  35316. * @readonly
  35317. * @default true
  35318. */
  35319. this.isImageBitmapLoader = true;
  35320. if ( typeof createImageBitmap === 'undefined' ) {
  35321. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  35322. }
  35323. if ( typeof fetch === 'undefined' ) {
  35324. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  35325. }
  35326. /**
  35327. * Represents the loader options.
  35328. *
  35329. * @type {Object}
  35330. * @default {premultiplyAlpha:'none'}
  35331. */
  35332. this.options = { premultiplyAlpha: 'none' };
  35333. }
  35334. /**
  35335. * Sets the given loader options. The structure of the object must match the `options` parameter of
  35336. * [createImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap}.
  35337. *
  35338. * @param {Object} options - The loader options to set.
  35339. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  35340. */
  35341. setOptions( options ) {
  35342. this.options = options;
  35343. return this;
  35344. }
  35345. /**
  35346. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  35347. *
  35348. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35349. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  35350. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  35351. * @param {onErrorCallback} onError - Executed when errors occur.
  35352. * @return {ImageBitmap|undefined} The image bitmap.
  35353. */
  35354. load( url, onLoad, onProgress, onError ) {
  35355. if ( url === undefined ) url = '';
  35356. if ( this.path !== undefined ) url = this.path + url;
  35357. url = this.manager.resolveURL( url );
  35358. const scope = this;
  35359. const cached = Cache.get( url );
  35360. if ( cached !== undefined ) {
  35361. scope.manager.itemStart( url );
  35362. // If cached is a promise, wait for it to resolve
  35363. if ( cached.then ) {
  35364. cached.then( imageBitmap => {
  35365. if ( onLoad ) onLoad( imageBitmap );
  35366. scope.manager.itemEnd( url );
  35367. } ).catch( e => {
  35368. if ( onError ) onError( e );
  35369. } );
  35370. return;
  35371. }
  35372. // If cached is not a promise (i.e., it's already an imageBitmap)
  35373. setTimeout( function () {
  35374. if ( onLoad ) onLoad( cached );
  35375. scope.manager.itemEnd( url );
  35376. }, 0 );
  35377. return cached;
  35378. }
  35379. const fetchOptions = {};
  35380. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  35381. fetchOptions.headers = this.requestHeader;
  35382. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  35383. return res.blob();
  35384. } ).then( function ( blob ) {
  35385. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  35386. } ).then( function ( imageBitmap ) {
  35387. Cache.add( url, imageBitmap );
  35388. if ( onLoad ) onLoad( imageBitmap );
  35389. scope.manager.itemEnd( url );
  35390. return imageBitmap;
  35391. } ).catch( function ( e ) {
  35392. if ( onError ) onError( e );
  35393. Cache.remove( url );
  35394. scope.manager.itemError( url );
  35395. scope.manager.itemEnd( url );
  35396. } );
  35397. Cache.add( url, promise );
  35398. scope.manager.itemStart( url );
  35399. }
  35400. }
  35401. let _context;
  35402. /**
  35403. * Manages the global audio context in the engine.
  35404. *
  35405. * @hideconstructor
  35406. */
  35407. class AudioContext {
  35408. /**
  35409. * Returns the global native audio context.
  35410. *
  35411. * @return {AudioContext} The native audio context.
  35412. */
  35413. static getContext() {
  35414. if ( _context === undefined ) {
  35415. _context = new ( window.AudioContext || window.webkitAudioContext )();
  35416. }
  35417. return _context;
  35418. }
  35419. /**
  35420. * Allows to set the global native audio context from outside.
  35421. *
  35422. * @param {AudioContext} value - The native context to set.
  35423. */
  35424. static setContext( value ) {
  35425. _context = value;
  35426. }
  35427. }
  35428. /**
  35429. * Class for loading audio buffers. Audios are internally
  35430. * loaded via {@link FileLoader}.
  35431. *
  35432. * ```js
  35433. * const audioListener = new THREE.AudioListener();
  35434. * const ambientSound = new THREE.Audio( audioListener );
  35435. *
  35436. * const loader = new THREE.AudioLoader();
  35437. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  35438. *
  35439. * ambientSound.setBuffer( audioBuffer );
  35440. * ambientSound.play();
  35441. * ```
  35442. *
  35443. * @augments Loader
  35444. */
  35445. class AudioLoader extends Loader {
  35446. /**
  35447. * Constructs a new audio loader.
  35448. *
  35449. * @param {LoadingManager} [manager] - The loading manager.
  35450. */
  35451. constructor( manager ) {
  35452. super( manager );
  35453. }
  35454. /**
  35455. * Starts loading from the given URL and passes the loaded audio buffer
  35456. * to the `onLoad()` callback.
  35457. *
  35458. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35459. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  35460. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35461. * @param {onErrorCallback} onError - Executed when errors occur.
  35462. */
  35463. load( url, onLoad, onProgress, onError ) {
  35464. const scope = this;
  35465. const loader = new FileLoader( this.manager );
  35466. loader.setResponseType( 'arraybuffer' );
  35467. loader.setPath( this.path );
  35468. loader.setRequestHeader( this.requestHeader );
  35469. loader.setWithCredentials( this.withCredentials );
  35470. loader.load( url, function ( buffer ) {
  35471. try {
  35472. // Create a copy of the buffer. The `decodeAudioData` method
  35473. // detaches the buffer when complete, preventing reuse.
  35474. const bufferCopy = buffer.slice( 0 );
  35475. const context = AudioContext.getContext();
  35476. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  35477. onLoad( audioBuffer );
  35478. } ).catch( handleError );
  35479. } catch ( e ) {
  35480. handleError( e );
  35481. }
  35482. }, onProgress, onError );
  35483. function handleError( e ) {
  35484. if ( onError ) {
  35485. onError( e );
  35486. } else {
  35487. console.error( e );
  35488. }
  35489. scope.manager.itemError( url );
  35490. }
  35491. }
  35492. }
  35493. const _eyeRight = /*@__PURE__*/ new Matrix4();
  35494. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  35495. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  35496. /**
  35497. * A special type of camera that uses two perspective cameras with
  35498. * stereoscopic projection. Can be used for rendering stereo effects
  35499. * like [3D Anaglyph]{@link https://en.wikipedia.org/wiki/Anaglyph_3D} or
  35500. * [Parallax Barrier]{@link https://en.wikipedia.org/wiki/parallax_barrier}.
  35501. */
  35502. class StereoCamera {
  35503. /**
  35504. * Constructs a new stereo camera.
  35505. */
  35506. constructor() {
  35507. /**
  35508. * The type property is used for detecting the object type
  35509. * in context of serialization/deserialization.
  35510. *
  35511. * @type {string}
  35512. * @readonly
  35513. */
  35514. this.type = 'StereoCamera';
  35515. /**
  35516. * The aspect.
  35517. *
  35518. * @type {number}
  35519. * @default 1
  35520. */
  35521. this.aspect = 1;
  35522. /**
  35523. * The eye separation which represents the distance
  35524. * between the left and right camera.
  35525. *
  35526. * @type {number}
  35527. * @default 0.064
  35528. */
  35529. this.eyeSep = 0.064;
  35530. /**
  35531. * The camera representing the left eye. This is added to layer `1` so objects to be
  35532. * rendered by the left camera must also be added to this layer.
  35533. *
  35534. * @type {PerspectiveCamera}
  35535. */
  35536. this.cameraL = new PerspectiveCamera();
  35537. this.cameraL.layers.enable( 1 );
  35538. this.cameraL.matrixAutoUpdate = false;
  35539. /**
  35540. * The camera representing the right eye. This is added to layer `2` so objects to be
  35541. * rendered by the right camera must also be added to this layer.
  35542. *
  35543. * @type {PerspectiveCamera}
  35544. */
  35545. this.cameraR = new PerspectiveCamera();
  35546. this.cameraR.layers.enable( 2 );
  35547. this.cameraR.matrixAutoUpdate = false;
  35548. this._cache = {
  35549. focus: null,
  35550. fov: null,
  35551. aspect: null,
  35552. near: null,
  35553. far: null,
  35554. zoom: null,
  35555. eyeSep: null
  35556. };
  35557. }
  35558. /**
  35559. * Updates the stereo camera based on the given perspective camera.
  35560. *
  35561. * @param {PerspectiveCamera} camera - The perspective camera.
  35562. */
  35563. update( camera ) {
  35564. const cache = this._cache;
  35565. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  35566. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  35567. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  35568. if ( needsUpdate ) {
  35569. cache.focus = camera.focus;
  35570. cache.fov = camera.fov;
  35571. cache.aspect = camera.aspect * this.aspect;
  35572. cache.near = camera.near;
  35573. cache.far = camera.far;
  35574. cache.zoom = camera.zoom;
  35575. cache.eyeSep = this.eyeSep;
  35576. // Off-axis stereoscopic effect based on
  35577. // http://paulbourke.net/stereographics/stereorender/
  35578. _projectionMatrix.copy( camera.projectionMatrix );
  35579. const eyeSepHalf = cache.eyeSep / 2;
  35580. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  35581. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  35582. let xmin, xmax;
  35583. // translate xOffset
  35584. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  35585. _eyeRight.elements[ 12 ] = eyeSepHalf;
  35586. // for left eye
  35587. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  35588. xmax = ymax * cache.aspect + eyeSepOnProjection;
  35589. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  35590. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  35591. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  35592. // for right eye
  35593. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  35594. xmax = ymax * cache.aspect - eyeSepOnProjection;
  35595. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  35596. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  35597. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  35598. }
  35599. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  35600. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  35601. }
  35602. }
  35603. /**
  35604. * This type of camera can be used in order to efficiently render a scene with a
  35605. * predefined set of cameras. This is an important performance aspect for
  35606. * rendering VR scenes.
  35607. *
  35608. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  35609. * to define for each sub camera the `viewport` property which determines the
  35610. * part of the viewport that is rendered with this camera.
  35611. *
  35612. * @augments PerspectiveCamera
  35613. */
  35614. class ArrayCamera extends PerspectiveCamera {
  35615. /**
  35616. * Constructs a new array camera.
  35617. *
  35618. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  35619. */
  35620. constructor( array = [] ) {
  35621. super();
  35622. /**
  35623. * This flag can be used for type testing.
  35624. *
  35625. * @type {boolean}
  35626. * @readonly
  35627. * @default true
  35628. */
  35629. this.isArrayCamera = true;
  35630. /**
  35631. * Whether this camera is used with multiview rendering or not.
  35632. *
  35633. * @type {boolean}
  35634. * @readonly
  35635. * @default false
  35636. */
  35637. this.isMultiViewCamera = false;
  35638. /**
  35639. * An array of perspective sub cameras.
  35640. *
  35641. * @type {Array<PerspectiveCamera>}
  35642. */
  35643. this.cameras = array;
  35644. }
  35645. }
  35646. /**
  35647. * Class for keeping track of time.
  35648. */
  35649. class Clock {
  35650. /**
  35651. * Constructs a new clock.
  35652. *
  35653. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  35654. * `getDelta()` is called for the first time.
  35655. */
  35656. constructor( autoStart = true ) {
  35657. /**
  35658. * If set to `true`, the clock starts automatically when `getDelta()` is called
  35659. * for the first time.
  35660. *
  35661. * @type {boolean}
  35662. * @default true
  35663. */
  35664. this.autoStart = autoStart;
  35665. /**
  35666. * Holds the time at which the clock's `start()` method was last called.
  35667. *
  35668. * @type {number}
  35669. * @default 0
  35670. */
  35671. this.startTime = 0;
  35672. /**
  35673. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  35674. * `getDelta()` methods were last called.
  35675. *
  35676. * @type {number}
  35677. * @default 0
  35678. */
  35679. this.oldTime = 0;
  35680. /**
  35681. * Keeps track of the total time that the clock has been running.
  35682. *
  35683. * @type {number}
  35684. * @default 0
  35685. */
  35686. this.elapsedTime = 0;
  35687. /**
  35688. * Whether the clock is running or not.
  35689. *
  35690. * @type {boolean}
  35691. * @default true
  35692. */
  35693. this.running = false;
  35694. }
  35695. /**
  35696. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  35697. * called by the class.
  35698. */
  35699. start() {
  35700. this.startTime = now();
  35701. this.oldTime = this.startTime;
  35702. this.elapsedTime = 0;
  35703. this.running = true;
  35704. }
  35705. /**
  35706. * Stops the clock.
  35707. */
  35708. stop() {
  35709. this.getElapsedTime();
  35710. this.running = false;
  35711. this.autoStart = false;
  35712. }
  35713. /**
  35714. * Returns the elapsed time in seconds.
  35715. *
  35716. * @return {number} The elapsed time.
  35717. */
  35718. getElapsedTime() {
  35719. this.getDelta();
  35720. return this.elapsedTime;
  35721. }
  35722. /**
  35723. * Returns the delta time in seconds.
  35724. *
  35725. * @return {number} The delta time.
  35726. */
  35727. getDelta() {
  35728. let diff = 0;
  35729. if ( this.autoStart && ! this.running ) {
  35730. this.start();
  35731. return 0;
  35732. }
  35733. if ( this.running ) {
  35734. const newTime = now();
  35735. diff = ( newTime - this.oldTime ) / 1000;
  35736. this.oldTime = newTime;
  35737. this.elapsedTime += diff;
  35738. }
  35739. return diff;
  35740. }
  35741. }
  35742. function now() {
  35743. return performance.now();
  35744. }
  35745. const _position$1 = /*@__PURE__*/ new Vector3();
  35746. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  35747. const _scale$1 = /*@__PURE__*/ new Vector3();
  35748. const _orientation$1 = /*@__PURE__*/ new Vector3();
  35749. /**
  35750. * The class represents a virtual listener of the all positional and non-positional audio effects
  35751. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  35752. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  35753. *
  35754. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  35755. * camera represents the 3D transformation of the listener.
  35756. *
  35757. * @augments Object3D
  35758. */
  35759. class AudioListener extends Object3D {
  35760. /**
  35761. * Constructs a new audio listener.
  35762. */
  35763. constructor() {
  35764. super();
  35765. this.type = 'AudioListener';
  35766. /**
  35767. * The native audio context.
  35768. *
  35769. * @type {AudioContext}
  35770. * @readonly
  35771. */
  35772. this.context = AudioContext.getContext();
  35773. /**
  35774. * The gain node used for volume control.
  35775. *
  35776. * @type {GainNode}
  35777. * @readonly
  35778. */
  35779. this.gain = this.context.createGain();
  35780. this.gain.connect( this.context.destination );
  35781. /**
  35782. * An optional filter.
  35783. *
  35784. * Defined via {@link AudioListener#setFilter}.
  35785. *
  35786. * @type {?AudioNode}
  35787. * @default null
  35788. * @readonly
  35789. */
  35790. this.filter = null;
  35791. /**
  35792. * Time delta values required for `linearRampToValueAtTime()` usage.
  35793. *
  35794. * @type {number}
  35795. * @default 0
  35796. * @readonly
  35797. */
  35798. this.timeDelta = 0;
  35799. // private
  35800. this._clock = new Clock();
  35801. }
  35802. /**
  35803. * Returns the listener's input node.
  35804. *
  35805. * This method is used by other audio nodes to connect to this listener.
  35806. *
  35807. * @return {GainNode} The input node.
  35808. */
  35809. getInput() {
  35810. return this.gain;
  35811. }
  35812. /**
  35813. * Removes the current filter from this listener.
  35814. *
  35815. * @return {AudioListener} A reference to this listener.
  35816. */
  35817. removeFilter() {
  35818. if ( this.filter !== null ) {
  35819. this.gain.disconnect( this.filter );
  35820. this.filter.disconnect( this.context.destination );
  35821. this.gain.connect( this.context.destination );
  35822. this.filter = null;
  35823. }
  35824. return this;
  35825. }
  35826. /**
  35827. * Returns the current set filter.
  35828. *
  35829. * @return {?AudioNode} The filter.
  35830. */
  35831. getFilter() {
  35832. return this.filter;
  35833. }
  35834. /**
  35835. * Sets the given filter to this listener.
  35836. *
  35837. * @param {AudioNode} value - The filter to set.
  35838. * @return {AudioListener} A reference to this listener.
  35839. */
  35840. setFilter( value ) {
  35841. if ( this.filter !== null ) {
  35842. this.gain.disconnect( this.filter );
  35843. this.filter.disconnect( this.context.destination );
  35844. } else {
  35845. this.gain.disconnect( this.context.destination );
  35846. }
  35847. this.filter = value;
  35848. this.gain.connect( this.filter );
  35849. this.filter.connect( this.context.destination );
  35850. return this;
  35851. }
  35852. /**
  35853. * Returns the applications master volume.
  35854. *
  35855. * @return {number} The master volume.
  35856. */
  35857. getMasterVolume() {
  35858. return this.gain.gain.value;
  35859. }
  35860. /**
  35861. * Sets the applications master volume. This volume setting affects
  35862. * all audio nodes in the scene.
  35863. *
  35864. * @param {number} value - The master volume to set.
  35865. * @return {AudioListener} A reference to this listener.
  35866. */
  35867. setMasterVolume( value ) {
  35868. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  35869. return this;
  35870. }
  35871. updateMatrixWorld( force ) {
  35872. super.updateMatrixWorld( force );
  35873. const listener = this.context.listener;
  35874. const up = this.up;
  35875. this.timeDelta = this._clock.getDelta();
  35876. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  35877. _orientation$1.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  35878. if ( listener.positionX ) {
  35879. // code path for Chrome (see #14393)
  35880. const endTime = this.context.currentTime + this.timeDelta;
  35881. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  35882. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  35883. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  35884. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  35885. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  35886. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  35887. listener.upX.linearRampToValueAtTime( up.x, endTime );
  35888. listener.upY.linearRampToValueAtTime( up.y, endTime );
  35889. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  35890. } else {
  35891. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  35892. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  35893. }
  35894. }
  35895. }
  35896. /**
  35897. * Represents a non-positional ( global ) audio object.
  35898. *
  35899. * This and related audio modules make use of the [Web Audio API]{@link https://www.w3.org/TR/webaudio-1.1/}.
  35900. *
  35901. * ```js
  35902. * // create an AudioListener and add it to the camera
  35903. * const listener = new THREE.AudioListener();
  35904. * camera.add( listener );
  35905. *
  35906. * // create a global audio source
  35907. * const sound = new THREE.Audio( listener );
  35908. *
  35909. * // load a sound and set it as the Audio object's buffer
  35910. * const audioLoader = new THREE.AudioLoader();
  35911. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  35912. * sound.setBuffer( buffer );
  35913. * sound.setLoop( true );
  35914. * sound.setVolume( 0.5 );
  35915. * sound.play();
  35916. * });
  35917. * ```
  35918. *
  35919. * @augments Object3D
  35920. */
  35921. class Audio extends Object3D {
  35922. /**
  35923. * Constructs a new audio.
  35924. *
  35925. * @param {AudioListener} listener - The global audio listener.
  35926. */
  35927. constructor( listener ) {
  35928. super();
  35929. this.type = 'Audio';
  35930. /**
  35931. * The global audio listener.
  35932. *
  35933. * @type {AudioListener}
  35934. * @readonly
  35935. */
  35936. this.listener = listener;
  35937. /**
  35938. * The audio context.
  35939. *
  35940. * @type {AudioContext}
  35941. * @readonly
  35942. */
  35943. this.context = listener.context;
  35944. /**
  35945. * The gain node used for volume control.
  35946. *
  35947. * @type {GainNode}
  35948. * @readonly
  35949. */
  35950. this.gain = this.context.createGain();
  35951. this.gain.connect( listener.getInput() );
  35952. /**
  35953. * Whether to start playback automatically or not.
  35954. *
  35955. * @type {boolean}
  35956. * @default false
  35957. */
  35958. this.autoplay = false;
  35959. /**
  35960. * A reference to an audio buffer.
  35961. *
  35962. * Defined via {@link Audio#setBuffer}.
  35963. *
  35964. * @type {?AudioBuffer}
  35965. * @default null
  35966. * @readonly
  35967. */
  35968. this.buffer = null;
  35969. /**
  35970. * Modify pitch, measured in cents. +/- 100 is a semitone.
  35971. * +/- 1200 is an octave.
  35972. *
  35973. * Defined via {@link Audio#setDetune}.
  35974. *
  35975. * @type {number}
  35976. * @default 0
  35977. * @readonly
  35978. */
  35979. this.detune = 0;
  35980. /**
  35981. * Whether the audio should loop or not.
  35982. *
  35983. * Defined via {@link Audio#setLoop}.
  35984. *
  35985. * @type {boolean}
  35986. * @default false
  35987. * @readonly
  35988. */
  35989. this.loop = false;
  35990. /**
  35991. * Defines where in the audio buffer the replay should
  35992. * start, in seconds.
  35993. *
  35994. * @type {number}
  35995. * @default 0
  35996. */
  35997. this.loopStart = 0;
  35998. /**
  35999. * Defines where in the audio buffer the replay should
  36000. * stop, in seconds.
  36001. *
  36002. * @type {number}
  36003. * @default 0
  36004. */
  36005. this.loopEnd = 0;
  36006. /**
  36007. * An offset to the time within the audio buffer the playback
  36008. * should begin, in seconds.
  36009. *
  36010. * @type {number}
  36011. * @default 0
  36012. */
  36013. this.offset = 0;
  36014. /**
  36015. * Overrides the default duration of the audio.
  36016. *
  36017. * @type {undefined|number}
  36018. * @default undefined
  36019. */
  36020. this.duration = undefined;
  36021. /**
  36022. * The playback speed.
  36023. *
  36024. * Defined via {@link Audio#setPlaybackRate}.
  36025. *
  36026. * @type {number}
  36027. * @readonly
  36028. * @default 1
  36029. */
  36030. this.playbackRate = 1;
  36031. /**
  36032. * Indicates whether the audio is playing or not.
  36033. *
  36034. * This flag will be automatically set when using {@link Audio#play},
  36035. * {@link Audio#pause}, {@link Audio#stop}.
  36036. *
  36037. * @type {boolean}
  36038. * @readonly
  36039. * @default false
  36040. */
  36041. this.isPlaying = false;
  36042. /**
  36043. * Indicates whether the audio playback can be controlled
  36044. * with method like {@link Audio#play} or {@link Audio#pause}.
  36045. *
  36046. * This flag will be automatically set when audio sources are
  36047. * defined.
  36048. *
  36049. * @type {boolean}
  36050. * @readonly
  36051. * @default true
  36052. */
  36053. this.hasPlaybackControl = true;
  36054. /**
  36055. * Holds a reference to the current audio source.
  36056. *
  36057. * The property is automatically by one of the `set*()` methods.
  36058. *
  36059. * @type {?AudioNode}
  36060. * @readonly
  36061. * @default null
  36062. */
  36063. this.source = null;
  36064. /**
  36065. * Defines the source type.
  36066. *
  36067. * The property is automatically by one of the `set*()` methods.
  36068. *
  36069. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  36070. * @readonly
  36071. * @default 'empty'
  36072. */
  36073. this.sourceType = 'empty';
  36074. this._startedAt = 0;
  36075. this._progress = 0;
  36076. this._connected = false;
  36077. /**
  36078. * Can be used to apply a variety of low-order filters to create
  36079. * more complex sound effects e.g. via `BiquadFilterNode`.
  36080. *
  36081. * The property is automatically set by {@link Audio#setFilters}.
  36082. *
  36083. * @type {Array<AudioNode>}
  36084. * @readonly
  36085. */
  36086. this.filters = [];
  36087. }
  36088. /**
  36089. * Returns the output audio node.
  36090. *
  36091. * @return {GainNode} The output node.
  36092. */
  36093. getOutput() {
  36094. return this.gain;
  36095. }
  36096. /**
  36097. * Sets the given audio node as the source of this instance.
  36098. *
  36099. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  36100. *
  36101. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  36102. * @return {Audio} A reference to this instance.
  36103. */
  36104. setNodeSource( audioNode ) {
  36105. this.hasPlaybackControl = false;
  36106. this.sourceType = 'audioNode';
  36107. this.source = audioNode;
  36108. this.connect();
  36109. return this;
  36110. }
  36111. /**
  36112. * Sets the given media element as the source of this instance.
  36113. *
  36114. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  36115. *
  36116. * @param {HTMLMediaElement} mediaElement - The media element.
  36117. * @return {Audio} A reference to this instance.
  36118. */
  36119. setMediaElementSource( mediaElement ) {
  36120. this.hasPlaybackControl = false;
  36121. this.sourceType = 'mediaNode';
  36122. this.source = this.context.createMediaElementSource( mediaElement );
  36123. this.connect();
  36124. return this;
  36125. }
  36126. /**
  36127. * Sets the given media stream as the source of this instance.
  36128. *
  36129. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  36130. *
  36131. * @param {MediaStream} mediaStream - The media stream.
  36132. * @return {Audio} A reference to this instance.
  36133. */
  36134. setMediaStreamSource( mediaStream ) {
  36135. this.hasPlaybackControl = false;
  36136. this.sourceType = 'mediaStreamNode';
  36137. this.source = this.context.createMediaStreamSource( mediaStream );
  36138. this.connect();
  36139. return this;
  36140. }
  36141. /**
  36142. * Sets the given audio buffer as the source of this instance.
  36143. *
  36144. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  36145. *
  36146. * @param {AudioBuffer} audioBuffer - The audio buffer.
  36147. * @return {Audio} A reference to this instance.
  36148. */
  36149. setBuffer( audioBuffer ) {
  36150. this.buffer = audioBuffer;
  36151. this.sourceType = 'buffer';
  36152. if ( this.autoplay ) this.play();
  36153. return this;
  36154. }
  36155. /**
  36156. * Starts the playback of the audio.
  36157. *
  36158. * Can only be used with compatible audio sources that allow playback control.
  36159. *
  36160. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  36161. * @return {Audio|undefined} A reference to this instance.
  36162. */
  36163. play( delay = 0 ) {
  36164. if ( this.isPlaying === true ) {
  36165. console.warn( 'THREE.Audio: Audio is already playing.' );
  36166. return;
  36167. }
  36168. if ( this.hasPlaybackControl === false ) {
  36169. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36170. return;
  36171. }
  36172. this._startedAt = this.context.currentTime + delay;
  36173. const source = this.context.createBufferSource();
  36174. source.buffer = this.buffer;
  36175. source.loop = this.loop;
  36176. source.loopStart = this.loopStart;
  36177. source.loopEnd = this.loopEnd;
  36178. source.onended = this.onEnded.bind( this );
  36179. source.start( this._startedAt, this._progress + this.offset, this.duration );
  36180. this.isPlaying = true;
  36181. this.source = source;
  36182. this.setDetune( this.detune );
  36183. this.setPlaybackRate( this.playbackRate );
  36184. return this.connect();
  36185. }
  36186. /**
  36187. * Pauses the playback of the audio.
  36188. *
  36189. * Can only be used with compatible audio sources that allow playback control.
  36190. *
  36191. * @return {Audio|undefined} A reference to this instance.
  36192. */
  36193. pause() {
  36194. if ( this.hasPlaybackControl === false ) {
  36195. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36196. return;
  36197. }
  36198. if ( this.isPlaying === true ) {
  36199. // update current progress
  36200. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  36201. if ( this.loop === true ) {
  36202. // ensure _progress does not exceed duration with looped audios
  36203. this._progress = this._progress % ( this.duration || this.buffer.duration );
  36204. }
  36205. this.source.stop();
  36206. this.source.onended = null;
  36207. this.isPlaying = false;
  36208. }
  36209. return this;
  36210. }
  36211. /**
  36212. * Stops the playback of the audio.
  36213. *
  36214. * Can only be used with compatible audio sources that allow playback control.
  36215. *
  36216. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  36217. * @return {Audio|undefined} A reference to this instance.
  36218. */
  36219. stop( delay = 0 ) {
  36220. if ( this.hasPlaybackControl === false ) {
  36221. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36222. return;
  36223. }
  36224. this._progress = 0;
  36225. if ( this.source !== null ) {
  36226. this.source.stop( this.context.currentTime + delay );
  36227. this.source.onended = null;
  36228. }
  36229. this.isPlaying = false;
  36230. return this;
  36231. }
  36232. /**
  36233. * Connects to the audio source. This is used internally on
  36234. * initialisation and when setting / removing filters.
  36235. *
  36236. * @return {Audio} A reference to this instance.
  36237. */
  36238. connect() {
  36239. if ( this.filters.length > 0 ) {
  36240. this.source.connect( this.filters[ 0 ] );
  36241. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36242. this.filters[ i - 1 ].connect( this.filters[ i ] );
  36243. }
  36244. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  36245. } else {
  36246. this.source.connect( this.getOutput() );
  36247. }
  36248. this._connected = true;
  36249. return this;
  36250. }
  36251. /**
  36252. * Disconnects to the audio source. This is used internally on
  36253. * initialisation and when setting / removing filters.
  36254. *
  36255. * @return {Audio|undefined} A reference to this instance.
  36256. */
  36257. disconnect() {
  36258. if ( this._connected === false ) {
  36259. return;
  36260. }
  36261. if ( this.filters.length > 0 ) {
  36262. this.source.disconnect( this.filters[ 0 ] );
  36263. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36264. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  36265. }
  36266. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  36267. } else {
  36268. this.source.disconnect( this.getOutput() );
  36269. }
  36270. this._connected = false;
  36271. return this;
  36272. }
  36273. /**
  36274. * Returns the current set filters.
  36275. *
  36276. * @return {Array<AudioNode>} The list of filters.
  36277. */
  36278. getFilters() {
  36279. return this.filters;
  36280. }
  36281. /**
  36282. * Sets an array of filters and connects them with the audio source.
  36283. *
  36284. * @param {Array<AudioNode>} [value] - A list of filters.
  36285. * @return {Audio} A reference to this instance.
  36286. */
  36287. setFilters( value ) {
  36288. if ( ! value ) value = [];
  36289. if ( this._connected === true ) {
  36290. this.disconnect();
  36291. this.filters = value.slice();
  36292. this.connect();
  36293. } else {
  36294. this.filters = value.slice();
  36295. }
  36296. return this;
  36297. }
  36298. /**
  36299. * Defines the detuning of oscillation in cents.
  36300. *
  36301. * @param {number} value - The detuning of oscillation in cents.
  36302. * @return {Audio} A reference to this instance.
  36303. */
  36304. setDetune( value ) {
  36305. this.detune = value;
  36306. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  36307. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  36308. }
  36309. return this;
  36310. }
  36311. /**
  36312. * Returns the detuning of oscillation in cents.
  36313. *
  36314. * @return {number} The detuning of oscillation in cents.
  36315. */
  36316. getDetune() {
  36317. return this.detune;
  36318. }
  36319. /**
  36320. * Returns the first filter in the list of filters.
  36321. *
  36322. * @return {AudioNode|undefined} The first filter in the list of filters.
  36323. */
  36324. getFilter() {
  36325. return this.getFilters()[ 0 ];
  36326. }
  36327. /**
  36328. * Applies a single filter node to the audio.
  36329. *
  36330. * @param {AudioNode} [filter] - The filter to set.
  36331. * @return {Audio} A reference to this instance.
  36332. */
  36333. setFilter( filter ) {
  36334. return this.setFilters( filter ? [ filter ] : [] );
  36335. }
  36336. /**
  36337. * Sets the playback rate.
  36338. *
  36339. * Can only be used with compatible audio sources that allow playback control.
  36340. *
  36341. * @param {number} [value] - The playback rate to set.
  36342. * @return {Audio|undefined} A reference to this instance.
  36343. */
  36344. setPlaybackRate( value ) {
  36345. if ( this.hasPlaybackControl === false ) {
  36346. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36347. return;
  36348. }
  36349. this.playbackRate = value;
  36350. if ( this.isPlaying === true ) {
  36351. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  36352. }
  36353. return this;
  36354. }
  36355. /**
  36356. * Returns the current playback rate.
  36357. * @return {number} The playback rate.
  36358. */
  36359. getPlaybackRate() {
  36360. return this.playbackRate;
  36361. }
  36362. /**
  36363. * Automatically called when playback finished.
  36364. */
  36365. onEnded() {
  36366. this.isPlaying = false;
  36367. this._progress = 0;
  36368. }
  36369. /**
  36370. * Returns the loop flag.
  36371. *
  36372. * Can only be used with compatible audio sources that allow playback control.
  36373. *
  36374. * @return {boolean} Whether the audio should loop or not.
  36375. */
  36376. getLoop() {
  36377. if ( this.hasPlaybackControl === false ) {
  36378. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36379. return false;
  36380. }
  36381. return this.loop;
  36382. }
  36383. /**
  36384. * Sets the loop flag.
  36385. *
  36386. * Can only be used with compatible audio sources that allow playback control.
  36387. *
  36388. * @param {boolean} value - Whether the audio should loop or not.
  36389. * @return {Audio|undefined} A reference to this instance.
  36390. */
  36391. setLoop( value ) {
  36392. if ( this.hasPlaybackControl === false ) {
  36393. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36394. return;
  36395. }
  36396. this.loop = value;
  36397. if ( this.isPlaying === true ) {
  36398. this.source.loop = this.loop;
  36399. }
  36400. return this;
  36401. }
  36402. /**
  36403. * Sets the loop start value which defines where in the audio buffer the replay should
  36404. * start, in seconds.
  36405. *
  36406. * @param {number} value - The loop start value.
  36407. * @return {Audio} A reference to this instance.
  36408. */
  36409. setLoopStart( value ) {
  36410. this.loopStart = value;
  36411. return this;
  36412. }
  36413. /**
  36414. * Sets the loop end value which defines where in the audio buffer the replay should
  36415. * stop, in seconds.
  36416. *
  36417. * @param {number} value - The loop end value.
  36418. * @return {Audio} A reference to this instance.
  36419. */
  36420. setLoopEnd( value ) {
  36421. this.loopEnd = value;
  36422. return this;
  36423. }
  36424. /**
  36425. * Returns the volume.
  36426. *
  36427. * @return {number} The volume.
  36428. */
  36429. getVolume() {
  36430. return this.gain.gain.value;
  36431. }
  36432. /**
  36433. * Sets the volume.
  36434. *
  36435. * @param {number} value - The volume to set.
  36436. * @return {Audio} A reference to this instance.
  36437. */
  36438. setVolume( value ) {
  36439. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36440. return this;
  36441. }
  36442. copy( source, recursive ) {
  36443. super.copy( source, recursive );
  36444. if ( source.sourceType !== 'buffer' ) {
  36445. console.warn( 'THREE.Audio: Audio source type cannot be copied.' );
  36446. return this;
  36447. }
  36448. this.autoplay = source.autoplay;
  36449. this.buffer = source.buffer;
  36450. this.detune = source.detune;
  36451. this.loop = source.loop;
  36452. this.loopStart = source.loopStart;
  36453. this.loopEnd = source.loopEnd;
  36454. this.offset = source.offset;
  36455. this.duration = source.duration;
  36456. this.playbackRate = source.playbackRate;
  36457. this.hasPlaybackControl = source.hasPlaybackControl;
  36458. this.sourceType = source.sourceType;
  36459. this.filters = source.filters.slice();
  36460. return this;
  36461. }
  36462. clone( recursive ) {
  36463. return new this.constructor( this.listener ).copy( this, recursive );
  36464. }
  36465. }
  36466. const _position = /*@__PURE__*/ new Vector3();
  36467. const _quaternion = /*@__PURE__*/ new Quaternion();
  36468. const _scale = /*@__PURE__*/ new Vector3();
  36469. const _orientation = /*@__PURE__*/ new Vector3();
  36470. /**
  36471. * Represents a positional audio object.
  36472. *
  36473. * ```js
  36474. * // create an AudioListener and add it to the camera
  36475. * const listener = new THREE.AudioListener();
  36476. * camera.add( listener );
  36477. *
  36478. * // create the PositionalAudio object (passing in the listener)
  36479. * const sound = new THREE.PositionalAudio( listener );
  36480. *
  36481. * // load a sound and set it as the PositionalAudio object's buffer
  36482. * const audioLoader = new THREE.AudioLoader();
  36483. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  36484. * sound.setBuffer( buffer );
  36485. * sound.setRefDistance( 20 );
  36486. * sound.play();
  36487. * });
  36488. *
  36489. * // create an object for the sound to play from
  36490. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  36491. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  36492. * const mesh = new THREE.Mesh( sphere, material );
  36493. * scene.add( mesh );
  36494. *
  36495. * // finally add the sound to the mesh
  36496. * mesh.add( sound );
  36497. *
  36498. * @augments Audio
  36499. */
  36500. class PositionalAudio extends Audio {
  36501. /**
  36502. * Constructs a positional audio.
  36503. *
  36504. * @param {AudioListener} listener - The global audio listener.
  36505. */
  36506. constructor( listener ) {
  36507. super( listener );
  36508. /**
  36509. * The panner node represents the location, direction, and behavior of an audio
  36510. * source in 3D space.
  36511. *
  36512. * @type {PannerNode}
  36513. * @readonly
  36514. */
  36515. this.panner = this.context.createPanner();
  36516. this.panner.panningModel = 'HRTF';
  36517. this.panner.connect( this.gain );
  36518. }
  36519. connect() {
  36520. super.connect();
  36521. this.panner.connect( this.gain );
  36522. return this;
  36523. }
  36524. disconnect() {
  36525. super.disconnect();
  36526. this.panner.disconnect( this.gain );
  36527. return this;
  36528. }
  36529. getOutput() {
  36530. return this.panner;
  36531. }
  36532. /**
  36533. * Returns the current reference distance.
  36534. *
  36535. * @return {number} The reference distance.
  36536. */
  36537. getRefDistance() {
  36538. return this.panner.refDistance;
  36539. }
  36540. /**
  36541. * Defines the reference distance for reducing volume as the audio source moves
  36542. * further from the listener – i.e. the distance at which the volume reduction
  36543. * starts taking effect.
  36544. *
  36545. * @param {number} value - The reference distance to set.
  36546. * @return {PositionalAudio} A reference to this instance.
  36547. */
  36548. setRefDistance( value ) {
  36549. this.panner.refDistance = value;
  36550. return this;
  36551. }
  36552. /**
  36553. * Returns the current rolloff factor.
  36554. *
  36555. * @return {number} The rolloff factor.
  36556. */
  36557. getRolloffFactor() {
  36558. return this.panner.rolloffFactor;
  36559. }
  36560. /**
  36561. * Defines how quickly the volume is reduced as the source moves away from the listener.
  36562. *
  36563. * @param {number} value - The rolloff factor.
  36564. * @return {PositionalAudio} A reference to this instance.
  36565. */
  36566. setRolloffFactor( value ) {
  36567. this.panner.rolloffFactor = value;
  36568. return this;
  36569. }
  36570. /**
  36571. * Returns the current distance model.
  36572. *
  36573. * @return {('linear'|'inverse'|'exponential')} The distance model.
  36574. */
  36575. getDistanceModel() {
  36576. return this.panner.distanceModel;
  36577. }
  36578. /**
  36579. * Defines which algorithm to use to reduce the volume of the audio source
  36580. * as it moves away from the listener.
  36581. *
  36582. * Read [the spec]{@link https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype}
  36583. * for more details.
  36584. *
  36585. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  36586. * @return {PositionalAudio} A reference to this instance.
  36587. */
  36588. setDistanceModel( value ) {
  36589. this.panner.distanceModel = value;
  36590. return this;
  36591. }
  36592. /**
  36593. * Returns the current max distance.
  36594. *
  36595. * @return {number} The max distance.
  36596. */
  36597. getMaxDistance() {
  36598. return this.panner.maxDistance;
  36599. }
  36600. /**
  36601. * Defines the maximum distance between the audio source and the listener,
  36602. * after which the volume is not reduced any further.
  36603. *
  36604. * This value is used only by the `linear` distance model.
  36605. *
  36606. * @param {number} value - The max distance.
  36607. * @return {PositionalAudio} A reference to this instance.
  36608. */
  36609. setMaxDistance( value ) {
  36610. this.panner.maxDistance = value;
  36611. return this;
  36612. }
  36613. /**
  36614. * Sets the directional cone in which the audio can be listened.
  36615. *
  36616. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  36617. * @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.
  36618. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  36619. * @return {PositionalAudio} A reference to this instance.
  36620. */
  36621. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  36622. this.panner.coneInnerAngle = coneInnerAngle;
  36623. this.panner.coneOuterAngle = coneOuterAngle;
  36624. this.panner.coneOuterGain = coneOuterGain;
  36625. return this;
  36626. }
  36627. updateMatrixWorld( force ) {
  36628. super.updateMatrixWorld( force );
  36629. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  36630. this.matrixWorld.decompose( _position, _quaternion, _scale );
  36631. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  36632. const panner = this.panner;
  36633. if ( panner.positionX ) {
  36634. // code path for Chrome and Firefox (see #14393)
  36635. const endTime = this.context.currentTime + this.listener.timeDelta;
  36636. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  36637. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  36638. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  36639. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  36640. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  36641. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  36642. } else {
  36643. panner.setPosition( _position.x, _position.y, _position.z );
  36644. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  36645. }
  36646. }
  36647. }
  36648. /**
  36649. * This class can be used to analyse audio data.
  36650. *
  36651. * ```js
  36652. * // create an AudioListener and add it to the camera
  36653. * const listener = new THREE.AudioListener();
  36654. * camera.add( listener );
  36655. *
  36656. * // create an Audio source
  36657. * const sound = new THREE.Audio( listener );
  36658. *
  36659. * // load a sound and set it as the Audio object's buffer
  36660. * const audioLoader = new THREE.AudioLoader();
  36661. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36662. * sound.setBuffer( buffer );
  36663. * sound.setLoop(true);
  36664. * sound.setVolume(0.5);
  36665. * sound.play();
  36666. * });
  36667. *
  36668. * // create an AudioAnalyser, passing in the sound and desired fftSize
  36669. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  36670. *
  36671. * // get the average frequency of the sound
  36672. * const data = analyser.getAverageFrequency();
  36673. * ```
  36674. */
  36675. class AudioAnalyser {
  36676. /**
  36677. * Constructs a new audio analyzer.
  36678. *
  36679. * @param {Audio} audio - The audio to analyze.
  36680. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  36681. */
  36682. constructor( audio, fftSize = 2048 ) {
  36683. /**
  36684. * The global audio listener.
  36685. *
  36686. * @type {AnalyserNode}
  36687. */
  36688. this.analyser = audio.context.createAnalyser();
  36689. this.analyser.fftSize = fftSize;
  36690. /**
  36691. * Holds the analyzed data.
  36692. *
  36693. * @type {Uint8Array}
  36694. */
  36695. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  36696. audio.getOutput().connect( this.analyser );
  36697. }
  36698. /**
  36699. * Returns an array with frequency data of the audio.
  36700. *
  36701. * Each item in the array represents the decibel value for a specific frequency.
  36702. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  36703. * For example, for 48000 sample rate, the last item of the array will represent
  36704. * the decibel value for 24000 Hz.
  36705. *
  36706. * @return {Uint8Array} The frequency data.
  36707. */
  36708. getFrequencyData() {
  36709. this.analyser.getByteFrequencyData( this.data );
  36710. return this.data;
  36711. }
  36712. /**
  36713. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  36714. *
  36715. * @return {number} The average frequency.
  36716. */
  36717. getAverageFrequency() {
  36718. let value = 0;
  36719. const data = this.getFrequencyData();
  36720. for ( let i = 0; i < data.length; i ++ ) {
  36721. value += data[ i ];
  36722. }
  36723. return value / data.length;
  36724. }
  36725. }
  36726. /**
  36727. * Buffered scene graph property that allows weighted accumulation; used internally.
  36728. */
  36729. class PropertyMixer {
  36730. /**
  36731. * Constructs a new property mixer.
  36732. *
  36733. * @param {PropertyBinding} binding - The property binding.
  36734. * @param {string} typeName - The keyframe track type name.
  36735. * @param {number} valueSize - The keyframe track value size.
  36736. */
  36737. constructor( binding, typeName, valueSize ) {
  36738. /**
  36739. * The property binding.
  36740. *
  36741. * @type {PropertyBinding}
  36742. */
  36743. this.binding = binding;
  36744. /**
  36745. * The keyframe track value size.
  36746. *
  36747. * @type {number}
  36748. */
  36749. this.valueSize = valueSize;
  36750. let mixFunction,
  36751. mixFunctionAdditive,
  36752. setIdentity;
  36753. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  36754. //
  36755. // interpolators can use .buffer as their .result
  36756. // the data then goes to 'incoming'
  36757. //
  36758. // 'accu0' and 'accu1' are used frame-interleaved for
  36759. // the cumulative result and are compared to detect
  36760. // changes
  36761. //
  36762. // 'orig' stores the original state of the property
  36763. //
  36764. // 'add' is used for additive cumulative results
  36765. //
  36766. // 'work' is optional and is only present for quaternion types. It is used
  36767. // to store intermediate quaternion multiplication results
  36768. switch ( typeName ) {
  36769. case 'quaternion':
  36770. mixFunction = this._slerp;
  36771. mixFunctionAdditive = this._slerpAdditive;
  36772. setIdentity = this._setAdditiveIdentityQuaternion;
  36773. this.buffer = new Float64Array( valueSize * 6 );
  36774. this._workIndex = 5;
  36775. break;
  36776. case 'string':
  36777. case 'bool':
  36778. mixFunction = this._select;
  36779. // Use the regular mix function and for additive on these types,
  36780. // additive is not relevant for non-numeric types
  36781. mixFunctionAdditive = this._select;
  36782. setIdentity = this._setAdditiveIdentityOther;
  36783. this.buffer = new Array( valueSize * 5 );
  36784. break;
  36785. default:
  36786. mixFunction = this._lerp;
  36787. mixFunctionAdditive = this._lerpAdditive;
  36788. setIdentity = this._setAdditiveIdentityNumeric;
  36789. this.buffer = new Float64Array( valueSize * 5 );
  36790. }
  36791. this._mixBufferRegion = mixFunction;
  36792. this._mixBufferRegionAdditive = mixFunctionAdditive;
  36793. this._setIdentity = setIdentity;
  36794. this._origIndex = 3;
  36795. this._addIndex = 4;
  36796. /**
  36797. * TODO
  36798. *
  36799. * @type {number}
  36800. * @default 0
  36801. */
  36802. this.cumulativeWeight = 0;
  36803. /**
  36804. * TODO
  36805. *
  36806. * @type {number}
  36807. * @default 0
  36808. */
  36809. this.cumulativeWeightAdditive = 0;
  36810. /**
  36811. * TODO
  36812. *
  36813. * @type {number}
  36814. * @default 0
  36815. */
  36816. this.useCount = 0;
  36817. /**
  36818. * TODO
  36819. *
  36820. * @type {number}
  36821. * @default 0
  36822. */
  36823. this.referenceCount = 0;
  36824. }
  36825. /**
  36826. * Accumulates data in the `incoming` region into `accu<i>`.
  36827. *
  36828. * @param {number} accuIndex - The accumulation index.
  36829. * @param {number} weight - The weight.
  36830. */
  36831. accumulate( accuIndex, weight ) {
  36832. // note: happily accumulating nothing when weight = 0, the caller knows
  36833. // the weight and shouldn't have made the call in the first place
  36834. const buffer = this.buffer,
  36835. stride = this.valueSize,
  36836. offset = accuIndex * stride + stride;
  36837. let currentWeight = this.cumulativeWeight;
  36838. if ( currentWeight === 0 ) {
  36839. // accuN := incoming * weight
  36840. for ( let i = 0; i !== stride; ++ i ) {
  36841. buffer[ offset + i ] = buffer[ i ];
  36842. }
  36843. currentWeight = weight;
  36844. } else {
  36845. // accuN := accuN + incoming * weight
  36846. currentWeight += weight;
  36847. const mix = weight / currentWeight;
  36848. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  36849. }
  36850. this.cumulativeWeight = currentWeight;
  36851. }
  36852. /**
  36853. * Accumulates data in the `incoming` region into `add`.
  36854. *
  36855. * @param {number} weight - The weight.
  36856. */
  36857. accumulateAdditive( weight ) {
  36858. const buffer = this.buffer,
  36859. stride = this.valueSize,
  36860. offset = stride * this._addIndex;
  36861. if ( this.cumulativeWeightAdditive === 0 ) {
  36862. // add = identity
  36863. this._setIdentity();
  36864. }
  36865. // add := add + incoming * weight
  36866. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  36867. this.cumulativeWeightAdditive += weight;
  36868. }
  36869. /**
  36870. * Applies the state of `accu<i>` to the binding when accus differ.
  36871. *
  36872. * @param {number} accuIndex - The accumulation index.
  36873. */
  36874. apply( accuIndex ) {
  36875. const stride = this.valueSize,
  36876. buffer = this.buffer,
  36877. offset = accuIndex * stride + stride,
  36878. weight = this.cumulativeWeight,
  36879. weightAdditive = this.cumulativeWeightAdditive,
  36880. binding = this.binding;
  36881. this.cumulativeWeight = 0;
  36882. this.cumulativeWeightAdditive = 0;
  36883. if ( weight < 1 ) {
  36884. // accuN := accuN + original * ( 1 - cumulativeWeight )
  36885. const originalValueOffset = stride * this._origIndex;
  36886. this._mixBufferRegion(
  36887. buffer, offset, originalValueOffset, 1 - weight, stride );
  36888. }
  36889. if ( weightAdditive > 0 ) {
  36890. // accuN := accuN + additive accuN
  36891. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  36892. }
  36893. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  36894. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  36895. // value has changed -> update scene graph
  36896. binding.setValue( buffer, offset );
  36897. break;
  36898. }
  36899. }
  36900. }
  36901. /**
  36902. * Remembers the state of the bound property and copy it to both accus.
  36903. */
  36904. saveOriginalState() {
  36905. const binding = this.binding;
  36906. const buffer = this.buffer,
  36907. stride = this.valueSize,
  36908. originalValueOffset = stride * this._origIndex;
  36909. binding.getValue( buffer, originalValueOffset );
  36910. // accu[0..1] := orig -- initially detect changes against the original
  36911. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  36912. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  36913. }
  36914. // Add to identity for additive
  36915. this._setIdentity();
  36916. this.cumulativeWeight = 0;
  36917. this.cumulativeWeightAdditive = 0;
  36918. }
  36919. /**
  36920. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  36921. */
  36922. restoreOriginalState() {
  36923. const originalValueOffset = this.valueSize * 3;
  36924. this.binding.setValue( this.buffer, originalValueOffset );
  36925. }
  36926. // internals
  36927. _setAdditiveIdentityNumeric() {
  36928. const startIndex = this._addIndex * this.valueSize;
  36929. const endIndex = startIndex + this.valueSize;
  36930. for ( let i = startIndex; i < endIndex; i ++ ) {
  36931. this.buffer[ i ] = 0;
  36932. }
  36933. }
  36934. _setAdditiveIdentityQuaternion() {
  36935. this._setAdditiveIdentityNumeric();
  36936. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  36937. }
  36938. _setAdditiveIdentityOther() {
  36939. const startIndex = this._origIndex * this.valueSize;
  36940. const targetIndex = this._addIndex * this.valueSize;
  36941. for ( let i = 0; i < this.valueSize; i ++ ) {
  36942. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  36943. }
  36944. }
  36945. // mix functions
  36946. _select( buffer, dstOffset, srcOffset, t, stride ) {
  36947. if ( t >= 0.5 ) {
  36948. for ( let i = 0; i !== stride; ++ i ) {
  36949. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  36950. }
  36951. }
  36952. }
  36953. _slerp( buffer, dstOffset, srcOffset, t ) {
  36954. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  36955. }
  36956. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  36957. const workOffset = this._workIndex * stride;
  36958. // Store result in intermediate buffer offset
  36959. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  36960. // Slerp to the intermediate result
  36961. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  36962. }
  36963. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  36964. const s = 1 - t;
  36965. for ( let i = 0; i !== stride; ++ i ) {
  36966. const j = dstOffset + i;
  36967. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  36968. }
  36969. }
  36970. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  36971. for ( let i = 0; i !== stride; ++ i ) {
  36972. const j = dstOffset + i;
  36973. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  36974. }
  36975. }
  36976. }
  36977. // Characters [].:/ are reserved for track binding syntax.
  36978. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  36979. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  36980. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  36981. // only latin characters, and the unicode \p{L} is not yet supported. So
  36982. // instead, we exclude reserved characters and match everything else.
  36983. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  36984. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  36985. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  36986. // be matched to parse the rest of the track name.
  36987. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  36988. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  36989. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  36990. // Object on target node, and accessor. May not contain reserved
  36991. // characters. Accessor may contain any character except closing bracket.
  36992. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  36993. // Property and accessor. May not contain reserved characters. Accessor may
  36994. // contain any non-bracket characters.
  36995. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  36996. const _trackRe = new RegExp( ''
  36997. + '^'
  36998. + _directoryRe
  36999. + _nodeRe
  37000. + _objectRe
  37001. + _propertyRe
  37002. + '$'
  37003. );
  37004. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  37005. class Composite {
  37006. constructor( targetGroup, path, optionalParsedPath ) {
  37007. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  37008. this._targetGroup = targetGroup;
  37009. this._bindings = targetGroup.subscribe_( path, parsedPath );
  37010. }
  37011. getValue( array, offset ) {
  37012. this.bind(); // bind all binding
  37013. const firstValidIndex = this._targetGroup.nCachedObjects_,
  37014. binding = this._bindings[ firstValidIndex ];
  37015. // and only call .getValue on the first
  37016. if ( binding !== undefined ) binding.getValue( array, offset );
  37017. }
  37018. setValue( array, offset ) {
  37019. const bindings = this._bindings;
  37020. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37021. bindings[ i ].setValue( array, offset );
  37022. }
  37023. }
  37024. bind() {
  37025. const bindings = this._bindings;
  37026. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37027. bindings[ i ].bind();
  37028. }
  37029. }
  37030. unbind() {
  37031. const bindings = this._bindings;
  37032. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37033. bindings[ i ].unbind();
  37034. }
  37035. }
  37036. }
  37037. // Note: This class uses a State pattern on a per-method basis:
  37038. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  37039. // prototype version of these methods with one that represents
  37040. // the bound state. When the property is not found, the methods
  37041. // become no-ops.
  37042. /**
  37043. * This holds a reference to a real property in the scene graph; used internally.
  37044. */
  37045. class PropertyBinding {
  37046. /**
  37047. * Constructs a new property binding.
  37048. *
  37049. * @param {Object} rootNode - The root node.
  37050. * @param {string} path - The path.
  37051. * @param {?Object} [parsedPath] - The parsed path.
  37052. */
  37053. constructor( rootNode, path, parsedPath ) {
  37054. /**
  37055. * The object path to the animated property.
  37056. *
  37057. * @type {string}
  37058. */
  37059. this.path = path;
  37060. /**
  37061. * An object holding information about the path.
  37062. *
  37063. * @type {Object}
  37064. */
  37065. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  37066. /**
  37067. * The object owns the animated property.
  37068. *
  37069. * @type {?Object}
  37070. */
  37071. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  37072. /**
  37073. * The root node.
  37074. *
  37075. * @type {Object3D|Skeleton}
  37076. */
  37077. this.rootNode = rootNode;
  37078. // initial state of these methods that calls 'bind'
  37079. this.getValue = this._getValue_unbound;
  37080. this.setValue = this._setValue_unbound;
  37081. }
  37082. /**
  37083. * Factory method for creating a property binding from the given parameters.
  37084. *
  37085. * @static
  37086. * @param {Object} root - The root node.
  37087. * @param {string} path - The path.
  37088. * @param {?Object} [parsedPath] - The parsed path.
  37089. * @return {PropertyBinding|Composite} The created property binding or composite.
  37090. */
  37091. static create( root, path, parsedPath ) {
  37092. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  37093. return new PropertyBinding( root, path, parsedPath );
  37094. } else {
  37095. return new PropertyBinding.Composite( root, path, parsedPath );
  37096. }
  37097. }
  37098. /**
  37099. * Replaces spaces with underscores and removes unsupported characters from
  37100. * node names, to ensure compatibility with parseTrackName().
  37101. *
  37102. * @param {string} name - Node name to be sanitized.
  37103. * @return {string} The sanitized node name.
  37104. */
  37105. static sanitizeNodeName( name ) {
  37106. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  37107. }
  37108. /**
  37109. * Parses the given track name (an object path to an animated property) and
  37110. * returns an object with information about the path. Matches strings in the following forms:
  37111. *
  37112. * - nodeName.property
  37113. * - nodeName.property[accessor]
  37114. * - nodeName.material.property[accessor]
  37115. * - uuid.property[accessor]
  37116. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  37117. * - parentName/nodeName.property
  37118. * - parentName/parentName/nodeName.property[index]
  37119. * - .bone[Armature.DEF_cog].position
  37120. * - scene:helium_balloon_model:helium_balloon_model.position
  37121. *
  37122. * @static
  37123. * @param {string} trackName - The track name to parse.
  37124. * @return {Object} The parsed track name as an object.
  37125. */
  37126. static parseTrackName( trackName ) {
  37127. const matches = _trackRe.exec( trackName );
  37128. if ( matches === null ) {
  37129. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  37130. }
  37131. const results = {
  37132. // directoryName: matches[ 1 ], // (tschw) currently unused
  37133. nodeName: matches[ 2 ],
  37134. objectName: matches[ 3 ],
  37135. objectIndex: matches[ 4 ],
  37136. propertyName: matches[ 5 ], // required
  37137. propertyIndex: matches[ 6 ]
  37138. };
  37139. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  37140. if ( lastDot !== undefined && lastDot !== -1 ) {
  37141. const objectName = results.nodeName.substring( lastDot + 1 );
  37142. // Object names must be checked against an allowlist. Otherwise, there
  37143. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  37144. // 'bar' could be the objectName, or part of a nodeName (which can
  37145. // include '.' characters).
  37146. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  37147. results.nodeName = results.nodeName.substring( 0, lastDot );
  37148. results.objectName = objectName;
  37149. }
  37150. }
  37151. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  37152. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  37153. }
  37154. return results;
  37155. }
  37156. /**
  37157. * Searches for a node in the hierarchy of the given root object by the given
  37158. * node name.
  37159. *
  37160. * @static
  37161. * @param {Object} root - The root object.
  37162. * @param {string|number} nodeName - The name of the node.
  37163. * @return {?Object} The found node. Returns `null` if no object was found.
  37164. */
  37165. static findNode( root, nodeName ) {
  37166. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  37167. return root;
  37168. }
  37169. // search into skeleton bones.
  37170. if ( root.skeleton ) {
  37171. const bone = root.skeleton.getBoneByName( nodeName );
  37172. if ( bone !== undefined ) {
  37173. return bone;
  37174. }
  37175. }
  37176. // search into node subtree.
  37177. if ( root.children ) {
  37178. const searchNodeSubtree = function ( children ) {
  37179. for ( let i = 0; i < children.length; i ++ ) {
  37180. const childNode = children[ i ];
  37181. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  37182. return childNode;
  37183. }
  37184. const result = searchNodeSubtree( childNode.children );
  37185. if ( result ) return result;
  37186. }
  37187. return null;
  37188. };
  37189. const subTreeNode = searchNodeSubtree( root.children );
  37190. if ( subTreeNode ) {
  37191. return subTreeNode;
  37192. }
  37193. }
  37194. return null;
  37195. }
  37196. // these are used to "bind" a nonexistent property
  37197. _getValue_unavailable() {}
  37198. _setValue_unavailable() {}
  37199. // Getters
  37200. _getValue_direct( buffer, offset ) {
  37201. buffer[ offset ] = this.targetObject[ this.propertyName ];
  37202. }
  37203. _getValue_array( buffer, offset ) {
  37204. const source = this.resolvedProperty;
  37205. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  37206. buffer[ offset ++ ] = source[ i ];
  37207. }
  37208. }
  37209. _getValue_arrayElement( buffer, offset ) {
  37210. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  37211. }
  37212. _getValue_toArray( buffer, offset ) {
  37213. this.resolvedProperty.toArray( buffer, offset );
  37214. }
  37215. // Direct
  37216. _setValue_direct( buffer, offset ) {
  37217. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37218. }
  37219. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  37220. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37221. this.targetObject.needsUpdate = true;
  37222. }
  37223. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37224. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37225. this.targetObject.matrixWorldNeedsUpdate = true;
  37226. }
  37227. // EntireArray
  37228. _setValue_array( buffer, offset ) {
  37229. const dest = this.resolvedProperty;
  37230. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37231. dest[ i ] = buffer[ offset ++ ];
  37232. }
  37233. }
  37234. _setValue_array_setNeedsUpdate( buffer, offset ) {
  37235. const dest = this.resolvedProperty;
  37236. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37237. dest[ i ] = buffer[ offset ++ ];
  37238. }
  37239. this.targetObject.needsUpdate = true;
  37240. }
  37241. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37242. const dest = this.resolvedProperty;
  37243. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37244. dest[ i ] = buffer[ offset ++ ];
  37245. }
  37246. this.targetObject.matrixWorldNeedsUpdate = true;
  37247. }
  37248. // ArrayElement
  37249. _setValue_arrayElement( buffer, offset ) {
  37250. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37251. }
  37252. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  37253. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37254. this.targetObject.needsUpdate = true;
  37255. }
  37256. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37257. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37258. this.targetObject.matrixWorldNeedsUpdate = true;
  37259. }
  37260. // HasToFromArray
  37261. _setValue_fromArray( buffer, offset ) {
  37262. this.resolvedProperty.fromArray( buffer, offset );
  37263. }
  37264. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  37265. this.resolvedProperty.fromArray( buffer, offset );
  37266. this.targetObject.needsUpdate = true;
  37267. }
  37268. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37269. this.resolvedProperty.fromArray( buffer, offset );
  37270. this.targetObject.matrixWorldNeedsUpdate = true;
  37271. }
  37272. _getValue_unbound( targetArray, offset ) {
  37273. this.bind();
  37274. this.getValue( targetArray, offset );
  37275. }
  37276. _setValue_unbound( sourceArray, offset ) {
  37277. this.bind();
  37278. this.setValue( sourceArray, offset );
  37279. }
  37280. /**
  37281. * Creates a getter / setter pair for the property tracked by this binding.
  37282. */
  37283. bind() {
  37284. let targetObject = this.node;
  37285. const parsedPath = this.parsedPath;
  37286. const objectName = parsedPath.objectName;
  37287. const propertyName = parsedPath.propertyName;
  37288. let propertyIndex = parsedPath.propertyIndex;
  37289. if ( ! targetObject ) {
  37290. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  37291. this.node = targetObject;
  37292. }
  37293. // set fail state so we can just 'return' on error
  37294. this.getValue = this._getValue_unavailable;
  37295. this.setValue = this._setValue_unavailable;
  37296. // ensure there is a value node
  37297. if ( ! targetObject ) {
  37298. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  37299. return;
  37300. }
  37301. if ( objectName ) {
  37302. let objectIndex = parsedPath.objectIndex;
  37303. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  37304. switch ( objectName ) {
  37305. case 'materials':
  37306. if ( ! targetObject.material ) {
  37307. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  37308. return;
  37309. }
  37310. if ( ! targetObject.material.materials ) {
  37311. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  37312. return;
  37313. }
  37314. targetObject = targetObject.material.materials;
  37315. break;
  37316. case 'bones':
  37317. if ( ! targetObject.skeleton ) {
  37318. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  37319. return;
  37320. }
  37321. // potential future optimization: skip this if propertyIndex is already an integer
  37322. // and convert the integer string to a true integer.
  37323. targetObject = targetObject.skeleton.bones;
  37324. // support resolving morphTarget names into indices.
  37325. for ( let i = 0; i < targetObject.length; i ++ ) {
  37326. if ( targetObject[ i ].name === objectIndex ) {
  37327. objectIndex = i;
  37328. break;
  37329. }
  37330. }
  37331. break;
  37332. case 'map':
  37333. if ( 'map' in targetObject ) {
  37334. targetObject = targetObject.map;
  37335. break;
  37336. }
  37337. if ( ! targetObject.material ) {
  37338. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  37339. return;
  37340. }
  37341. if ( ! targetObject.material.map ) {
  37342. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  37343. return;
  37344. }
  37345. targetObject = targetObject.material.map;
  37346. break;
  37347. default:
  37348. if ( targetObject[ objectName ] === undefined ) {
  37349. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  37350. return;
  37351. }
  37352. targetObject = targetObject[ objectName ];
  37353. }
  37354. if ( objectIndex !== undefined ) {
  37355. if ( targetObject[ objectIndex ] === undefined ) {
  37356. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  37357. return;
  37358. }
  37359. targetObject = targetObject[ objectIndex ];
  37360. }
  37361. }
  37362. // resolve property
  37363. const nodeProperty = targetObject[ propertyName ];
  37364. if ( nodeProperty === undefined ) {
  37365. const nodeName = parsedPath.nodeName;
  37366. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  37367. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  37368. return;
  37369. }
  37370. // determine versioning scheme
  37371. let versioning = this.Versioning.None;
  37372. this.targetObject = targetObject;
  37373. if ( targetObject.isMaterial === true ) {
  37374. versioning = this.Versioning.NeedsUpdate;
  37375. } else if ( targetObject.isObject3D === true ) {
  37376. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  37377. }
  37378. // determine how the property gets bound
  37379. let bindingType = this.BindingType.Direct;
  37380. if ( propertyIndex !== undefined ) {
  37381. // access a sub element of the property array (only primitives are supported right now)
  37382. if ( propertyName === 'morphTargetInfluences' ) {
  37383. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  37384. // support resolving morphTarget names into indices.
  37385. if ( ! targetObject.geometry ) {
  37386. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  37387. return;
  37388. }
  37389. if ( ! targetObject.geometry.morphAttributes ) {
  37390. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  37391. return;
  37392. }
  37393. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  37394. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  37395. }
  37396. }
  37397. bindingType = this.BindingType.ArrayElement;
  37398. this.resolvedProperty = nodeProperty;
  37399. this.propertyIndex = propertyIndex;
  37400. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  37401. // must use copy for Object3D.Euler/Quaternion
  37402. bindingType = this.BindingType.HasFromToArray;
  37403. this.resolvedProperty = nodeProperty;
  37404. } else if ( Array.isArray( nodeProperty ) ) {
  37405. bindingType = this.BindingType.EntireArray;
  37406. this.resolvedProperty = nodeProperty;
  37407. } else {
  37408. this.propertyName = propertyName;
  37409. }
  37410. // select getter / setter
  37411. this.getValue = this.GetterByBindingType[ bindingType ];
  37412. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  37413. }
  37414. /**
  37415. * Unbinds the property.
  37416. */
  37417. unbind() {
  37418. this.node = null;
  37419. // back to the prototype version of getValue / setValue
  37420. // note: avoiding to mutate the shape of 'this' via 'delete'
  37421. this.getValue = this._getValue_unbound;
  37422. this.setValue = this._setValue_unbound;
  37423. }
  37424. }
  37425. PropertyBinding.Composite = Composite;
  37426. PropertyBinding.prototype.BindingType = {
  37427. Direct: 0,
  37428. EntireArray: 1,
  37429. ArrayElement: 2,
  37430. HasFromToArray: 3
  37431. };
  37432. PropertyBinding.prototype.Versioning = {
  37433. None: 0,
  37434. NeedsUpdate: 1,
  37435. MatrixWorldNeedsUpdate: 2
  37436. };
  37437. PropertyBinding.prototype.GetterByBindingType = [
  37438. PropertyBinding.prototype._getValue_direct,
  37439. PropertyBinding.prototype._getValue_array,
  37440. PropertyBinding.prototype._getValue_arrayElement,
  37441. PropertyBinding.prototype._getValue_toArray,
  37442. ];
  37443. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  37444. [
  37445. // Direct
  37446. PropertyBinding.prototype._setValue_direct,
  37447. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  37448. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  37449. ], [
  37450. // EntireArray
  37451. PropertyBinding.prototype._setValue_array,
  37452. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  37453. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  37454. ], [
  37455. // ArrayElement
  37456. PropertyBinding.prototype._setValue_arrayElement,
  37457. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  37458. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  37459. ], [
  37460. // HasToFromArray
  37461. PropertyBinding.prototype._setValue_fromArray,
  37462. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  37463. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  37464. ]
  37465. ];
  37466. /**
  37467. * A group of objects that receives a shared animation state.
  37468. *
  37469. * Usage:
  37470. *
  37471. * - Add objects you would otherwise pass as 'root' to the
  37472. * constructor or the .clipAction method of AnimationMixer.
  37473. * - Instead pass this object as 'root'.
  37474. * - You can also add and remove objects later when the mixer is running.
  37475. *
  37476. * Note:
  37477. *
  37478. * - Objects of this class appear as one object to the mixer,
  37479. * so cache control of the individual objects must be done on the group.
  37480. *
  37481. * Limitation:
  37482. *
  37483. * - The animated properties must be compatible among the all objects in the group.
  37484. * - A single property can either be controlled through a target group or directly, but not both.
  37485. */
  37486. class AnimationObjectGroup {
  37487. /**
  37488. * Constructs a new animation group.
  37489. *
  37490. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  37491. */
  37492. constructor() {
  37493. /**
  37494. * This flag can be used for type testing.
  37495. *
  37496. * @type {boolean}
  37497. * @readonly
  37498. * @default true
  37499. */
  37500. this.isAnimationObjectGroup = true;
  37501. /**
  37502. * The UUID of the 3D object.
  37503. *
  37504. * @type {string}
  37505. * @readonly
  37506. */
  37507. this.uuid = generateUUID();
  37508. // cached objects followed by the active ones
  37509. this._objects = Array.prototype.slice.call( arguments );
  37510. this.nCachedObjects_ = 0; // threshold
  37511. // note: read by PropertyBinding.Composite
  37512. const indices = {};
  37513. this._indicesByUUID = indices; // for bookkeeping
  37514. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37515. indices[ arguments[ i ].uuid ] = i;
  37516. }
  37517. this._paths = []; // inside: string
  37518. this._parsedPaths = []; // inside: { we don't care, here }
  37519. this._bindings = []; // inside: Array< PropertyBinding >
  37520. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  37521. const scope = this;
  37522. this.stats = {
  37523. objects: {
  37524. get total() {
  37525. return scope._objects.length;
  37526. },
  37527. get inUse() {
  37528. return this.total - scope.nCachedObjects_;
  37529. }
  37530. },
  37531. get bindingsPerObject() {
  37532. return scope._bindings.length;
  37533. }
  37534. };
  37535. }
  37536. /**
  37537. * Adds an arbitrary number of objects to this animation group.
  37538. *
  37539. * @param {...Object3D} arguments - The 3D objects to add.
  37540. */
  37541. add() {
  37542. const objects = this._objects,
  37543. indicesByUUID = this._indicesByUUID,
  37544. paths = this._paths,
  37545. parsedPaths = this._parsedPaths,
  37546. bindings = this._bindings,
  37547. nBindings = bindings.length;
  37548. let knownObject = undefined,
  37549. nObjects = objects.length,
  37550. nCachedObjects = this.nCachedObjects_;
  37551. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37552. const object = arguments[ i ],
  37553. uuid = object.uuid;
  37554. let index = indicesByUUID[ uuid ];
  37555. if ( index === undefined ) {
  37556. // unknown object -> add it to the ACTIVE region
  37557. index = nObjects ++;
  37558. indicesByUUID[ uuid ] = index;
  37559. objects.push( object );
  37560. // accounting is done, now do the same for all bindings
  37561. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37562. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  37563. }
  37564. } else if ( index < nCachedObjects ) {
  37565. knownObject = objects[ index ];
  37566. // move existing object to the ACTIVE region
  37567. const firstActiveIndex = -- nCachedObjects,
  37568. lastCachedObject = objects[ firstActiveIndex ];
  37569. indicesByUUID[ lastCachedObject.uuid ] = index;
  37570. objects[ index ] = lastCachedObject;
  37571. indicesByUUID[ uuid ] = firstActiveIndex;
  37572. objects[ firstActiveIndex ] = object;
  37573. // accounting is done, now do the same for all bindings
  37574. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37575. const bindingsForPath = bindings[ j ],
  37576. lastCached = bindingsForPath[ firstActiveIndex ];
  37577. let binding = bindingsForPath[ index ];
  37578. bindingsForPath[ index ] = lastCached;
  37579. if ( binding === undefined ) {
  37580. // since we do not bother to create new bindings
  37581. // for objects that are cached, the binding may
  37582. // or may not exist
  37583. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  37584. }
  37585. bindingsForPath[ firstActiveIndex ] = binding;
  37586. }
  37587. } else if ( objects[ index ] !== knownObject ) {
  37588. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  37589. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  37590. } // else the object is already where we want it to be
  37591. } // for arguments
  37592. this.nCachedObjects_ = nCachedObjects;
  37593. }
  37594. /**
  37595. * Removes an arbitrary number of objects to this animation group
  37596. *
  37597. * @param {...Object3D} arguments - The 3D objects to remove.
  37598. */
  37599. remove() {
  37600. const objects = this._objects,
  37601. indicesByUUID = this._indicesByUUID,
  37602. bindings = this._bindings,
  37603. nBindings = bindings.length;
  37604. let nCachedObjects = this.nCachedObjects_;
  37605. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37606. const object = arguments[ i ],
  37607. uuid = object.uuid,
  37608. index = indicesByUUID[ uuid ];
  37609. if ( index !== undefined && index >= nCachedObjects ) {
  37610. // move existing object into the CACHED region
  37611. const lastCachedIndex = nCachedObjects ++,
  37612. firstActiveObject = objects[ lastCachedIndex ];
  37613. indicesByUUID[ firstActiveObject.uuid ] = index;
  37614. objects[ index ] = firstActiveObject;
  37615. indicesByUUID[ uuid ] = lastCachedIndex;
  37616. objects[ lastCachedIndex ] = object;
  37617. // accounting is done, now do the same for all bindings
  37618. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37619. const bindingsForPath = bindings[ j ],
  37620. firstActive = bindingsForPath[ lastCachedIndex ],
  37621. binding = bindingsForPath[ index ];
  37622. bindingsForPath[ index ] = firstActive;
  37623. bindingsForPath[ lastCachedIndex ] = binding;
  37624. }
  37625. }
  37626. } // for arguments
  37627. this.nCachedObjects_ = nCachedObjects;
  37628. }
  37629. /**
  37630. * Deallocates all memory resources for the passed 3D objects of this animation group.
  37631. *
  37632. * @param {...Object3D} arguments - The 3D objects to uncache.
  37633. */
  37634. uncache() {
  37635. const objects = this._objects,
  37636. indicesByUUID = this._indicesByUUID,
  37637. bindings = this._bindings,
  37638. nBindings = bindings.length;
  37639. let nCachedObjects = this.nCachedObjects_,
  37640. nObjects = objects.length;
  37641. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37642. const object = arguments[ i ],
  37643. uuid = object.uuid,
  37644. index = indicesByUUID[ uuid ];
  37645. if ( index !== undefined ) {
  37646. delete indicesByUUID[ uuid ];
  37647. if ( index < nCachedObjects ) {
  37648. // object is cached, shrink the CACHED region
  37649. const firstActiveIndex = -- nCachedObjects,
  37650. lastCachedObject = objects[ firstActiveIndex ],
  37651. lastIndex = -- nObjects,
  37652. lastObject = objects[ lastIndex ];
  37653. // last cached object takes this object's place
  37654. indicesByUUID[ lastCachedObject.uuid ] = index;
  37655. objects[ index ] = lastCachedObject;
  37656. // last object goes to the activated slot and pop
  37657. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  37658. objects[ firstActiveIndex ] = lastObject;
  37659. objects.pop();
  37660. // accounting is done, now do the same for all bindings
  37661. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37662. const bindingsForPath = bindings[ j ],
  37663. lastCached = bindingsForPath[ firstActiveIndex ],
  37664. last = bindingsForPath[ lastIndex ];
  37665. bindingsForPath[ index ] = lastCached;
  37666. bindingsForPath[ firstActiveIndex ] = last;
  37667. bindingsForPath.pop();
  37668. }
  37669. } else {
  37670. // object is active, just swap with the last and pop
  37671. const lastIndex = -- nObjects,
  37672. lastObject = objects[ lastIndex ];
  37673. if ( lastIndex > 0 ) {
  37674. indicesByUUID[ lastObject.uuid ] = index;
  37675. }
  37676. objects[ index ] = lastObject;
  37677. objects.pop();
  37678. // accounting is done, now do the same for all bindings
  37679. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37680. const bindingsForPath = bindings[ j ];
  37681. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  37682. bindingsForPath.pop();
  37683. }
  37684. } // cached or active
  37685. } // if object is known
  37686. } // for arguments
  37687. this.nCachedObjects_ = nCachedObjects;
  37688. }
  37689. // Internal interface used by befriended PropertyBinding.Composite:
  37690. subscribe_( path, parsedPath ) {
  37691. // returns an array of bindings for the given path that is changed
  37692. // according to the contained objects in the group
  37693. const indicesByPath = this._bindingsIndicesByPath;
  37694. let index = indicesByPath[ path ];
  37695. const bindings = this._bindings;
  37696. if ( index !== undefined ) return bindings[ index ];
  37697. const paths = this._paths,
  37698. parsedPaths = this._parsedPaths,
  37699. objects = this._objects,
  37700. nObjects = objects.length,
  37701. nCachedObjects = this.nCachedObjects_,
  37702. bindingsForPath = new Array( nObjects );
  37703. index = bindings.length;
  37704. indicesByPath[ path ] = index;
  37705. paths.push( path );
  37706. parsedPaths.push( parsedPath );
  37707. bindings.push( bindingsForPath );
  37708. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  37709. const object = objects[ i ];
  37710. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  37711. }
  37712. return bindingsForPath;
  37713. }
  37714. unsubscribe_( path ) {
  37715. // tells the group to forget about a property path and no longer
  37716. // update the array previously obtained with 'subscribe_'
  37717. const indicesByPath = this._bindingsIndicesByPath,
  37718. index = indicesByPath[ path ];
  37719. if ( index !== undefined ) {
  37720. const paths = this._paths,
  37721. parsedPaths = this._parsedPaths,
  37722. bindings = this._bindings,
  37723. lastBindingsIndex = bindings.length - 1,
  37724. lastBindings = bindings[ lastBindingsIndex ],
  37725. lastBindingsPath = path[ lastBindingsIndex ];
  37726. indicesByPath[ lastBindingsPath ] = index;
  37727. bindings[ index ] = lastBindings;
  37728. bindings.pop();
  37729. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  37730. parsedPaths.pop();
  37731. paths[ index ] = paths[ lastBindingsIndex ];
  37732. paths.pop();
  37733. }
  37734. }
  37735. }
  37736. /**
  37737. * An instance of `AnimationAction` schedules the playback of an animation which is
  37738. * stored in {@link AnimationClip}.
  37739. */
  37740. class AnimationAction {
  37741. /**
  37742. * Constructs a new animation action.
  37743. *
  37744. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  37745. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  37746. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  37747. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  37748. */
  37749. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  37750. this._mixer = mixer;
  37751. this._clip = clip;
  37752. this._localRoot = localRoot;
  37753. /**
  37754. * Defines how the animation is blended/combined when two or more animations
  37755. * are simultaneously played.
  37756. *
  37757. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  37758. */
  37759. this.blendMode = blendMode;
  37760. const tracks = clip.tracks,
  37761. nTracks = tracks.length,
  37762. interpolants = new Array( nTracks );
  37763. const interpolantSettings = {
  37764. endingStart: ZeroCurvatureEnding,
  37765. endingEnd: ZeroCurvatureEnding
  37766. };
  37767. for ( let i = 0; i !== nTracks; ++ i ) {
  37768. const interpolant = tracks[ i ].createInterpolant( null );
  37769. interpolants[ i ] = interpolant;
  37770. interpolant.settings = interpolantSettings;
  37771. }
  37772. this._interpolantSettings = interpolantSettings;
  37773. this._interpolants = interpolants; // bound by the mixer
  37774. // inside: PropertyMixer (managed by the mixer)
  37775. this._propertyBindings = new Array( nTracks );
  37776. this._cacheIndex = null; // for the memory manager
  37777. this._byClipCacheIndex = null; // for the memory manager
  37778. this._timeScaleInterpolant = null;
  37779. this._weightInterpolant = null;
  37780. /**
  37781. * The loop mode, set via {@link AnimationAction#setLoop}.
  37782. *
  37783. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  37784. * @default LoopRepeat
  37785. */
  37786. this.loop = LoopRepeat;
  37787. this._loopCount = -1;
  37788. // global mixer time when the action is to be started
  37789. // it's set back to 'null' upon start of the action
  37790. this._startTime = null;
  37791. /**
  37792. * The local time of this action (in seconds, starting with `0`).
  37793. *
  37794. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  37795. * loop state).
  37796. *
  37797. * @type {number}
  37798. * @default Infinity
  37799. */
  37800. this.time = 0;
  37801. /**
  37802. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  37803. * animation to pause. Negative values cause the animation to play backwards.
  37804. *
  37805. * @type {number}
  37806. * @default 1
  37807. */
  37808. this.timeScale = 1;
  37809. this._effectiveTimeScale = 1;
  37810. /**
  37811. * The degree of influence of this action (in the interval `[0, 1]`). Values
  37812. * between `0` (no impact) and `1` (full impact) can be used to blend between
  37813. * several actions.
  37814. *
  37815. * @type {number}
  37816. * @default 1
  37817. */
  37818. this.weight = 1;
  37819. this._effectiveWeight = 1;
  37820. /**
  37821. * The number of repetitions of the performed clip over the course of this action.
  37822. * Can be set via {@link AnimationAction#setLoop}.
  37823. *
  37824. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  37825. * `THREE:LoopOnce`.
  37826. *
  37827. * @type {number}
  37828. * @default Infinity
  37829. */
  37830. this.repetitions = Infinity;
  37831. /**
  37832. * If set to `true`, the playback of the action is paused.
  37833. *
  37834. * @type {boolean}
  37835. * @default false
  37836. */
  37837. this.paused = false;
  37838. /**
  37839. * If set to `false`, the action is disabled so it has no impact.
  37840. *
  37841. * When the action is re-enabled, the animation continues from its current
  37842. * time (setting `enabled` to `false` doesn't reset the action).
  37843. *
  37844. * @type {boolean}
  37845. * @default true
  37846. */
  37847. this.enabled = true;
  37848. /**
  37849. * If set to true the animation will automatically be paused on its last frame.
  37850. *
  37851. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  37852. * to `false` when the last loop of the action has finished, so that this action has
  37853. * no further impact.
  37854. *
  37855. * Note: This member has no impact if the action is interrupted (it
  37856. * has only an effect if its last loop has really finished).
  37857. *
  37858. * @type {boolean}
  37859. * @default false
  37860. */
  37861. this.clampWhenFinished = false;
  37862. /**
  37863. * Enables smooth interpolation without separate clips for start, loop and end.
  37864. *
  37865. * @type {boolean}
  37866. * @default true
  37867. */
  37868. this.zeroSlopeAtStart = true;
  37869. /**
  37870. * Enables smooth interpolation without separate clips for start, loop and end.
  37871. *
  37872. * @type {boolean}
  37873. * @default true
  37874. */
  37875. this.zeroSlopeAtEnd = true;
  37876. }
  37877. /**
  37878. * Starts the playback of the animation.
  37879. *
  37880. * @return {AnimationAction} A reference to this animation action.
  37881. */
  37882. play() {
  37883. this._mixer._activateAction( this );
  37884. return this;
  37885. }
  37886. /**
  37887. * Stops the playback of the animation.
  37888. *
  37889. * @return {AnimationAction} A reference to this animation action.
  37890. */
  37891. stop() {
  37892. this._mixer._deactivateAction( this );
  37893. return this.reset();
  37894. }
  37895. /**
  37896. * Resets the playback of the animation.
  37897. *
  37898. * @return {AnimationAction} A reference to this animation action.
  37899. */
  37900. reset() {
  37901. this.paused = false;
  37902. this.enabled = true;
  37903. this.time = 0; // restart clip
  37904. this._loopCount = -1;// forget previous loops
  37905. this._startTime = null;// forget scheduling
  37906. return this.stopFading().stopWarping();
  37907. }
  37908. /**
  37909. * Returns `true` if the animation is running.
  37910. *
  37911. * @return {boolean} Whether the animation is running or not.
  37912. */
  37913. isRunning() {
  37914. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  37915. this._startTime === null && this._mixer._isActiveAction( this );
  37916. }
  37917. /**
  37918. * Returns `true` when {@link AnimationAction#play} has been called.
  37919. *
  37920. * @return {boolean} Whether the animation is scheduled or not.
  37921. */
  37922. isScheduled() {
  37923. return this._mixer._isActiveAction( this );
  37924. }
  37925. /**
  37926. * Defines the time when the animation should start.
  37927. *
  37928. * @param {number} time - The start time in seconds.
  37929. * @return {AnimationAction} A reference to this animation action.
  37930. */
  37931. startAt( time ) {
  37932. this._startTime = time;
  37933. return this;
  37934. }
  37935. /**
  37936. * Configures the loop settings for this action.
  37937. *
  37938. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  37939. * @param {number} repetitions - The number of repetitions.
  37940. * @return {AnimationAction} A reference to this animation action.
  37941. */
  37942. setLoop( mode, repetitions ) {
  37943. this.loop = mode;
  37944. this.repetitions = repetitions;
  37945. return this;
  37946. }
  37947. /**
  37948. * Sets the effective weight of this action.
  37949. *
  37950. * An action has no effect and thus an effective weight of zero when the
  37951. * action is disabled.
  37952. *
  37953. * @param {number} weight - The weight to set.
  37954. * @return {AnimationAction} A reference to this animation action.
  37955. */
  37956. setEffectiveWeight( weight ) {
  37957. this.weight = weight;
  37958. // note: same logic as when updated at runtime
  37959. this._effectiveWeight = this.enabled ? weight : 0;
  37960. return this.stopFading();
  37961. }
  37962. /**
  37963. * Returns the effective weight of this action.
  37964. *
  37965. * @return {number} The effective weight.
  37966. */
  37967. getEffectiveWeight() {
  37968. return this._effectiveWeight;
  37969. }
  37970. /**
  37971. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  37972. * within the passed time interval.
  37973. *
  37974. * @param {number} duration - The duration of the fade.
  37975. * @return {AnimationAction} A reference to this animation action.
  37976. */
  37977. fadeIn( duration ) {
  37978. return this._scheduleFading( duration, 0, 1 );
  37979. }
  37980. /**
  37981. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  37982. * within the passed time interval.
  37983. *
  37984. * @param {number} duration - The duration of the fade.
  37985. * @return {AnimationAction} A reference to this animation action.
  37986. */
  37987. fadeOut( duration ) {
  37988. return this._scheduleFading( duration, 1, 0 );
  37989. }
  37990. /**
  37991. * Causes this action to fade in and the given action to fade out,
  37992. * within the passed time interval.
  37993. *
  37994. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  37995. * @param {number} duration - The duration of the fade.
  37996. * @param {boolean} [warp=false] - Whether warping should be used or not.
  37997. * @return {AnimationAction} A reference to this animation action.
  37998. */
  37999. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  38000. fadeOutAction.fadeOut( duration );
  38001. this.fadeIn( duration );
  38002. if ( warp === true ) {
  38003. const fadeInDuration = this._clip.duration,
  38004. fadeOutDuration = fadeOutAction._clip.duration,
  38005. startEndRatio = fadeOutDuration / fadeInDuration,
  38006. endStartRatio = fadeInDuration / fadeOutDuration;
  38007. fadeOutAction.warp( 1.0, startEndRatio, duration );
  38008. this.warp( endStartRatio, 1.0, duration );
  38009. }
  38010. return this;
  38011. }
  38012. /**
  38013. * Causes this action to fade out and the given action to fade in,
  38014. * within the passed time interval.
  38015. *
  38016. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  38017. * @param {number} duration - The duration of the fade.
  38018. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38019. * @return {AnimationAction} A reference to this animation action.
  38020. */
  38021. crossFadeTo( fadeInAction, duration, warp = false ) {
  38022. return fadeInAction.crossFadeFrom( this, duration, warp );
  38023. }
  38024. /**
  38025. * Stops any fading which is applied to this action.
  38026. *
  38027. * @return {AnimationAction} A reference to this animation action.
  38028. */
  38029. stopFading() {
  38030. const weightInterpolant = this._weightInterpolant;
  38031. if ( weightInterpolant !== null ) {
  38032. this._weightInterpolant = null;
  38033. this._mixer._takeBackControlInterpolant( weightInterpolant );
  38034. }
  38035. return this;
  38036. }
  38037. /**
  38038. * Sets the effective time scale of this action.
  38039. *
  38040. * An action has no effect and thus an effective time scale of zero when the
  38041. * action is paused.
  38042. *
  38043. * @param {number} timeScale - The time scale to set.
  38044. * @return {AnimationAction} A reference to this animation action.
  38045. */
  38046. setEffectiveTimeScale( timeScale ) {
  38047. this.timeScale = timeScale;
  38048. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  38049. return this.stopWarping();
  38050. }
  38051. /**
  38052. * Returns the effective time scale of this action.
  38053. *
  38054. * @return {number} The effective time scale.
  38055. */
  38056. getEffectiveTimeScale() {
  38057. return this._effectiveTimeScale;
  38058. }
  38059. /**
  38060. * Sets the duration for a single loop of this action.
  38061. *
  38062. * @param {number} duration - The duration to set.
  38063. * @return {AnimationAction} A reference to this animation action.
  38064. */
  38065. setDuration( duration ) {
  38066. this.timeScale = this._clip.duration / duration;
  38067. return this.stopWarping();
  38068. }
  38069. /**
  38070. * Synchronizes this action with the passed other action.
  38071. *
  38072. * @param {AnimationAction} action - The action to sync with.
  38073. * @return {AnimationAction} A reference to this animation action.
  38074. */
  38075. syncWith( action ) {
  38076. this.time = action.time;
  38077. this.timeScale = action.timeScale;
  38078. return this.stopWarping();
  38079. }
  38080. /**
  38081. * Decelerates this animation's speed to `0` within the passed time interval.
  38082. *
  38083. * @param {number} duration - The duration.
  38084. * @return {AnimationAction} A reference to this animation action.
  38085. */
  38086. halt( duration ) {
  38087. return this.warp( this._effectiveTimeScale, 0, duration );
  38088. }
  38089. /**
  38090. * Changes the playback speed, within the passed time interval, by modifying
  38091. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  38092. * `endTimeScale`.
  38093. *
  38094. * @param {number} startTimeScale - The start time scale.
  38095. * @param {number} endTimeScale - The end time scale.
  38096. * @param {number} duration - The duration.
  38097. * @return {AnimationAction} A reference to this animation action.
  38098. */
  38099. warp( startTimeScale, endTimeScale, duration ) {
  38100. const mixer = this._mixer,
  38101. now = mixer.time,
  38102. timeScale = this.timeScale;
  38103. let interpolant = this._timeScaleInterpolant;
  38104. if ( interpolant === null ) {
  38105. interpolant = mixer._lendControlInterpolant();
  38106. this._timeScaleInterpolant = interpolant;
  38107. }
  38108. const times = interpolant.parameterPositions,
  38109. values = interpolant.sampleValues;
  38110. times[ 0 ] = now;
  38111. times[ 1 ] = now + duration;
  38112. values[ 0 ] = startTimeScale / timeScale;
  38113. values[ 1 ] = endTimeScale / timeScale;
  38114. return this;
  38115. }
  38116. /**
  38117. * Stops any scheduled warping which is applied to this action.
  38118. *
  38119. * @return {AnimationAction} A reference to this animation action.
  38120. */
  38121. stopWarping() {
  38122. const timeScaleInterpolant = this._timeScaleInterpolant;
  38123. if ( timeScaleInterpolant !== null ) {
  38124. this._timeScaleInterpolant = null;
  38125. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  38126. }
  38127. return this;
  38128. }
  38129. /**
  38130. * Returns the animation mixer of this animation action.
  38131. *
  38132. * @return {AnimationMixer} The animation mixer.
  38133. */
  38134. getMixer() {
  38135. return this._mixer;
  38136. }
  38137. /**
  38138. * Returns the animation clip of this animation action.
  38139. *
  38140. * @return {AnimationClip} The animation clip.
  38141. */
  38142. getClip() {
  38143. return this._clip;
  38144. }
  38145. /**
  38146. * Returns the root object of this animation action.
  38147. *
  38148. * @return {Object3D} The root object.
  38149. */
  38150. getRoot() {
  38151. return this._localRoot || this._mixer._root;
  38152. }
  38153. // Interna
  38154. _update( time, deltaTime, timeDirection, accuIndex ) {
  38155. // called by the mixer
  38156. if ( ! this.enabled ) {
  38157. // call ._updateWeight() to update ._effectiveWeight
  38158. this._updateWeight( time );
  38159. return;
  38160. }
  38161. const startTime = this._startTime;
  38162. if ( startTime !== null ) {
  38163. // check for scheduled start of action
  38164. const timeRunning = ( time - startTime ) * timeDirection;
  38165. if ( timeRunning < 0 || timeDirection === 0 ) {
  38166. deltaTime = 0;
  38167. } else {
  38168. this._startTime = null; // unschedule
  38169. deltaTime = timeDirection * timeRunning;
  38170. }
  38171. }
  38172. // apply time scale and advance time
  38173. deltaTime *= this._updateTimeScale( time );
  38174. const clipTime = this._updateTime( deltaTime );
  38175. // note: _updateTime may disable the action resulting in
  38176. // an effective weight of 0
  38177. const weight = this._updateWeight( time );
  38178. if ( weight > 0 ) {
  38179. const interpolants = this._interpolants;
  38180. const propertyMixers = this._propertyBindings;
  38181. switch ( this.blendMode ) {
  38182. case AdditiveAnimationBlendMode:
  38183. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38184. interpolants[ j ].evaluate( clipTime );
  38185. propertyMixers[ j ].accumulateAdditive( weight );
  38186. }
  38187. break;
  38188. case NormalAnimationBlendMode:
  38189. default:
  38190. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38191. interpolants[ j ].evaluate( clipTime );
  38192. propertyMixers[ j ].accumulate( accuIndex, weight );
  38193. }
  38194. }
  38195. }
  38196. }
  38197. _updateWeight( time ) {
  38198. let weight = 0;
  38199. if ( this.enabled ) {
  38200. weight = this.weight;
  38201. const interpolant = this._weightInterpolant;
  38202. if ( interpolant !== null ) {
  38203. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38204. weight *= interpolantValue;
  38205. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38206. this.stopFading();
  38207. if ( interpolantValue === 0 ) {
  38208. // faded out, disable
  38209. this.enabled = false;
  38210. }
  38211. }
  38212. }
  38213. }
  38214. this._effectiveWeight = weight;
  38215. return weight;
  38216. }
  38217. _updateTimeScale( time ) {
  38218. let timeScale = 0;
  38219. if ( ! this.paused ) {
  38220. timeScale = this.timeScale;
  38221. const interpolant = this._timeScaleInterpolant;
  38222. if ( interpolant !== null ) {
  38223. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38224. timeScale *= interpolantValue;
  38225. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38226. this.stopWarping();
  38227. if ( timeScale === 0 ) {
  38228. // motion has halted, pause
  38229. this.paused = true;
  38230. } else {
  38231. // warp done - apply final time scale
  38232. this.timeScale = timeScale;
  38233. }
  38234. }
  38235. }
  38236. }
  38237. this._effectiveTimeScale = timeScale;
  38238. return timeScale;
  38239. }
  38240. _updateTime( deltaTime ) {
  38241. const duration = this._clip.duration;
  38242. const loop = this.loop;
  38243. let time = this.time + deltaTime;
  38244. let loopCount = this._loopCount;
  38245. const pingPong = ( loop === LoopPingPong );
  38246. if ( deltaTime === 0 ) {
  38247. if ( loopCount === -1 ) return time;
  38248. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  38249. }
  38250. if ( loop === LoopOnce ) {
  38251. if ( loopCount === -1 ) {
  38252. // just started
  38253. this._loopCount = 0;
  38254. this._setEndings( true, true, false );
  38255. }
  38256. handle_stop: {
  38257. if ( time >= duration ) {
  38258. time = duration;
  38259. } else if ( time < 0 ) {
  38260. time = 0;
  38261. } else {
  38262. this.time = time;
  38263. break handle_stop;
  38264. }
  38265. if ( this.clampWhenFinished ) this.paused = true;
  38266. else this.enabled = false;
  38267. this.time = time;
  38268. this._mixer.dispatchEvent( {
  38269. type: 'finished', action: this,
  38270. direction: deltaTime < 0 ? -1 : 1
  38271. } );
  38272. }
  38273. } else { // repetitive Repeat or PingPong
  38274. if ( loopCount === -1 ) {
  38275. // just started
  38276. if ( deltaTime >= 0 ) {
  38277. loopCount = 0;
  38278. this._setEndings( true, this.repetitions === 0, pingPong );
  38279. } else {
  38280. // when looping in reverse direction, the initial
  38281. // transition through zero counts as a repetition,
  38282. // so leave loopCount at -1
  38283. this._setEndings( this.repetitions === 0, true, pingPong );
  38284. }
  38285. }
  38286. if ( time >= duration || time < 0 ) {
  38287. // wrap around
  38288. const loopDelta = Math.floor( time / duration ); // signed
  38289. time -= duration * loopDelta;
  38290. loopCount += Math.abs( loopDelta );
  38291. const pending = this.repetitions - loopCount;
  38292. if ( pending <= 0 ) {
  38293. // have to stop (switch state, clamp time, fire event)
  38294. if ( this.clampWhenFinished ) this.paused = true;
  38295. else this.enabled = false;
  38296. time = deltaTime > 0 ? duration : 0;
  38297. this.time = time;
  38298. this._mixer.dispatchEvent( {
  38299. type: 'finished', action: this,
  38300. direction: deltaTime > 0 ? 1 : -1
  38301. } );
  38302. } else {
  38303. // keep running
  38304. if ( pending === 1 ) {
  38305. // entering the last round
  38306. const atStart = deltaTime < 0;
  38307. this._setEndings( atStart, ! atStart, pingPong );
  38308. } else {
  38309. this._setEndings( false, false, pingPong );
  38310. }
  38311. this._loopCount = loopCount;
  38312. this.time = time;
  38313. this._mixer.dispatchEvent( {
  38314. type: 'loop', action: this, loopDelta: loopDelta
  38315. } );
  38316. }
  38317. } else {
  38318. this.time = time;
  38319. }
  38320. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  38321. // invert time for the "pong round"
  38322. return duration - time;
  38323. }
  38324. }
  38325. return time;
  38326. }
  38327. _setEndings( atStart, atEnd, pingPong ) {
  38328. const settings = this._interpolantSettings;
  38329. if ( pingPong ) {
  38330. settings.endingStart = ZeroSlopeEnding;
  38331. settings.endingEnd = ZeroSlopeEnding;
  38332. } else {
  38333. // assuming for LoopOnce atStart == atEnd == true
  38334. if ( atStart ) {
  38335. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38336. } else {
  38337. settings.endingStart = WrapAroundEnding;
  38338. }
  38339. if ( atEnd ) {
  38340. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38341. } else {
  38342. settings.endingEnd = WrapAroundEnding;
  38343. }
  38344. }
  38345. }
  38346. _scheduleFading( duration, weightNow, weightThen ) {
  38347. const mixer = this._mixer, now = mixer.time;
  38348. let interpolant = this._weightInterpolant;
  38349. if ( interpolant === null ) {
  38350. interpolant = mixer._lendControlInterpolant();
  38351. this._weightInterpolant = interpolant;
  38352. }
  38353. const times = interpolant.parameterPositions,
  38354. values = interpolant.sampleValues;
  38355. times[ 0 ] = now;
  38356. values[ 0 ] = weightNow;
  38357. times[ 1 ] = now + duration;
  38358. values[ 1 ] = weightThen;
  38359. return this;
  38360. }
  38361. }
  38362. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  38363. /**
  38364. * `AnimationMixer` is a player for animations on a particular object in
  38365. * the scene. When multiple objects in the scene are animated independently,
  38366. * one `AnimationMixer` may be used for each object.
  38367. */
  38368. class AnimationMixer extends EventDispatcher {
  38369. /**
  38370. * Constructs a new animation mixer.
  38371. *
  38372. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  38373. */
  38374. constructor( root ) {
  38375. super();
  38376. this._root = root;
  38377. this._initMemoryManager();
  38378. this._accuIndex = 0;
  38379. /**
  38380. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  38381. *
  38382. * @type {number}
  38383. * @default 0
  38384. */
  38385. this.time = 0;
  38386. /**
  38387. * A scaling factor for the global time.
  38388. *
  38389. * Note: Setting this member to `0` and later back to `1` is a
  38390. * possibility to pause/unpause all actions that are controlled by this
  38391. * mixer.
  38392. *
  38393. * @type {number}
  38394. * @default 1
  38395. */
  38396. this.timeScale = 1.0;
  38397. }
  38398. _bindAction( action, prototypeAction ) {
  38399. const root = action._localRoot || this._root,
  38400. tracks = action._clip.tracks,
  38401. nTracks = tracks.length,
  38402. bindings = action._propertyBindings,
  38403. interpolants = action._interpolants,
  38404. rootUuid = root.uuid,
  38405. bindingsByRoot = this._bindingsByRootAndName;
  38406. let bindingsByName = bindingsByRoot[ rootUuid ];
  38407. if ( bindingsByName === undefined ) {
  38408. bindingsByName = {};
  38409. bindingsByRoot[ rootUuid ] = bindingsByName;
  38410. }
  38411. for ( let i = 0; i !== nTracks; ++ i ) {
  38412. const track = tracks[ i ],
  38413. trackName = track.name;
  38414. let binding = bindingsByName[ trackName ];
  38415. if ( binding !== undefined ) {
  38416. ++ binding.referenceCount;
  38417. bindings[ i ] = binding;
  38418. } else {
  38419. binding = bindings[ i ];
  38420. if ( binding !== undefined ) {
  38421. // existing binding, make sure the cache knows
  38422. if ( binding._cacheIndex === null ) {
  38423. ++ binding.referenceCount;
  38424. this._addInactiveBinding( binding, rootUuid, trackName );
  38425. }
  38426. continue;
  38427. }
  38428. const path = prototypeAction && prototypeAction.
  38429. _propertyBindings[ i ].binding.parsedPath;
  38430. binding = new PropertyMixer(
  38431. PropertyBinding.create( root, trackName, path ),
  38432. track.ValueTypeName, track.getValueSize() );
  38433. ++ binding.referenceCount;
  38434. this._addInactiveBinding( binding, rootUuid, trackName );
  38435. bindings[ i ] = binding;
  38436. }
  38437. interpolants[ i ].resultBuffer = binding.buffer;
  38438. }
  38439. }
  38440. _activateAction( action ) {
  38441. if ( ! this._isActiveAction( action ) ) {
  38442. if ( action._cacheIndex === null ) {
  38443. // this action has been forgotten by the cache, but the user
  38444. // appears to be still using it -> rebind
  38445. const rootUuid = ( action._localRoot || this._root ).uuid,
  38446. clipUuid = action._clip.uuid,
  38447. actionsForClip = this._actionsByClip[ clipUuid ];
  38448. this._bindAction( action,
  38449. actionsForClip && actionsForClip.knownActions[ 0 ] );
  38450. this._addInactiveAction( action, clipUuid, rootUuid );
  38451. }
  38452. const bindings = action._propertyBindings;
  38453. // increment reference counts / sort out state
  38454. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38455. const binding = bindings[ i ];
  38456. if ( binding.useCount ++ === 0 ) {
  38457. this._lendBinding( binding );
  38458. binding.saveOriginalState();
  38459. }
  38460. }
  38461. this._lendAction( action );
  38462. }
  38463. }
  38464. _deactivateAction( action ) {
  38465. if ( this._isActiveAction( action ) ) {
  38466. const bindings = action._propertyBindings;
  38467. // decrement reference counts / sort out state
  38468. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38469. const binding = bindings[ i ];
  38470. if ( -- binding.useCount === 0 ) {
  38471. binding.restoreOriginalState();
  38472. this._takeBackBinding( binding );
  38473. }
  38474. }
  38475. this._takeBackAction( action );
  38476. }
  38477. }
  38478. // Memory manager
  38479. _initMemoryManager() {
  38480. this._actions = []; // 'nActiveActions' followed by inactive ones
  38481. this._nActiveActions = 0;
  38482. this._actionsByClip = {};
  38483. // inside:
  38484. // {
  38485. // knownActions: Array< AnimationAction > - used as prototypes
  38486. // actionByRoot: AnimationAction - lookup
  38487. // }
  38488. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  38489. this._nActiveBindings = 0;
  38490. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  38491. this._controlInterpolants = []; // same game as above
  38492. this._nActiveControlInterpolants = 0;
  38493. const scope = this;
  38494. this.stats = {
  38495. actions: {
  38496. get total() {
  38497. return scope._actions.length;
  38498. },
  38499. get inUse() {
  38500. return scope._nActiveActions;
  38501. }
  38502. },
  38503. bindings: {
  38504. get total() {
  38505. return scope._bindings.length;
  38506. },
  38507. get inUse() {
  38508. return scope._nActiveBindings;
  38509. }
  38510. },
  38511. controlInterpolants: {
  38512. get total() {
  38513. return scope._controlInterpolants.length;
  38514. },
  38515. get inUse() {
  38516. return scope._nActiveControlInterpolants;
  38517. }
  38518. }
  38519. };
  38520. }
  38521. // Memory management for AnimationAction objects
  38522. _isActiveAction( action ) {
  38523. const index = action._cacheIndex;
  38524. return index !== null && index < this._nActiveActions;
  38525. }
  38526. _addInactiveAction( action, clipUuid, rootUuid ) {
  38527. const actions = this._actions,
  38528. actionsByClip = this._actionsByClip;
  38529. let actionsForClip = actionsByClip[ clipUuid ];
  38530. if ( actionsForClip === undefined ) {
  38531. actionsForClip = {
  38532. knownActions: [ action ],
  38533. actionByRoot: {}
  38534. };
  38535. action._byClipCacheIndex = 0;
  38536. actionsByClip[ clipUuid ] = actionsForClip;
  38537. } else {
  38538. const knownActions = actionsForClip.knownActions;
  38539. action._byClipCacheIndex = knownActions.length;
  38540. knownActions.push( action );
  38541. }
  38542. action._cacheIndex = actions.length;
  38543. actions.push( action );
  38544. actionsForClip.actionByRoot[ rootUuid ] = action;
  38545. }
  38546. _removeInactiveAction( action ) {
  38547. const actions = this._actions,
  38548. lastInactiveAction = actions[ actions.length - 1 ],
  38549. cacheIndex = action._cacheIndex;
  38550. lastInactiveAction._cacheIndex = cacheIndex;
  38551. actions[ cacheIndex ] = lastInactiveAction;
  38552. actions.pop();
  38553. action._cacheIndex = null;
  38554. const clipUuid = action._clip.uuid,
  38555. actionsByClip = this._actionsByClip,
  38556. actionsForClip = actionsByClip[ clipUuid ],
  38557. knownActionsForClip = actionsForClip.knownActions,
  38558. lastKnownAction =
  38559. knownActionsForClip[ knownActionsForClip.length - 1 ],
  38560. byClipCacheIndex = action._byClipCacheIndex;
  38561. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  38562. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  38563. knownActionsForClip.pop();
  38564. action._byClipCacheIndex = null;
  38565. const actionByRoot = actionsForClip.actionByRoot,
  38566. rootUuid = ( action._localRoot || this._root ).uuid;
  38567. delete actionByRoot[ rootUuid ];
  38568. if ( knownActionsForClip.length === 0 ) {
  38569. delete actionsByClip[ clipUuid ];
  38570. }
  38571. this._removeInactiveBindingsForAction( action );
  38572. }
  38573. _removeInactiveBindingsForAction( action ) {
  38574. const bindings = action._propertyBindings;
  38575. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38576. const binding = bindings[ i ];
  38577. if ( -- binding.referenceCount === 0 ) {
  38578. this._removeInactiveBinding( binding );
  38579. }
  38580. }
  38581. }
  38582. _lendAction( action ) {
  38583. // [ active actions | inactive actions ]
  38584. // [ active actions >| inactive actions ]
  38585. // s a
  38586. // <-swap->
  38587. // a s
  38588. const actions = this._actions,
  38589. prevIndex = action._cacheIndex,
  38590. lastActiveIndex = this._nActiveActions ++,
  38591. firstInactiveAction = actions[ lastActiveIndex ];
  38592. action._cacheIndex = lastActiveIndex;
  38593. actions[ lastActiveIndex ] = action;
  38594. firstInactiveAction._cacheIndex = prevIndex;
  38595. actions[ prevIndex ] = firstInactiveAction;
  38596. }
  38597. _takeBackAction( action ) {
  38598. // [ active actions | inactive actions ]
  38599. // [ active actions |< inactive actions ]
  38600. // a s
  38601. // <-swap->
  38602. // s a
  38603. const actions = this._actions,
  38604. prevIndex = action._cacheIndex,
  38605. firstInactiveIndex = -- this._nActiveActions,
  38606. lastActiveAction = actions[ firstInactiveIndex ];
  38607. action._cacheIndex = firstInactiveIndex;
  38608. actions[ firstInactiveIndex ] = action;
  38609. lastActiveAction._cacheIndex = prevIndex;
  38610. actions[ prevIndex ] = lastActiveAction;
  38611. }
  38612. // Memory management for PropertyMixer objects
  38613. _addInactiveBinding( binding, rootUuid, trackName ) {
  38614. const bindingsByRoot = this._bindingsByRootAndName,
  38615. bindings = this._bindings;
  38616. let bindingByName = bindingsByRoot[ rootUuid ];
  38617. if ( bindingByName === undefined ) {
  38618. bindingByName = {};
  38619. bindingsByRoot[ rootUuid ] = bindingByName;
  38620. }
  38621. bindingByName[ trackName ] = binding;
  38622. binding._cacheIndex = bindings.length;
  38623. bindings.push( binding );
  38624. }
  38625. _removeInactiveBinding( binding ) {
  38626. const bindings = this._bindings,
  38627. propBinding = binding.binding,
  38628. rootUuid = propBinding.rootNode.uuid,
  38629. trackName = propBinding.path,
  38630. bindingsByRoot = this._bindingsByRootAndName,
  38631. bindingByName = bindingsByRoot[ rootUuid ],
  38632. lastInactiveBinding = bindings[ bindings.length - 1 ],
  38633. cacheIndex = binding._cacheIndex;
  38634. lastInactiveBinding._cacheIndex = cacheIndex;
  38635. bindings[ cacheIndex ] = lastInactiveBinding;
  38636. bindings.pop();
  38637. delete bindingByName[ trackName ];
  38638. if ( Object.keys( bindingByName ).length === 0 ) {
  38639. delete bindingsByRoot[ rootUuid ];
  38640. }
  38641. }
  38642. _lendBinding( binding ) {
  38643. const bindings = this._bindings,
  38644. prevIndex = binding._cacheIndex,
  38645. lastActiveIndex = this._nActiveBindings ++,
  38646. firstInactiveBinding = bindings[ lastActiveIndex ];
  38647. binding._cacheIndex = lastActiveIndex;
  38648. bindings[ lastActiveIndex ] = binding;
  38649. firstInactiveBinding._cacheIndex = prevIndex;
  38650. bindings[ prevIndex ] = firstInactiveBinding;
  38651. }
  38652. _takeBackBinding( binding ) {
  38653. const bindings = this._bindings,
  38654. prevIndex = binding._cacheIndex,
  38655. firstInactiveIndex = -- this._nActiveBindings,
  38656. lastActiveBinding = bindings[ firstInactiveIndex ];
  38657. binding._cacheIndex = firstInactiveIndex;
  38658. bindings[ firstInactiveIndex ] = binding;
  38659. lastActiveBinding._cacheIndex = prevIndex;
  38660. bindings[ prevIndex ] = lastActiveBinding;
  38661. }
  38662. // Memory management of Interpolants for weight and time scale
  38663. _lendControlInterpolant() {
  38664. const interpolants = this._controlInterpolants,
  38665. lastActiveIndex = this._nActiveControlInterpolants ++;
  38666. let interpolant = interpolants[ lastActiveIndex ];
  38667. if ( interpolant === undefined ) {
  38668. interpolant = new LinearInterpolant(
  38669. new Float32Array( 2 ), new Float32Array( 2 ),
  38670. 1, _controlInterpolantsResultBuffer );
  38671. interpolant.__cacheIndex = lastActiveIndex;
  38672. interpolants[ lastActiveIndex ] = interpolant;
  38673. }
  38674. return interpolant;
  38675. }
  38676. _takeBackControlInterpolant( interpolant ) {
  38677. const interpolants = this._controlInterpolants,
  38678. prevIndex = interpolant.__cacheIndex,
  38679. firstInactiveIndex = -- this._nActiveControlInterpolants,
  38680. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  38681. interpolant.__cacheIndex = firstInactiveIndex;
  38682. interpolants[ firstInactiveIndex ] = interpolant;
  38683. lastActiveInterpolant.__cacheIndex = prevIndex;
  38684. interpolants[ prevIndex ] = lastActiveInterpolant;
  38685. }
  38686. /**
  38687. * Returns an instance of {@link AnimationAction} for the passed clip.
  38688. *
  38689. * If an action fitting the clip and root parameters doesn't yet exist, it
  38690. * will be created by this method. Calling this method several times with the
  38691. * same clip and root parameters always returns the same action.
  38692. *
  38693. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  38694. * @param {Object3D} [optionalRoot] - An alternative root object.
  38695. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38696. * @return {?AnimationAction} The animation action.
  38697. */
  38698. clipAction( clip, optionalRoot, blendMode ) {
  38699. const root = optionalRoot || this._root,
  38700. rootUuid = root.uuid;
  38701. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  38702. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  38703. const actionsForClip = this._actionsByClip[ clipUuid ];
  38704. let prototypeAction = null;
  38705. if ( blendMode === undefined ) {
  38706. if ( clipObject !== null ) {
  38707. blendMode = clipObject.blendMode;
  38708. } else {
  38709. blendMode = NormalAnimationBlendMode;
  38710. }
  38711. }
  38712. if ( actionsForClip !== undefined ) {
  38713. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  38714. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  38715. return existingAction;
  38716. }
  38717. // we know the clip, so we don't have to parse all
  38718. // the bindings again but can just copy
  38719. prototypeAction = actionsForClip.knownActions[ 0 ];
  38720. // also, take the clip from the prototype action
  38721. if ( clipObject === null )
  38722. clipObject = prototypeAction._clip;
  38723. }
  38724. // clip must be known when specified via string
  38725. if ( clipObject === null ) return null;
  38726. // allocate all resources required to run it
  38727. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  38728. this._bindAction( newAction, prototypeAction );
  38729. // and make the action known to the memory manager
  38730. this._addInactiveAction( newAction, clipUuid, rootUuid );
  38731. return newAction;
  38732. }
  38733. /**
  38734. * Returns an existing animation action for the passed clip.
  38735. *
  38736. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  38737. * @param {Object3D} [optionalRoot] - An alternative root object.
  38738. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  38739. */
  38740. existingAction( clip, optionalRoot ) {
  38741. const root = optionalRoot || this._root,
  38742. rootUuid = root.uuid,
  38743. clipObject = typeof clip === 'string' ?
  38744. AnimationClip.findByName( root, clip ) : clip,
  38745. clipUuid = clipObject ? clipObject.uuid : clip,
  38746. actionsForClip = this._actionsByClip[ clipUuid ];
  38747. if ( actionsForClip !== undefined ) {
  38748. return actionsForClip.actionByRoot[ rootUuid ] || null;
  38749. }
  38750. return null;
  38751. }
  38752. /**
  38753. * Deactivates all previously scheduled actions on this mixer.
  38754. *
  38755. * @return {AnimationMixer} A reference to thi animation mixer.
  38756. */
  38757. stopAllAction() {
  38758. const actions = this._actions,
  38759. nActions = this._nActiveActions;
  38760. for ( let i = nActions - 1; i >= 0; -- i ) {
  38761. actions[ i ].stop();
  38762. }
  38763. return this;
  38764. }
  38765. /**
  38766. * Advances the global mixer time and updates the animation.
  38767. *
  38768. * This is usually done in the render loop by passing the delta
  38769. * time from {@link Clock} or {@link Timer}.
  38770. *
  38771. * @param {number} deltaTime - The delta time in seconds.
  38772. * @return {AnimationMixer} A reference to thi animation mixer.
  38773. */
  38774. update( deltaTime ) {
  38775. deltaTime *= this.timeScale;
  38776. const actions = this._actions,
  38777. nActions = this._nActiveActions,
  38778. time = this.time += deltaTime,
  38779. timeDirection = Math.sign( deltaTime ),
  38780. accuIndex = this._accuIndex ^= 1;
  38781. // run active actions
  38782. for ( let i = 0; i !== nActions; ++ i ) {
  38783. const action = actions[ i ];
  38784. action._update( time, deltaTime, timeDirection, accuIndex );
  38785. }
  38786. // update scene graph
  38787. const bindings = this._bindings,
  38788. nBindings = this._nActiveBindings;
  38789. for ( let i = 0; i !== nBindings; ++ i ) {
  38790. bindings[ i ].apply( accuIndex );
  38791. }
  38792. return this;
  38793. }
  38794. /**
  38795. * Sets the global mixer to a specific time and updates the animation accordingly.
  38796. *
  38797. * This is useful when you need to jump to an exact time in an animation. The
  38798. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  38799. *
  38800. * @param {number} time - The time to set in seconds.
  38801. * @return {AnimationMixer} A reference to thi animation mixer.
  38802. */
  38803. setTime( time ) {
  38804. this.time = 0; // Zero out time attribute for AnimationMixer object;
  38805. for ( let i = 0; i < this._actions.length; i ++ ) {
  38806. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  38807. }
  38808. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  38809. }
  38810. /**
  38811. * Returns this mixer's root object.
  38812. *
  38813. * @return {Object3D} The mixer's root object.
  38814. */
  38815. getRoot() {
  38816. return this._root;
  38817. }
  38818. /**
  38819. * Deallocates all memory resources for a clip. Before using this method make
  38820. * sure to call {@link AnimationAction#stop} for all related actions.
  38821. *
  38822. * @param {AnimationClip} clip - The clip to uncache.
  38823. */
  38824. uncacheClip( clip ) {
  38825. const actions = this._actions,
  38826. clipUuid = clip.uuid,
  38827. actionsByClip = this._actionsByClip,
  38828. actionsForClip = actionsByClip[ clipUuid ];
  38829. if ( actionsForClip !== undefined ) {
  38830. // note: just calling _removeInactiveAction would mess up the
  38831. // iteration state and also require updating the state we can
  38832. // just throw away
  38833. const actionsToRemove = actionsForClip.knownActions;
  38834. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  38835. const action = actionsToRemove[ i ];
  38836. this._deactivateAction( action );
  38837. const cacheIndex = action._cacheIndex,
  38838. lastInactiveAction = actions[ actions.length - 1 ];
  38839. action._cacheIndex = null;
  38840. action._byClipCacheIndex = null;
  38841. lastInactiveAction._cacheIndex = cacheIndex;
  38842. actions[ cacheIndex ] = lastInactiveAction;
  38843. actions.pop();
  38844. this._removeInactiveBindingsForAction( action );
  38845. }
  38846. delete actionsByClip[ clipUuid ];
  38847. }
  38848. }
  38849. /**
  38850. * Deallocates all memory resources for a root object. Before using this
  38851. * method make sure to call {@link AnimationAction#stop} for all related
  38852. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  38853. * mixer operates on a single root.
  38854. *
  38855. * @param {Object3D} root - The root object to uncache.
  38856. */
  38857. uncacheRoot( root ) {
  38858. const rootUuid = root.uuid,
  38859. actionsByClip = this._actionsByClip;
  38860. for ( const clipUuid in actionsByClip ) {
  38861. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  38862. action = actionByRoot[ rootUuid ];
  38863. if ( action !== undefined ) {
  38864. this._deactivateAction( action );
  38865. this._removeInactiveAction( action );
  38866. }
  38867. }
  38868. const bindingsByRoot = this._bindingsByRootAndName,
  38869. bindingByName = bindingsByRoot[ rootUuid ];
  38870. if ( bindingByName !== undefined ) {
  38871. for ( const trackName in bindingByName ) {
  38872. const binding = bindingByName[ trackName ];
  38873. binding.restoreOriginalState();
  38874. this._removeInactiveBinding( binding );
  38875. }
  38876. }
  38877. }
  38878. /**
  38879. * Deallocates all memory resources for an action. The action is identified by the
  38880. * given clip and an optional root object. Before using this method make
  38881. * sure to call {@link AnimationAction#stop} to deactivate the action.
  38882. *
  38883. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  38884. * @param {Object3D} [optionalRoot] - An alternative root object.
  38885. */
  38886. uncacheAction( clip, optionalRoot ) {
  38887. const action = this.existingAction( clip, optionalRoot );
  38888. if ( action !== null ) {
  38889. this._deactivateAction( action );
  38890. this._removeInactiveAction( action );
  38891. }
  38892. }
  38893. }
  38894. /**
  38895. * Represents a 3D render target.
  38896. *
  38897. * @augments RenderTarget
  38898. */
  38899. class RenderTarget3D extends RenderTarget {
  38900. /**
  38901. * Constructs a new 3D render target.
  38902. *
  38903. * @param {number} [width=1] - The width of the render target.
  38904. * @param {number} [height=1] - The height of the render target.
  38905. * @param {number} [depth=1] - The height of the render target.
  38906. * @param {RenderTarget~Options} [options] - The configuration object.
  38907. */
  38908. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  38909. super( width, height, options );
  38910. /**
  38911. * This flag can be used for type testing.
  38912. *
  38913. * @type {boolean}
  38914. * @readonly
  38915. * @default true
  38916. */
  38917. this.isRenderTarget3D = true;
  38918. this.depth = depth;
  38919. /**
  38920. * Overwritten with a different texture type.
  38921. *
  38922. * @type {Data3DTexture}
  38923. */
  38924. this.texture = new Data3DTexture( null, width, height, depth );
  38925. this.texture.isRenderTargetTexture = true;
  38926. }
  38927. }
  38928. /**
  38929. * Represents an array render target.
  38930. *
  38931. * @augments RenderTarget
  38932. */
  38933. class RenderTargetArray extends RenderTarget {
  38934. /**
  38935. * Constructs a new 3D render target.
  38936. *
  38937. * @param {number} [width=1] - The width of the render target.
  38938. * @param {number} [height=1] - The height of the render target.
  38939. * @param {number} [depth=1] - The height of the render target.
  38940. * @param {RenderTarget~Options} [options] - The configuration object.
  38941. */
  38942. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  38943. super( width, height, options );
  38944. this.isRenderTargetArray = true;
  38945. this.depth = depth;
  38946. /**
  38947. * Overwritten with a different texture type.
  38948. *
  38949. * @type {DataArrayTexture}
  38950. */
  38951. this.texture = new DataArrayTexture( null, width, height, depth );
  38952. this.texture.isRenderTargetTexture = true;
  38953. }
  38954. }
  38955. /**
  38956. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  38957. *
  38958. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  38959. * ```js
  38960. * uniforms: {
  38961. * time: { value: 1.0 },
  38962. * resolution: new Uniform( new Vector2() )
  38963. * };
  38964. * ```
  38965. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  38966. * in {@link WebGLRenderer}.
  38967. */
  38968. class Uniform {
  38969. /**
  38970. * Constructs a new uniform.
  38971. *
  38972. * @param {any} value - The uniform value.
  38973. */
  38974. constructor( value ) {
  38975. /**
  38976. * The uniform value.
  38977. *
  38978. * @type {any}
  38979. */
  38980. this.value = value;
  38981. }
  38982. /**
  38983. * Returns a new uniform with copied values from this instance.
  38984. * If the value has a `clone()` method, the value is cloned as well.
  38985. *
  38986. * @return {Uniform} A clone of this instance.
  38987. */
  38988. clone() {
  38989. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  38990. }
  38991. }
  38992. let _id$1 = 0;
  38993. /**
  38994. * A class for managing multiple uniforms in a single group. The renderer will process
  38995. * such a definition as a single UBO.
  38996. *
  38997. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  38998. * in {@link WebGLRenderer}.
  38999. *
  39000. * @augments EventDispatcher
  39001. */
  39002. class UniformsGroup extends EventDispatcher {
  39003. /**
  39004. * Constructs a new uniforms group.
  39005. */
  39006. constructor() {
  39007. super();
  39008. /**
  39009. * This flag can be used for type testing.
  39010. *
  39011. * @type {boolean}
  39012. * @readonly
  39013. * @default true
  39014. */
  39015. this.isUniformsGroup = true;
  39016. /**
  39017. * The ID of the 3D object.
  39018. *
  39019. * @name UniformsGroup#id
  39020. * @type {number}
  39021. * @readonly
  39022. */
  39023. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  39024. /**
  39025. * The name of the uniforms group.
  39026. *
  39027. * @type {string}
  39028. */
  39029. this.name = '';
  39030. /**
  39031. * The buffer usage.
  39032. *
  39033. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  39034. * @default StaticDrawUsage
  39035. */
  39036. this.usage = StaticDrawUsage;
  39037. /**
  39038. * An array holding the uniforms.
  39039. *
  39040. * @type {Array<Uniform>}
  39041. */
  39042. this.uniforms = [];
  39043. }
  39044. /**
  39045. * Adds the given uniform to this uniforms group.
  39046. *
  39047. * @param {Uniform} uniform - The uniform to add.
  39048. * @return {UniformsGroup} A reference to this uniforms group.
  39049. */
  39050. add( uniform ) {
  39051. this.uniforms.push( uniform );
  39052. return this;
  39053. }
  39054. /**
  39055. * Removes the given uniform from this uniforms group.
  39056. *
  39057. * @param {Uniform} uniform - The uniform to remove.
  39058. * @return {UniformsGroup} A reference to this uniforms group.
  39059. */
  39060. remove( uniform ) {
  39061. const index = this.uniforms.indexOf( uniform );
  39062. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  39063. return this;
  39064. }
  39065. /**
  39066. * Sets the name of this uniforms group.
  39067. *
  39068. * @param {string} name - The name to set.
  39069. * @return {UniformsGroup} A reference to this uniforms group.
  39070. */
  39071. setName( name ) {
  39072. this.name = name;
  39073. return this;
  39074. }
  39075. /**
  39076. * Sets the usage of this uniforms group.
  39077. *
  39078. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  39079. * @return {UniformsGroup} A reference to this uniforms group.
  39080. */
  39081. setUsage( value ) {
  39082. this.usage = value;
  39083. return this;
  39084. }
  39085. /**
  39086. * Frees the GPU-related resources allocated by this instance. Call this
  39087. * method whenever this instance is no longer used in your app.
  39088. *
  39089. * @fires Texture#dispose
  39090. */
  39091. dispose() {
  39092. this.dispatchEvent( { type: 'dispose' } );
  39093. }
  39094. /**
  39095. * Copies the values of the given uniforms group to this instance.
  39096. *
  39097. * @param {UniformsGroup} source - The uniforms group to copy.
  39098. * @return {UniformsGroup} A reference to this uniforms group.
  39099. */
  39100. copy( source ) {
  39101. this.name = source.name;
  39102. this.usage = source.usage;
  39103. const uniformsSource = source.uniforms;
  39104. this.uniforms.length = 0;
  39105. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  39106. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  39107. for ( let j = 0; j < uniforms.length; j ++ ) {
  39108. this.uniforms.push( uniforms[ j ].clone() );
  39109. }
  39110. }
  39111. return this;
  39112. }
  39113. /**
  39114. * Returns a new uniforms group with copied values from this instance.
  39115. *
  39116. * @return {UniformsGroup} A clone of this instance.
  39117. */
  39118. clone() {
  39119. return new this.constructor().copy( this );
  39120. }
  39121. }
  39122. /**
  39123. * An instanced version of an interleaved buffer.
  39124. *
  39125. * @augments InterleavedBuffer
  39126. */
  39127. class InstancedInterleavedBuffer extends InterleavedBuffer {
  39128. /**
  39129. * Constructs a new instanced interleaved buffer.
  39130. *
  39131. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  39132. * @param {number} stride - The number of typed-array elements per vertex.
  39133. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  39134. */
  39135. constructor( array, stride, meshPerAttribute = 1 ) {
  39136. super( array, stride );
  39137. /**
  39138. * This flag can be used for type testing.
  39139. *
  39140. * @type {boolean}
  39141. * @readonly
  39142. * @default true
  39143. */
  39144. this.isInstancedInterleavedBuffer = true;
  39145. /**
  39146. * Defines how often a value of this buffer attribute should be repeated,
  39147. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  39148. *
  39149. * @type {number}
  39150. * @default 1
  39151. */
  39152. this.meshPerAttribute = meshPerAttribute;
  39153. }
  39154. copy( source ) {
  39155. super.copy( source );
  39156. this.meshPerAttribute = source.meshPerAttribute;
  39157. return this;
  39158. }
  39159. clone( data ) {
  39160. const ib = super.clone( data );
  39161. ib.meshPerAttribute = this.meshPerAttribute;
  39162. return ib;
  39163. }
  39164. toJSON( data ) {
  39165. const json = super.toJSON( data );
  39166. json.isInstancedInterleavedBuffer = true;
  39167. json.meshPerAttribute = this.meshPerAttribute;
  39168. return json;
  39169. }
  39170. }
  39171. /**
  39172. * An alternative version of a buffer attribute with more control over the VBO.
  39173. *
  39174. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  39175. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  39176. *
  39177. * The most common use case for this class is when some kind of GPGPU calculation interferes
  39178. * or even produces the VBOs in question.
  39179. *
  39180. * Notice that this class can only be used with {@link WebGLRenderer}.
  39181. */
  39182. class GLBufferAttribute {
  39183. /**
  39184. * Constructs a new GL buffer attribute.
  39185. *
  39186. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  39187. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39188. * @param {number} itemSize - The item size.
  39189. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39190. * @param {number} count - The expected number of vertices in VBO.
  39191. */
  39192. constructor( buffer, type, itemSize, elementSize, count ) {
  39193. /**
  39194. * This flag can be used for type testing.
  39195. *
  39196. * @type {boolean}
  39197. * @readonly
  39198. * @default true
  39199. */
  39200. this.isGLBufferAttribute = true;
  39201. /**
  39202. * The name of the buffer attribute.
  39203. *
  39204. * @type {string}
  39205. */
  39206. this.name = '';
  39207. /**
  39208. * The native WebGL buffer.
  39209. *
  39210. * @type {WebGLBuffer}
  39211. */
  39212. this.buffer = buffer;
  39213. /**
  39214. * The native data type.
  39215. *
  39216. * @type {number}
  39217. */
  39218. this.type = type;
  39219. /**
  39220. * The item size, see {@link BufferAttribute#itemSize}.
  39221. *
  39222. * @type {number}
  39223. */
  39224. this.itemSize = itemSize;
  39225. /**
  39226. * The corresponding size (in bytes) for the given `type` parameter.
  39227. *
  39228. * @type {number}
  39229. */
  39230. this.elementSize = elementSize;
  39231. /**
  39232. * The expected number of vertices in VBO.
  39233. *
  39234. * @type {number}
  39235. */
  39236. this.count = count;
  39237. /**
  39238. * A version number, incremented every time the `needsUpdate` is set to `true`.
  39239. *
  39240. * @type {number}
  39241. */
  39242. this.version = 0;
  39243. }
  39244. /**
  39245. * Flag to indicate that this attribute has changed and should be re-sent to
  39246. * the GPU. Set this to `true` when you modify the value of the array.
  39247. *
  39248. * @type {number}
  39249. * @default false
  39250. * @param {boolean} value
  39251. */
  39252. set needsUpdate( value ) {
  39253. if ( value === true ) this.version ++;
  39254. }
  39255. /**
  39256. * Sets the given native WebGL buffer.
  39257. *
  39258. * @param {WebGLBuffer} buffer - The buffer to set.
  39259. * @return {BufferAttribute} A reference to this instance.
  39260. */
  39261. setBuffer( buffer ) {
  39262. this.buffer = buffer;
  39263. return this;
  39264. }
  39265. /**
  39266. * Sets the given native data type and element size.
  39267. *
  39268. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39269. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39270. * @return {BufferAttribute} A reference to this instance.
  39271. */
  39272. setType( type, elementSize ) {
  39273. this.type = type;
  39274. this.elementSize = elementSize;
  39275. return this;
  39276. }
  39277. /**
  39278. * Sets the item size.
  39279. *
  39280. * @param {number} itemSize - The item size.
  39281. * @return {BufferAttribute} A reference to this instance.
  39282. */
  39283. setItemSize( itemSize ) {
  39284. this.itemSize = itemSize;
  39285. return this;
  39286. }
  39287. /**
  39288. * Sets the count (the expected number of vertices in VBO).
  39289. *
  39290. * @param {number} count - The count.
  39291. * @return {BufferAttribute} A reference to this instance.
  39292. */
  39293. setCount( count ) {
  39294. this.count = count;
  39295. return this;
  39296. }
  39297. }
  39298. const _matrix = /*@__PURE__*/ new Matrix4();
  39299. /**
  39300. * This class is designed to assist with raycasting. Raycasting is used for
  39301. * mouse picking (working out what objects in the 3d space the mouse is over)
  39302. * amongst other things.
  39303. */
  39304. class Raycaster {
  39305. /**
  39306. * Constructs a new raycaster.
  39307. *
  39308. * @param {Vector3} origin - The origin vector where the ray casts from.
  39309. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39310. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  39311. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  39312. */
  39313. constructor( origin, direction, near = 0, far = Infinity ) {
  39314. /**
  39315. * The ray used for raycasting.
  39316. *
  39317. * @type {Ray}
  39318. */
  39319. this.ray = new Ray( origin, direction );
  39320. /**
  39321. * All results returned are further away than near. Near can't be negative.
  39322. *
  39323. * @type {number}
  39324. * @default 0
  39325. */
  39326. this.near = near;
  39327. /**
  39328. * All results returned are further away than near. Near can't be negative.
  39329. *
  39330. * @type {number}
  39331. * @default Infinity
  39332. */
  39333. this.far = far;
  39334. /**
  39335. * The camera to use when raycasting against view-dependent objects such as
  39336. * billboarded objects like sprites. This field can be set manually or
  39337. * is set when calling `setFromCamera()`.
  39338. *
  39339. * @type {?Camera}
  39340. * @default null
  39341. */
  39342. this.camera = null;
  39343. /**
  39344. * Allows to selectively ignore 3D objects when performing intersection tests.
  39345. * The following code example ensures that only 3D objects on layer `1` will be
  39346. * honored by raycaster.
  39347. * ```js
  39348. * raycaster.layers.set( 1 );
  39349. * object.layers.enable( 1 );
  39350. * ```
  39351. *
  39352. * @type {Layers}
  39353. */
  39354. this.layers = new Layers();
  39355. /**
  39356. * A parameter object that configures the raycasting. It has the structure:
  39357. *
  39358. * ```
  39359. * {
  39360. * Mesh: {},
  39361. * Line: { threshold: 1 },
  39362. * LOD: {},
  39363. * Points: { threshold: 1 },
  39364. * Sprite: {}
  39365. * }
  39366. * ```
  39367. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  39368. *
  39369. * @type {Object}
  39370. */
  39371. this.params = {
  39372. Mesh: {},
  39373. Line: { threshold: 1 },
  39374. LOD: {},
  39375. Points: { threshold: 1 },
  39376. Sprite: {}
  39377. };
  39378. }
  39379. /**
  39380. * Updates the ray with a new origin and direction by copying the values from the arguments.
  39381. *
  39382. * @param {Vector3} origin - The origin vector where the ray casts from.
  39383. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39384. */
  39385. set( origin, direction ) {
  39386. // direction is assumed to be normalized (for accurate distance calculations)
  39387. this.ray.set( origin, direction );
  39388. }
  39389. /**
  39390. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  39391. *
  39392. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  39393. * X and Y components should be between `-1` and `1`.
  39394. * @param {Camera} camera - The camera from which the ray should originate.
  39395. */
  39396. setFromCamera( coords, camera ) {
  39397. if ( camera.isPerspectiveCamera ) {
  39398. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  39399. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  39400. this.camera = camera;
  39401. } else if ( camera.isOrthographicCamera ) {
  39402. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  39403. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  39404. this.camera = camera;
  39405. } else {
  39406. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  39407. }
  39408. }
  39409. /**
  39410. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  39411. *
  39412. * @param {WebXRController} controller - The controller to copy the position and direction from.
  39413. * @return {Raycaster} A reference to this raycaster.
  39414. */
  39415. setFromXRController( controller ) {
  39416. _matrix.identity().extractRotation( controller.matrixWorld );
  39417. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  39418. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  39419. return this;
  39420. }
  39421. /**
  39422. * The intersection point of a raycaster intersection test.
  39423. * @typedef {Object} Raycaster~Intersection
  39424. * @property {number} distance - The distance from the ray's origin to the intersection point.
  39425. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  39426. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  39427. * @property {Vector3} point - The intersection point, in world coordinates.
  39428. * @property {Object} face - The face that has been intersected.
  39429. * @property {number} faceIndex - The face index.
  39430. * @property {Object3D} object - The 3D object that has been intersected.
  39431. * @property {Vector2} uv - U,V coordinates at point of intersection.
  39432. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  39433. * @property {Vector3} uv1 - Interpolated normal vector at point of intersection.
  39434. * @property {number} instanceId - The index number of the instance where the ray
  39435. * intersects the {@link InstancedMesh}.
  39436. */
  39437. /**
  39438. * Checks all intersection between the ray and the object with or without the
  39439. * descendants. Intersections are returned sorted by distance, closest first.
  39440. *
  39441. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  39442. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  39443. * differently to ray casting than lines or points.
  39444. *
  39445. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  39446. * to be detected; intersections of the ray passing through the back of a face will not
  39447. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  39448. * to `THREE.DoubleSide`.
  39449. *
  39450. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  39451. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39452. * Otherwise it only checks intersection with the object.
  39453. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39454. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39455. */
  39456. intersectObject( object, recursive = true, intersects = [] ) {
  39457. intersect( object, this, intersects, recursive );
  39458. intersects.sort( ascSort );
  39459. return intersects;
  39460. }
  39461. /**
  39462. * Checks all intersection between the ray and the objects with or without
  39463. * the descendants. Intersections are returned sorted by distance, closest first.
  39464. *
  39465. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  39466. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39467. * Otherwise it only checks intersection with the object.
  39468. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39469. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39470. */
  39471. intersectObjects( objects, recursive = true, intersects = [] ) {
  39472. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  39473. intersect( objects[ i ], this, intersects, recursive );
  39474. }
  39475. intersects.sort( ascSort );
  39476. return intersects;
  39477. }
  39478. }
  39479. function ascSort( a, b ) {
  39480. return a.distance - b.distance;
  39481. }
  39482. function intersect( object, raycaster, intersects, recursive ) {
  39483. let propagate = true;
  39484. if ( object.layers.test( raycaster.layers ) ) {
  39485. const result = object.raycast( raycaster, intersects );
  39486. if ( result === false ) propagate = false;
  39487. }
  39488. if ( propagate === true && recursive === true ) {
  39489. const children = object.children;
  39490. for ( let i = 0, l = children.length; i < l; i ++ ) {
  39491. intersect( children[ i ], raycaster, intersects, true );
  39492. }
  39493. }
  39494. }
  39495. /**
  39496. * This class can be used to represent points in 3D space as
  39497. * [Spherical coordinates]{@link https://en.wikipedia.org/wiki/Spherical_coordinate_system}.
  39498. */
  39499. class Spherical {
  39500. /**
  39501. * Constructs a new spherical.
  39502. *
  39503. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  39504. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  39505. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  39506. */
  39507. constructor( radius = 1, phi = 0, theta = 0 ) {
  39508. /**
  39509. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  39510. *
  39511. * @type {number}
  39512. * @default 1
  39513. */
  39514. this.radius = radius;
  39515. /**
  39516. * The polar angle in radians from the y (up) axis.
  39517. *
  39518. * @type {number}
  39519. * @default 0
  39520. */
  39521. this.phi = phi;
  39522. /**
  39523. * The equator/azimuthal angle in radians around the y (up) axis.
  39524. *
  39525. * @type {number}
  39526. * @default 0
  39527. */
  39528. this.theta = theta;
  39529. }
  39530. /**
  39531. * Sets the spherical components by copying the given values.
  39532. *
  39533. * @param {number} radius - The radius.
  39534. * @param {number} phi - The polar angle.
  39535. * @param {number} theta - The azimuthal angle.
  39536. * @return {Spherical} A reference to this spherical.
  39537. */
  39538. set( radius, phi, theta ) {
  39539. this.radius = radius;
  39540. this.phi = phi;
  39541. this.theta = theta;
  39542. return this;
  39543. }
  39544. /**
  39545. * Copies the values of the given spherical to this instance.
  39546. *
  39547. * @param {Spherical} other - The spherical to copy.
  39548. * @return {Spherical} A reference to this spherical.
  39549. */
  39550. copy( other ) {
  39551. this.radius = other.radius;
  39552. this.phi = other.phi;
  39553. this.theta = other.theta;
  39554. return this;
  39555. }
  39556. /**
  39557. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  39558. * `0.000001`.
  39559. *
  39560. * @return {Spherical} A reference to this spherical.
  39561. */
  39562. makeSafe() {
  39563. const EPS = 0.000001;
  39564. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  39565. return this;
  39566. }
  39567. /**
  39568. * Sets the spherical components from the given vector which is assumed to hold
  39569. * Cartesian coordinates.
  39570. *
  39571. * @param {Vector3} v - The vector to set.
  39572. * @return {Spherical} A reference to this spherical.
  39573. */
  39574. setFromVector3( v ) {
  39575. return this.setFromCartesianCoords( v.x, v.y, v.z );
  39576. }
  39577. /**
  39578. * Sets the spherical components from the given Cartesian coordinates.
  39579. *
  39580. * @param {number} x - The x value.
  39581. * @param {number} y - The x value.
  39582. * @param {number} z - The x value.
  39583. * @return {Spherical} A reference to this spherical.
  39584. */
  39585. setFromCartesianCoords( x, y, z ) {
  39586. this.radius = Math.sqrt( x * x + y * y + z * z );
  39587. if ( this.radius === 0 ) {
  39588. this.theta = 0;
  39589. this.phi = 0;
  39590. } else {
  39591. this.theta = Math.atan2( x, z );
  39592. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  39593. }
  39594. return this;
  39595. }
  39596. /**
  39597. * Returns a new spherical with copied values from this instance.
  39598. *
  39599. * @return {Spherical} A clone of this instance.
  39600. */
  39601. clone() {
  39602. return new this.constructor().copy( this );
  39603. }
  39604. }
  39605. /**
  39606. * This class can be used to represent points in 3D space as
  39607. * [Cylindrical coordinates]{@link https://en.wikipedia.org/wiki/Cylindrical_coordinate_system}.
  39608. */
  39609. class Cylindrical {
  39610. /**
  39611. * Constructs a new cylindrical.
  39612. *
  39613. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  39614. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  39615. * @param {number} [y=0] - The height above the x-z plane.
  39616. */
  39617. constructor( radius = 1, theta = 0, y = 0 ) {
  39618. /**
  39619. * The distance from the origin to a point in the x-z plane.
  39620. *
  39621. * @type {number}
  39622. * @default 1
  39623. */
  39624. this.radius = radius;
  39625. /**
  39626. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  39627. *
  39628. * @type {number}
  39629. * @default 0
  39630. */
  39631. this.theta = theta;
  39632. /**
  39633. * The height above the x-z plane.
  39634. *
  39635. * @type {number}
  39636. * @default 0
  39637. */
  39638. this.y = y;
  39639. }
  39640. /**
  39641. * Sets the cylindrical components by copying the given values.
  39642. *
  39643. * @param {number} radius - The radius.
  39644. * @param {number} theta - The theta angle.
  39645. * @param {number} y - The height value.
  39646. * @return {Cylindrical} A reference to this cylindrical.
  39647. */
  39648. set( radius, theta, y ) {
  39649. this.radius = radius;
  39650. this.theta = theta;
  39651. this.y = y;
  39652. return this;
  39653. }
  39654. /**
  39655. * Copies the values of the given cylindrical to this instance.
  39656. *
  39657. * @param {Cylindrical} other - The cylindrical to copy.
  39658. * @return {Cylindrical} A reference to this cylindrical.
  39659. */
  39660. copy( other ) {
  39661. this.radius = other.radius;
  39662. this.theta = other.theta;
  39663. this.y = other.y;
  39664. return this;
  39665. }
  39666. /**
  39667. * Sets the cylindrical components from the given vector which is assumed to hold
  39668. * Cartesian coordinates.
  39669. *
  39670. * @param {Vector3} v - The vector to set.
  39671. * @return {Cylindrical} A reference to this cylindrical.
  39672. */
  39673. setFromVector3( v ) {
  39674. return this.setFromCartesianCoords( v.x, v.y, v.z );
  39675. }
  39676. /**
  39677. * Sets the cylindrical components from the given Cartesian coordinates.
  39678. *
  39679. * @param {number} x - The x value.
  39680. * @param {number} y - The x value.
  39681. * @param {number} z - The x value.
  39682. * @return {Cylindrical} A reference to this cylindrical.
  39683. */
  39684. setFromCartesianCoords( x, y, z ) {
  39685. this.radius = Math.sqrt( x * x + z * z );
  39686. this.theta = Math.atan2( x, z );
  39687. this.y = y;
  39688. return this;
  39689. }
  39690. /**
  39691. * Returns a new cylindrical with copied values from this instance.
  39692. *
  39693. * @return {Cylindrical} A clone of this instance.
  39694. */
  39695. clone() {
  39696. return new this.constructor().copy( this );
  39697. }
  39698. }
  39699. /**
  39700. * Represents a 2x2 matrix.
  39701. *
  39702. * A Note on Row-Major and Column-Major Ordering:
  39703. *
  39704. * The constructor and {@link Matrix2#set} method take arguments in
  39705. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  39706. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  39707. * This means that calling:
  39708. * ```js
  39709. * const m = new THREE.Matrix2();
  39710. * m.set( 11, 12,
  39711. * 21, 22 );
  39712. * ```
  39713. * will result in the elements array containing:
  39714. * ```js
  39715. * m.elements = [ 11, 21,
  39716. * 12, 22 ];
  39717. * ```
  39718. * and internally all calculations are performed using column-major ordering.
  39719. * However, as the actual ordering makes no difference mathematically and
  39720. * most people are used to thinking about matrices in row-major order, the
  39721. * three.js documentation shows matrices in row-major order. Just bear in
  39722. * mind that if you are reading the source code, you'll have to take the
  39723. * transpose of any matrices outlined here to make sense of the calculations.
  39724. */
  39725. class Matrix2 {
  39726. /**
  39727. * Constructs a new 2x2 matrix. The arguments are supposed to be
  39728. * in row-major order. If no arguments are provided, the constructor
  39729. * initializes the matrix as an identity matrix.
  39730. *
  39731. * @param {number} [n11] - 1-1 matrix element.
  39732. * @param {number} [n12] - 1-2 matrix element.
  39733. * @param {number} [n21] - 2-1 matrix element.
  39734. * @param {number} [n22] - 2-2 matrix element.
  39735. */
  39736. constructor( n11, n12, n21, n22 ) {
  39737. /**
  39738. * This flag can be used for type testing.
  39739. *
  39740. * @type {boolean}
  39741. * @readonly
  39742. * @default true
  39743. */
  39744. Matrix2.prototype.isMatrix2 = true;
  39745. /**
  39746. * A column-major list of matrix values.
  39747. *
  39748. * @type {Array<number>}
  39749. */
  39750. this.elements = [
  39751. 1, 0,
  39752. 0, 1,
  39753. ];
  39754. if ( n11 !== undefined ) {
  39755. this.set( n11, n12, n21, n22 );
  39756. }
  39757. }
  39758. /**
  39759. * Sets this matrix to the 2x2 identity matrix.
  39760. *
  39761. * @return {Matrix2} A reference to this matrix.
  39762. */
  39763. identity() {
  39764. this.set(
  39765. 1, 0,
  39766. 0, 1,
  39767. );
  39768. return this;
  39769. }
  39770. /**
  39771. * Sets the elements of the matrix from the given array.
  39772. *
  39773. * @param {Array<number>} array - The matrix elements in column-major order.
  39774. * @param {number} [offset=0] - Index of the first element in the array.
  39775. * @return {Matrix2} A reference to this matrix.
  39776. */
  39777. fromArray( array, offset = 0 ) {
  39778. for ( let i = 0; i < 4; i ++ ) {
  39779. this.elements[ i ] = array[ i + offset ];
  39780. }
  39781. return this;
  39782. }
  39783. /**
  39784. * Sets the elements of the matrix.The arguments are supposed to be
  39785. * in row-major order.
  39786. *
  39787. * @param {number} n11 - 1-1 matrix element.
  39788. * @param {number} n12 - 1-2 matrix element.
  39789. * @param {number} n21 - 2-1 matrix element.
  39790. * @param {number} n22 - 2-2 matrix element.
  39791. * @return {Matrix2} A reference to this matrix.
  39792. */
  39793. set( n11, n12, n21, n22 ) {
  39794. const te = this.elements;
  39795. te[ 0 ] = n11; te[ 2 ] = n12;
  39796. te[ 1 ] = n21; te[ 3 ] = n22;
  39797. return this;
  39798. }
  39799. }
  39800. const _vector$4 = /*@__PURE__*/ new Vector2();
  39801. /**
  39802. * Represents an axis-aligned bounding box (AABB) in 2D space.
  39803. */
  39804. class Box2 {
  39805. /**
  39806. * Constructs a new bounding box.
  39807. *
  39808. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  39809. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  39810. */
  39811. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  39812. /**
  39813. * This flag can be used for type testing.
  39814. *
  39815. * @type {boolean}
  39816. * @readonly
  39817. * @default true
  39818. */
  39819. this.isBox2 = true;
  39820. /**
  39821. * The lower boundary of the box.
  39822. *
  39823. * @type {Vector2}
  39824. */
  39825. this.min = min;
  39826. /**
  39827. * The upper boundary of the box.
  39828. *
  39829. * @type {Vector2}
  39830. */
  39831. this.max = max;
  39832. }
  39833. /**
  39834. * Sets the lower and upper boundaries of this box.
  39835. * Please note that this method only copies the values from the given objects.
  39836. *
  39837. * @param {Vector2} min - The lower boundary of the box.
  39838. * @param {Vector2} max - The upper boundary of the box.
  39839. * @return {Box2} A reference to this bounding box.
  39840. */
  39841. set( min, max ) {
  39842. this.min.copy( min );
  39843. this.max.copy( max );
  39844. return this;
  39845. }
  39846. /**
  39847. * Sets the upper and lower bounds of this box so it encloses the position data
  39848. * in the given array.
  39849. *
  39850. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  39851. * @return {Box2} A reference to this bounding box.
  39852. */
  39853. setFromPoints( points ) {
  39854. this.makeEmpty();
  39855. for ( let i = 0, il = points.length; i < il; i ++ ) {
  39856. this.expandByPoint( points[ i ] );
  39857. }
  39858. return this;
  39859. }
  39860. /**
  39861. * Centers this box on the given center vector and sets this box's width, height and
  39862. * depth to the given size values.
  39863. *
  39864. * @param {Vector2} center - The center of the box.
  39865. * @param {Vector2} size - The x and y dimensions of the box.
  39866. * @return {Box2} A reference to this bounding box.
  39867. */
  39868. setFromCenterAndSize( center, size ) {
  39869. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  39870. this.min.copy( center ).sub( halfSize );
  39871. this.max.copy( center ).add( halfSize );
  39872. return this;
  39873. }
  39874. /**
  39875. * Returns a new box with copied values from this instance.
  39876. *
  39877. * @return {Box2} A clone of this instance.
  39878. */
  39879. clone() {
  39880. return new this.constructor().copy( this );
  39881. }
  39882. /**
  39883. * Copies the values of the given box to this instance.
  39884. *
  39885. * @param {Box2} box - The box to copy.
  39886. * @return {Box2} A reference to this bounding box.
  39887. */
  39888. copy( box ) {
  39889. this.min.copy( box.min );
  39890. this.max.copy( box.max );
  39891. return this;
  39892. }
  39893. /**
  39894. * Makes this box empty which means in encloses a zero space in 2D.
  39895. *
  39896. * @return {Box2} A reference to this bounding box.
  39897. */
  39898. makeEmpty() {
  39899. this.min.x = this.min.y = + Infinity;
  39900. this.max.x = this.max.y = - Infinity;
  39901. return this;
  39902. }
  39903. /**
  39904. * Returns true if this box includes zero points within its bounds.
  39905. * Note that a box with equal lower and upper bounds still includes one
  39906. * point, the one both bounds share.
  39907. *
  39908. * @return {boolean} Whether this box is empty or not.
  39909. */
  39910. isEmpty() {
  39911. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  39912. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  39913. }
  39914. /**
  39915. * Returns the center point of this box.
  39916. *
  39917. * @param {Vector2} target - The target vector that is used to store the method's result.
  39918. * @return {Vector2} The center point.
  39919. */
  39920. getCenter( target ) {
  39921. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  39922. }
  39923. /**
  39924. * Returns the dimensions of this box.
  39925. *
  39926. * @param {Vector2} target - The target vector that is used to store the method's result.
  39927. * @return {Vector2} The size.
  39928. */
  39929. getSize( target ) {
  39930. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  39931. }
  39932. /**
  39933. * Expands the boundaries of this box to include the given point.
  39934. *
  39935. * @param {Vector2} point - The point that should be included by the bounding box.
  39936. * @return {Box2} A reference to this bounding box.
  39937. */
  39938. expandByPoint( point ) {
  39939. this.min.min( point );
  39940. this.max.max( point );
  39941. return this;
  39942. }
  39943. /**
  39944. * Expands this box equilaterally by the given vector. The width of this
  39945. * box will be expanded by the x component of the vector in both
  39946. * directions. The height of this box will be expanded by the y component of
  39947. * the vector in both directions.
  39948. *
  39949. * @param {Vector2} vector - The vector that should expand the bounding box.
  39950. * @return {Box2} A reference to this bounding box.
  39951. */
  39952. expandByVector( vector ) {
  39953. this.min.sub( vector );
  39954. this.max.add( vector );
  39955. return this;
  39956. }
  39957. /**
  39958. * Expands each dimension of the box by the given scalar. If negative, the
  39959. * dimensions of the box will be contracted.
  39960. *
  39961. * @param {number} scalar - The scalar value that should expand the bounding box.
  39962. * @return {Box2} A reference to this bounding box.
  39963. */
  39964. expandByScalar( scalar ) {
  39965. this.min.addScalar( - scalar );
  39966. this.max.addScalar( scalar );
  39967. return this;
  39968. }
  39969. /**
  39970. * Returns `true` if the given point lies within or on the boundaries of this box.
  39971. *
  39972. * @param {Vector2} point - The point to test.
  39973. * @return {boolean} Whether the bounding box contains the given point or not.
  39974. */
  39975. containsPoint( point ) {
  39976. return point.x >= this.min.x && point.x <= this.max.x &&
  39977. point.y >= this.min.y && point.y <= this.max.y;
  39978. }
  39979. /**
  39980. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  39981. * If this box and the given one are identical, this function also returns `true`.
  39982. *
  39983. * @param {Box2} box - The bounding box to test.
  39984. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  39985. */
  39986. containsBox( box ) {
  39987. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  39988. this.min.y <= box.min.y && box.max.y <= this.max.y;
  39989. }
  39990. /**
  39991. * Returns a point as a proportion of this box's width and height.
  39992. *
  39993. * @param {Vector2} point - A point in 2D space.
  39994. * @param {Vector2} target - The target vector that is used to store the method's result.
  39995. * @return {Vector2} A point as a proportion of this box's width and height.
  39996. */
  39997. getParameter( point, target ) {
  39998. // This can potentially have a divide by zero if the box
  39999. // has a size dimension of 0.
  40000. return target.set(
  40001. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  40002. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  40003. );
  40004. }
  40005. /**
  40006. * Returns `true` if the given bounding box intersects with this bounding box.
  40007. *
  40008. * @param {Box2} box - The bounding box to test.
  40009. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  40010. */
  40011. intersectsBox( box ) {
  40012. // using 4 splitting planes to rule out intersections
  40013. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  40014. box.max.y >= this.min.y && box.min.y <= this.max.y;
  40015. }
  40016. /**
  40017. * Clamps the given point within the bounds of this box.
  40018. *
  40019. * @param {Vector2} point - The point to clamp.
  40020. * @param {Vector2} target - The target vector that is used to store the method's result.
  40021. * @return {Vector2} The clamped point.
  40022. */
  40023. clampPoint( point, target ) {
  40024. return target.copy( point ).clamp( this.min, this.max );
  40025. }
  40026. /**
  40027. * Returns the euclidean distance from any edge of this box to the specified point. If
  40028. * the given point lies inside of this box, the distance will be `0`.
  40029. *
  40030. * @param {Vector2} point - The point to compute the distance to.
  40031. * @return {number} The euclidean distance.
  40032. */
  40033. distanceToPoint( point ) {
  40034. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  40035. }
  40036. /**
  40037. * Computes the intersection of this bounding box and the given one, setting the upper
  40038. * bound of this box to the lesser of the two boxes' upper bounds and the
  40039. * lower bound of this box to the greater of the two boxes' lower bounds. If
  40040. * there's no overlap, makes this box empty.
  40041. *
  40042. * @param {Box2} box - The bounding box to intersect with.
  40043. * @return {Box2} A reference to this bounding box.
  40044. */
  40045. intersect( box ) {
  40046. this.min.max( box.min );
  40047. this.max.min( box.max );
  40048. if ( this.isEmpty() ) this.makeEmpty();
  40049. return this;
  40050. }
  40051. /**
  40052. * Computes the union of this box and another and the given one, setting the upper
  40053. * bound of this box to the greater of the two boxes' upper bounds and the
  40054. * lower bound of this box to the lesser of the two boxes' lower bounds.
  40055. *
  40056. * @param {Box2} box - The bounding box that will be unioned with this instance.
  40057. * @return {Box2} A reference to this bounding box.
  40058. */
  40059. union( box ) {
  40060. this.min.min( box.min );
  40061. this.max.max( box.max );
  40062. return this;
  40063. }
  40064. /**
  40065. * Adds the given offset to both the upper and lower bounds of this bounding box,
  40066. * effectively moving it in 2D space.
  40067. *
  40068. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  40069. * @return {Box2} A reference to this bounding box.
  40070. */
  40071. translate( offset ) {
  40072. this.min.add( offset );
  40073. this.max.add( offset );
  40074. return this;
  40075. }
  40076. /**
  40077. * Returns `true` if this bounding box is equal with the given one.
  40078. *
  40079. * @param {Box2} box - The box to test for equality.
  40080. * @return {boolean} Whether this bounding box is equal with the given one.
  40081. */
  40082. equals( box ) {
  40083. return box.min.equals( this.min ) && box.max.equals( this.max );
  40084. }
  40085. }
  40086. const _startP = /*@__PURE__*/ new Vector3();
  40087. const _startEnd = /*@__PURE__*/ new Vector3();
  40088. /**
  40089. * An analytical line segment in 3D space represented by a start and end point.
  40090. */
  40091. class Line3 {
  40092. /**
  40093. * Constructs a new line segment.
  40094. *
  40095. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  40096. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  40097. */
  40098. constructor( start = new Vector3(), end = new Vector3() ) {
  40099. /**
  40100. * Start of the line segment.
  40101. *
  40102. * @type {Vector3}
  40103. */
  40104. this.start = start;
  40105. /**
  40106. * End of the line segment.
  40107. *
  40108. * @type {Vector3}
  40109. */
  40110. this.end = end;
  40111. }
  40112. /**
  40113. * Sets the start and end values by copying the given vectors.
  40114. *
  40115. * @param {Vector3} start - The start point.
  40116. * @param {Vector3} end - The end point.
  40117. * @return {Line3} A reference to this line segment.
  40118. */
  40119. set( start, end ) {
  40120. this.start.copy( start );
  40121. this.end.copy( end );
  40122. return this;
  40123. }
  40124. /**
  40125. * Copies the values of the given line segment to this instance.
  40126. *
  40127. * @param {Line3} line - The line segment to copy.
  40128. * @return {Line3} A reference to this line segment.
  40129. */
  40130. copy( line ) {
  40131. this.start.copy( line.start );
  40132. this.end.copy( line.end );
  40133. return this;
  40134. }
  40135. /**
  40136. * Returns the center of the line segment.
  40137. *
  40138. * @param {Vector3} target - The target vector that is used to store the method's result.
  40139. * @return {Vector3} The center point.
  40140. */
  40141. getCenter( target ) {
  40142. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  40143. }
  40144. /**
  40145. * Returns the delta vector of the line segment's start and end point.
  40146. *
  40147. * @param {Vector3} target - The target vector that is used to store the method's result.
  40148. * @return {Vector3} The delta vector.
  40149. */
  40150. delta( target ) {
  40151. return target.subVectors( this.end, this.start );
  40152. }
  40153. /**
  40154. * Returns the squared Euclidean distance between the line' start and end point.
  40155. *
  40156. * @return {number} The squared Euclidean distance.
  40157. */
  40158. distanceSq() {
  40159. return this.start.distanceToSquared( this.end );
  40160. }
  40161. /**
  40162. * Returns the Euclidean distance between the line' start and end point.
  40163. *
  40164. * @return {number} The Euclidean distance.
  40165. */
  40166. distance() {
  40167. return this.start.distanceTo( this.end );
  40168. }
  40169. /**
  40170. * Returns a vector at a certain position along the line segment.
  40171. *
  40172. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  40173. * @param {Vector3} target - The target vector that is used to store the method's result.
  40174. * @return {Vector3} The delta vector.
  40175. */
  40176. at( t, target ) {
  40177. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40178. }
  40179. /**
  40180. * Returns a point parameter based on the closest point as projected on the line segment.
  40181. *
  40182. * @param {Vector3} point - The point for which to return a point parameter.
  40183. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40184. * @return {number} The point parameter.
  40185. */
  40186. closestPointToPointParameter( point, clampToLine ) {
  40187. _startP.subVectors( point, this.start );
  40188. _startEnd.subVectors( this.end, this.start );
  40189. const startEnd2 = _startEnd.dot( _startEnd );
  40190. const startEnd_startP = _startEnd.dot( _startP );
  40191. let t = startEnd_startP / startEnd2;
  40192. if ( clampToLine ) {
  40193. t = clamp( t, 0, 1 );
  40194. }
  40195. return t;
  40196. }
  40197. /**
  40198. * Returns the closets point on the line for a given point.
  40199. *
  40200. * @param {Vector3} point - The point to compute the closest point on the line for.
  40201. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40202. * @param {Vector3} target - The target vector that is used to store the method's result.
  40203. * @return {Vector3} The closest point on the line.
  40204. */
  40205. closestPointToPoint( point, clampToLine, target ) {
  40206. const t = this.closestPointToPointParameter( point, clampToLine );
  40207. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40208. }
  40209. /**
  40210. * Applies a 4x4 transformation matrix to this line segment.
  40211. *
  40212. * @param {Matrix4} matrix - The transformation matrix.
  40213. * @return {Line3} A reference to this line segment.
  40214. */
  40215. applyMatrix4( matrix ) {
  40216. this.start.applyMatrix4( matrix );
  40217. this.end.applyMatrix4( matrix );
  40218. return this;
  40219. }
  40220. /**
  40221. * Returns `true` if this line segment is equal with the given one.
  40222. *
  40223. * @param {Line3} line - The line segment to test for equality.
  40224. * @return {boolean} Whether this line segment is equal with the given one.
  40225. */
  40226. equals( line ) {
  40227. return line.start.equals( this.start ) && line.end.equals( this.end );
  40228. }
  40229. /**
  40230. * Returns a new line segment with copied values from this instance.
  40231. *
  40232. * @return {Line3} A clone of this instance.
  40233. */
  40234. clone() {
  40235. return new this.constructor().copy( this );
  40236. }
  40237. }
  40238. const _vector$3 = /*@__PURE__*/ new Vector3();
  40239. /**
  40240. * This displays a cone shaped helper object for a {@link SpotLight}.
  40241. *
  40242. * ```js
  40243. * const spotLight = new THREE.SpotLight( 0xffffff );
  40244. * spotLight.position.set( 10, 10, 10 );
  40245. * scene.add( spotLight );
  40246. *
  40247. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  40248. * scene.add( spotLightHelper );
  40249. * ```
  40250. *
  40251. * @augments Object3D
  40252. */
  40253. class SpotLightHelper extends Object3D {
  40254. /**
  40255. * Constructs a new spot light helper.
  40256. *
  40257. * @param {HemisphereLight} light - The light to be visualized.
  40258. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40259. * the color of the light.
  40260. */
  40261. constructor( light, color ) {
  40262. super();
  40263. /**
  40264. * The light being visualized.
  40265. *
  40266. * @type {SpotLight}
  40267. */
  40268. this.light = light;
  40269. this.matrixAutoUpdate = false;
  40270. /**
  40271. * The color parameter passed in the constructor.
  40272. * If not set, the helper will take the color of the light.
  40273. *
  40274. * @type {number|Color|string}
  40275. */
  40276. this.color = color;
  40277. this.type = 'SpotLightHelper';
  40278. const geometry = new BufferGeometry();
  40279. const positions = [
  40280. 0, 0, 0, 0, 0, 1,
  40281. 0, 0, 0, 1, 0, 1,
  40282. 0, 0, 0, -1, 0, 1,
  40283. 0, 0, 0, 0, 1, 1,
  40284. 0, 0, 0, 0, -1, 1
  40285. ];
  40286. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  40287. const p1 = ( i / l ) * Math.PI * 2;
  40288. const p2 = ( j / l ) * Math.PI * 2;
  40289. positions.push(
  40290. Math.cos( p1 ), Math.sin( p1 ), 1,
  40291. Math.cos( p2 ), Math.sin( p2 ), 1
  40292. );
  40293. }
  40294. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  40295. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  40296. this.cone = new LineSegments( geometry, material );
  40297. this.add( this.cone );
  40298. this.update();
  40299. }
  40300. /**
  40301. * Frees the GPU-related resources allocated by this instance. Call this
  40302. * method whenever this instance is no longer used in your app.
  40303. */
  40304. dispose() {
  40305. this.cone.geometry.dispose();
  40306. this.cone.material.dispose();
  40307. }
  40308. /**
  40309. * Updates the helper to match the position and direction of the
  40310. * light being visualized.
  40311. */
  40312. update() {
  40313. this.light.updateWorldMatrix( true, false );
  40314. this.light.target.updateWorldMatrix( true, false );
  40315. // update the local matrix based on the parent and light target transforms
  40316. if ( this.parent ) {
  40317. this.parent.updateWorldMatrix( true );
  40318. this.matrix
  40319. .copy( this.parent.matrixWorld )
  40320. .invert()
  40321. .multiply( this.light.matrixWorld );
  40322. } else {
  40323. this.matrix.copy( this.light.matrixWorld );
  40324. }
  40325. this.matrixWorld.copy( this.light.matrixWorld );
  40326. const coneLength = this.light.distance ? this.light.distance : 1000;
  40327. const coneWidth = coneLength * Math.tan( this.light.angle );
  40328. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  40329. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  40330. this.cone.lookAt( _vector$3 );
  40331. if ( this.color !== undefined ) {
  40332. this.cone.material.color.set( this.color );
  40333. } else {
  40334. this.cone.material.color.copy( this.light.color );
  40335. }
  40336. }
  40337. }
  40338. const _vector$2 = /*@__PURE__*/ new Vector3();
  40339. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  40340. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  40341. /**
  40342. * A helper object to assist with visualizing a {@link Skeleton}.
  40343. *
  40344. * ```js
  40345. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  40346. * scene.add( helper );
  40347. * ```
  40348. *
  40349. * @augments LineSegments
  40350. */
  40351. class SkeletonHelper extends LineSegments {
  40352. /**
  40353. * Constructs a new hemisphere light helper.
  40354. *
  40355. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  40356. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  40357. */
  40358. constructor( object ) {
  40359. const bones = getBoneList( object );
  40360. const geometry = new BufferGeometry();
  40361. const vertices = [];
  40362. const colors = [];
  40363. const color1 = new Color( 0, 0, 1 );
  40364. const color2 = new Color( 0, 1, 0 );
  40365. for ( let i = 0; i < bones.length; i ++ ) {
  40366. const bone = bones[ i ];
  40367. if ( bone.parent && bone.parent.isBone ) {
  40368. vertices.push( 0, 0, 0 );
  40369. vertices.push( 0, 0, 0 );
  40370. colors.push( color1.r, color1.g, color1.b );
  40371. colors.push( color2.r, color2.g, color2.b );
  40372. }
  40373. }
  40374. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40375. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  40376. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  40377. super( geometry, material );
  40378. /**
  40379. * This flag can be used for type testing.
  40380. *
  40381. * @type {boolean}
  40382. * @readonly
  40383. * @default true
  40384. */
  40385. this.isSkeletonHelper = true;
  40386. this.type = 'SkeletonHelper';
  40387. /**
  40388. * The object being visualized.
  40389. *
  40390. * @type {Object3D}
  40391. */
  40392. this.root = object;
  40393. /**
  40394. * he list of bones that the helper visualizes.
  40395. *
  40396. * @type {Array<Bone>}
  40397. */
  40398. this.bones = bones;
  40399. this.matrix = object.matrixWorld;
  40400. this.matrixAutoUpdate = false;
  40401. }
  40402. updateMatrixWorld( force ) {
  40403. const bones = this.bones;
  40404. const geometry = this.geometry;
  40405. const position = geometry.getAttribute( 'position' );
  40406. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  40407. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  40408. const bone = bones[ i ];
  40409. if ( bone.parent && bone.parent.isBone ) {
  40410. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  40411. _vector$2.setFromMatrixPosition( _boneMatrix );
  40412. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  40413. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  40414. _vector$2.setFromMatrixPosition( _boneMatrix );
  40415. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  40416. j += 2;
  40417. }
  40418. }
  40419. geometry.getAttribute( 'position' ).needsUpdate = true;
  40420. super.updateMatrixWorld( force );
  40421. }
  40422. /**
  40423. * Frees the GPU-related resources allocated by this instance. Call this
  40424. * method whenever this instance is no longer used in your app.
  40425. */
  40426. dispose() {
  40427. this.geometry.dispose();
  40428. this.material.dispose();
  40429. }
  40430. }
  40431. function getBoneList( object ) {
  40432. const boneList = [];
  40433. if ( object.isBone === true ) {
  40434. boneList.push( object );
  40435. }
  40436. for ( let i = 0; i < object.children.length; i ++ ) {
  40437. boneList.push( ...getBoneList( object.children[ i ] ) );
  40438. }
  40439. return boneList;
  40440. }
  40441. /**
  40442. * This displays a helper object consisting of a spherical mesh for
  40443. * visualizing an instance of {@link PointLight}.
  40444. *
  40445. * ```js
  40446. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  40447. * pointLight.position.set( 10, 10, 10 );
  40448. * scene.add( pointLight );
  40449. *
  40450. * const sphereSize = 1;
  40451. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  40452. * scene.add( pointLightHelper );
  40453. * ```
  40454. *
  40455. * @augments Mesh
  40456. */
  40457. class PointLightHelper extends Mesh {
  40458. /**
  40459. * Constructs a new point light helper.
  40460. *
  40461. * @param {PointLight} light - The light to be visualized.
  40462. * @param {number} [sphereSize=1] - The size of the sphere helper.
  40463. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40464. * the color of the light.
  40465. */
  40466. constructor( light, sphereSize, color ) {
  40467. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  40468. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  40469. super( geometry, material );
  40470. /**
  40471. * The light being visualized.
  40472. *
  40473. * @type {HemisphereLight}
  40474. */
  40475. this.light = light;
  40476. /**
  40477. * The color parameter passed in the constructor.
  40478. * If not set, the helper will take the color of the light.
  40479. *
  40480. * @type {number|Color|string}
  40481. */
  40482. this.color = color;
  40483. this.type = 'PointLightHelper';
  40484. this.matrix = this.light.matrixWorld;
  40485. this.matrixAutoUpdate = false;
  40486. this.update();
  40487. /*
  40488. // TODO: delete this comment?
  40489. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  40490. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  40491. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  40492. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  40493. const d = light.distance;
  40494. if ( d === 0.0 ) {
  40495. this.lightDistance.visible = false;
  40496. } else {
  40497. this.lightDistance.scale.set( d, d, d );
  40498. }
  40499. this.add( this.lightDistance );
  40500. */
  40501. }
  40502. /**
  40503. * Frees the GPU-related resources allocated by this instance. Call this
  40504. * method whenever this instance is no longer used in your app.
  40505. */
  40506. dispose() {
  40507. this.geometry.dispose();
  40508. this.material.dispose();
  40509. }
  40510. /**
  40511. * Updates the helper to match the position of the
  40512. * light being visualized.
  40513. */
  40514. update() {
  40515. this.light.updateWorldMatrix( true, false );
  40516. if ( this.color !== undefined ) {
  40517. this.material.color.set( this.color );
  40518. } else {
  40519. this.material.color.copy( this.light.color );
  40520. }
  40521. /*
  40522. const d = this.light.distance;
  40523. if ( d === 0.0 ) {
  40524. this.lightDistance.visible = false;
  40525. } else {
  40526. this.lightDistance.visible = true;
  40527. this.lightDistance.scale.set( d, d, d );
  40528. }
  40529. */
  40530. }
  40531. }
  40532. const _vector$1 = /*@__PURE__*/ new Vector3();
  40533. const _color1 = /*@__PURE__*/ new Color();
  40534. const _color2 = /*@__PURE__*/ new Color();
  40535. /**
  40536. * Creates a visual aid consisting of a spherical mesh for a
  40537. * given {@link HemisphereLight}.
  40538. *
  40539. * ```js
  40540. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  40541. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  40542. * scene.add( helper );
  40543. * ```
  40544. *
  40545. * @augments Object3D
  40546. */
  40547. class HemisphereLightHelper extends Object3D {
  40548. /**
  40549. * Constructs a new hemisphere light helper.
  40550. *
  40551. * @param {HemisphereLight} light - The light to be visualized.
  40552. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  40553. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40554. * the color of the light.
  40555. */
  40556. constructor( light, size, color ) {
  40557. super();
  40558. /**
  40559. * The light being visualized.
  40560. *
  40561. * @type {HemisphereLight}
  40562. */
  40563. this.light = light;
  40564. this.matrix = light.matrixWorld;
  40565. this.matrixAutoUpdate = false;
  40566. /**
  40567. * The color parameter passed in the constructor.
  40568. * If not set, the helper will take the color of the light.
  40569. *
  40570. * @type {number|Color|string}
  40571. */
  40572. this.color = color;
  40573. this.type = 'HemisphereLightHelper';
  40574. const geometry = new OctahedronGeometry( size );
  40575. geometry.rotateY( Math.PI * 0.5 );
  40576. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  40577. if ( this.color === undefined ) this.material.vertexColors = true;
  40578. const position = geometry.getAttribute( 'position' );
  40579. const colors = new Float32Array( position.count * 3 );
  40580. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  40581. this.add( new Mesh( geometry, this.material ) );
  40582. this.update();
  40583. }
  40584. /**
  40585. * Frees the GPU-related resources allocated by this instance. Call this
  40586. * method whenever this instance is no longer used in your app.
  40587. */
  40588. dispose() {
  40589. this.children[ 0 ].geometry.dispose();
  40590. this.children[ 0 ].material.dispose();
  40591. }
  40592. /**
  40593. * Updates the helper to match the position and direction of the
  40594. * light being visualized.
  40595. */
  40596. update() {
  40597. const mesh = this.children[ 0 ];
  40598. if ( this.color !== undefined ) {
  40599. this.material.color.set( this.color );
  40600. } else {
  40601. const colors = mesh.geometry.getAttribute( 'color' );
  40602. _color1.copy( this.light.color );
  40603. _color2.copy( this.light.groundColor );
  40604. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  40605. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  40606. colors.setXYZ( i, color.r, color.g, color.b );
  40607. }
  40608. colors.needsUpdate = true;
  40609. }
  40610. this.light.updateWorldMatrix( true, false );
  40611. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  40612. }
  40613. }
  40614. /**
  40615. * The helper is an object to define grids. Grids are two-dimensional
  40616. * arrays of lines.
  40617. *
  40618. * ```js
  40619. * const size = 10;
  40620. * const divisions = 10;
  40621. *
  40622. * const gridHelper = new THREE.GridHelper( size, divisions );
  40623. * scene.add( gridHelper );
  40624. * ```
  40625. *
  40626. * @augments LineSegments
  40627. */
  40628. class GridHelper extends LineSegments {
  40629. /**
  40630. * Constructs a new grid helper.
  40631. *
  40632. * @param {number} [size=10] - The size of the grid.
  40633. * @param {number} [divisions=10] - The number of divisions across the grid.
  40634. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  40635. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  40636. */
  40637. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  40638. color1 = new Color( color1 );
  40639. color2 = new Color( color2 );
  40640. const center = divisions / 2;
  40641. const step = size / divisions;
  40642. const halfSize = size / 2;
  40643. const vertices = [], colors = [];
  40644. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  40645. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  40646. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  40647. const color = i === center ? color1 : color2;
  40648. color.toArray( colors, j ); j += 3;
  40649. color.toArray( colors, j ); j += 3;
  40650. color.toArray( colors, j ); j += 3;
  40651. color.toArray( colors, j ); j += 3;
  40652. }
  40653. const geometry = new BufferGeometry();
  40654. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40655. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  40656. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  40657. super( geometry, material );
  40658. this.type = 'GridHelper';
  40659. }
  40660. /**
  40661. * Frees the GPU-related resources allocated by this instance. Call this
  40662. * method whenever this instance is no longer used in your app.
  40663. */
  40664. dispose() {
  40665. this.geometry.dispose();
  40666. this.material.dispose();
  40667. }
  40668. }
  40669. /**
  40670. * This helper is an object to define polar grids. Grids are
  40671. * two-dimensional arrays of lines.
  40672. *
  40673. * ```js
  40674. * const radius = 10;
  40675. * const sectors = 16;
  40676. * const rings = 8;
  40677. * const divisions = 64;
  40678. *
  40679. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  40680. * scene.add( helper );
  40681. * ```
  40682. *
  40683. * @augments LineSegments
  40684. */
  40685. class PolarGridHelper extends LineSegments {
  40686. /**
  40687. * Constructs a new polar grid helper.
  40688. *
  40689. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  40690. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  40691. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  40692. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  40693. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  40694. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  40695. */
  40696. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  40697. color1 = new Color( color1 );
  40698. color2 = new Color( color2 );
  40699. const vertices = [];
  40700. const colors = [];
  40701. // create the sectors
  40702. if ( sectors > 1 ) {
  40703. for ( let i = 0; i < sectors; i ++ ) {
  40704. const v = ( i / sectors ) * ( Math.PI * 2 );
  40705. const x = Math.sin( v ) * radius;
  40706. const z = Math.cos( v ) * radius;
  40707. vertices.push( 0, 0, 0 );
  40708. vertices.push( x, 0, z );
  40709. const color = ( i & 1 ) ? color1 : color2;
  40710. colors.push( color.r, color.g, color.b );
  40711. colors.push( color.r, color.g, color.b );
  40712. }
  40713. }
  40714. // create the rings
  40715. for ( let i = 0; i < rings; i ++ ) {
  40716. const color = ( i & 1 ) ? color1 : color2;
  40717. const r = radius - ( radius / rings * i );
  40718. for ( let j = 0; j < divisions; j ++ ) {
  40719. // first vertex
  40720. let v = ( j / divisions ) * ( Math.PI * 2 );
  40721. let x = Math.sin( v ) * r;
  40722. let z = Math.cos( v ) * r;
  40723. vertices.push( x, 0, z );
  40724. colors.push( color.r, color.g, color.b );
  40725. // second vertex
  40726. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  40727. x = Math.sin( v ) * r;
  40728. z = Math.cos( v ) * r;
  40729. vertices.push( x, 0, z );
  40730. colors.push( color.r, color.g, color.b );
  40731. }
  40732. }
  40733. const geometry = new BufferGeometry();
  40734. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40735. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  40736. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  40737. super( geometry, material );
  40738. this.type = 'PolarGridHelper';
  40739. }
  40740. /**
  40741. * Frees the GPU-related resources allocated by this instance. Call this
  40742. * method whenever this instance is no longer used in your app.
  40743. */
  40744. dispose() {
  40745. this.geometry.dispose();
  40746. this.material.dispose();
  40747. }
  40748. }
  40749. const _v1 = /*@__PURE__*/ new Vector3();
  40750. const _v2 = /*@__PURE__*/ new Vector3();
  40751. const _v3 = /*@__PURE__*/ new Vector3();
  40752. /**
  40753. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  40754. * effect on the scene. This consists of plane and a line representing the
  40755. * light's position and direction.
  40756. *
  40757. * ```js
  40758. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  40759. * scene.add( light );
  40760. *
  40761. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  40762. * scene.add( helper );
  40763. * ```
  40764. *
  40765. * @augments Object3D
  40766. */
  40767. class DirectionalLightHelper extends Object3D {
  40768. /**
  40769. * Constructs a new directional light helper.
  40770. *
  40771. * @param {DirectionalLight} light - The light to be visualized.
  40772. * @param {number} [size=1] - The dimensions of the plane.
  40773. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40774. * the color of the light.
  40775. */
  40776. constructor( light, size, color ) {
  40777. super();
  40778. /**
  40779. * The light being visualized.
  40780. *
  40781. * @type {DirectionalLight}
  40782. */
  40783. this.light = light;
  40784. this.matrix = light.matrixWorld;
  40785. this.matrixAutoUpdate = false;
  40786. /**
  40787. * The color parameter passed in the constructor.
  40788. * If not set, the helper will take the color of the light.
  40789. *
  40790. * @type {number|Color|string}
  40791. */
  40792. this.color = color;
  40793. this.type = 'DirectionalLightHelper';
  40794. if ( size === undefined ) size = 1;
  40795. let geometry = new BufferGeometry();
  40796. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  40797. - size, size, 0,
  40798. size, size, 0,
  40799. size, - size, 0,
  40800. - size, - size, 0,
  40801. - size, size, 0
  40802. ], 3 ) );
  40803. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  40804. /**
  40805. * Contains the line showing the location of the directional light.
  40806. *
  40807. * @type {Line}
  40808. */
  40809. this.lightPlane = new Line( geometry, material );
  40810. this.add( this.lightPlane );
  40811. geometry = new BufferGeometry();
  40812. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  40813. /**
  40814. * Represents the target line of the directional light.
  40815. *
  40816. * @type {Line}
  40817. */
  40818. this.targetLine = new Line( geometry, material );
  40819. this.add( this.targetLine );
  40820. this.update();
  40821. }
  40822. /**
  40823. * Frees the GPU-related resources allocated by this instance. Call this
  40824. * method whenever this instance is no longer used in your app.
  40825. */
  40826. dispose() {
  40827. this.lightPlane.geometry.dispose();
  40828. this.lightPlane.material.dispose();
  40829. this.targetLine.geometry.dispose();
  40830. this.targetLine.material.dispose();
  40831. }
  40832. /**
  40833. * Updates the helper to match the position and direction of the
  40834. * light being visualized.
  40835. */
  40836. update() {
  40837. this.light.updateWorldMatrix( true, false );
  40838. this.light.target.updateWorldMatrix( true, false );
  40839. _v1.setFromMatrixPosition( this.light.matrixWorld );
  40840. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  40841. _v3.subVectors( _v2, _v1 );
  40842. this.lightPlane.lookAt( _v2 );
  40843. if ( this.color !== undefined ) {
  40844. this.lightPlane.material.color.set( this.color );
  40845. this.targetLine.material.color.set( this.color );
  40846. } else {
  40847. this.lightPlane.material.color.copy( this.light.color );
  40848. this.targetLine.material.color.copy( this.light.color );
  40849. }
  40850. this.targetLine.lookAt( _v2 );
  40851. this.targetLine.scale.z = _v3.length();
  40852. }
  40853. }
  40854. const _vector = /*@__PURE__*/ new Vector3();
  40855. const _camera = /*@__PURE__*/ new Camera();
  40856. /**
  40857. * This helps with visualizing what a camera contains in its frustum. It
  40858. * visualizes the frustum of a camera using a line segments.
  40859. *
  40860. * Based on frustum visualization in [lightgl.js shadowmap example]{@link https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html}.
  40861. *
  40862. * `CameraHelper` must be a child of the scene.
  40863. *
  40864. * ```js
  40865. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  40866. * const helper = new THREE.CameraHelper( camera );
  40867. * scene.add( helper );
  40868. * ```
  40869. *
  40870. * @augments LineSegments
  40871. */
  40872. class CameraHelper extends LineSegments {
  40873. /**
  40874. * Constructs a new arrow helper.
  40875. *
  40876. * @param {Camera} camera - The camera to visualize.
  40877. */
  40878. constructor( camera ) {
  40879. const geometry = new BufferGeometry();
  40880. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  40881. const vertices = [];
  40882. const colors = [];
  40883. const pointMap = {};
  40884. // near
  40885. addLine( 'n1', 'n2' );
  40886. addLine( 'n2', 'n4' );
  40887. addLine( 'n4', 'n3' );
  40888. addLine( 'n3', 'n1' );
  40889. // far
  40890. addLine( 'f1', 'f2' );
  40891. addLine( 'f2', 'f4' );
  40892. addLine( 'f4', 'f3' );
  40893. addLine( 'f3', 'f1' );
  40894. // sides
  40895. addLine( 'n1', 'f1' );
  40896. addLine( 'n2', 'f2' );
  40897. addLine( 'n3', 'f3' );
  40898. addLine( 'n4', 'f4' );
  40899. // cone
  40900. addLine( 'p', 'n1' );
  40901. addLine( 'p', 'n2' );
  40902. addLine( 'p', 'n3' );
  40903. addLine( 'p', 'n4' );
  40904. // up
  40905. addLine( 'u1', 'u2' );
  40906. addLine( 'u2', 'u3' );
  40907. addLine( 'u3', 'u1' );
  40908. // target
  40909. addLine( 'c', 't' );
  40910. addLine( 'p', 'c' );
  40911. // cross
  40912. addLine( 'cn1', 'cn2' );
  40913. addLine( 'cn3', 'cn4' );
  40914. addLine( 'cf1', 'cf2' );
  40915. addLine( 'cf3', 'cf4' );
  40916. function addLine( a, b ) {
  40917. addPoint( a );
  40918. addPoint( b );
  40919. }
  40920. function addPoint( id ) {
  40921. vertices.push( 0, 0, 0 );
  40922. colors.push( 0, 0, 0 );
  40923. if ( pointMap[ id ] === undefined ) {
  40924. pointMap[ id ] = [];
  40925. }
  40926. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  40927. }
  40928. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40929. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  40930. super( geometry, material );
  40931. this.type = 'CameraHelper';
  40932. /**
  40933. * The camera being visualized.
  40934. *
  40935. * @type {Camera}
  40936. */
  40937. this.camera = camera;
  40938. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  40939. this.matrix = camera.matrixWorld;
  40940. this.matrixAutoUpdate = false;
  40941. /**
  40942. * This contains the points used to visualize the camera.
  40943. *
  40944. * @type {Object<string,Array<number>>}
  40945. */
  40946. this.pointMap = pointMap;
  40947. this.update();
  40948. // colors
  40949. const colorFrustum = new Color( 0xffaa00 );
  40950. const colorCone = new Color( 0xff0000 );
  40951. const colorUp = new Color( 0x00aaff );
  40952. const colorTarget = new Color( 0xffffff );
  40953. const colorCross = new Color( 0x333333 );
  40954. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  40955. }
  40956. /**
  40957. * Defines the colors of the helper.
  40958. *
  40959. * @param {Color} frustum - The frustum line color.
  40960. * @param {Color} cone - The cone line color.
  40961. * @param {Color} up - The up line color.
  40962. * @param {Color} target - The target line color.
  40963. * @param {Color} cross - The cross line color.
  40964. */
  40965. setColors( frustum, cone, up, target, cross ) {
  40966. const geometry = this.geometry;
  40967. const colorAttribute = geometry.getAttribute( 'color' );
  40968. // near
  40969. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  40970. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  40971. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  40972. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  40973. // far
  40974. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  40975. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  40976. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  40977. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  40978. // sides
  40979. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  40980. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  40981. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  40982. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  40983. // cone
  40984. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  40985. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  40986. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  40987. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  40988. // up
  40989. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  40990. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  40991. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  40992. // target
  40993. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  40994. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  40995. // cross
  40996. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  40997. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  40998. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  40999. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  41000. colorAttribute.needsUpdate = true;
  41001. }
  41002. /**
  41003. * Updates the helper based on the projection matrix of the camera.
  41004. */
  41005. update() {
  41006. const geometry = this.geometry;
  41007. const pointMap = this.pointMap;
  41008. const w = 1, h = 1;
  41009. // we need just camera projection matrix inverse
  41010. // world matrix must be identity
  41011. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  41012. // Adjust z values based on coordinate system
  41013. const nearZ = this.camera.coordinateSystem === WebGLCoordinateSystem ? -1 : 0;
  41014. // center / target
  41015. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  41016. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  41017. // near
  41018. setPoint( 'n1', pointMap, geometry, _camera, -1, -1, nearZ );
  41019. setPoint( 'n2', pointMap, geometry, _camera, w, -1, nearZ );
  41020. setPoint( 'n3', pointMap, geometry, _camera, -1, h, nearZ );
  41021. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  41022. // far
  41023. setPoint( 'f1', pointMap, geometry, _camera, -1, -1, 1 );
  41024. setPoint( 'f2', pointMap, geometry, _camera, w, -1, 1 );
  41025. setPoint( 'f3', pointMap, geometry, _camera, -1, h, 1 );
  41026. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  41027. // up
  41028. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  41029. setPoint( 'u2', pointMap, geometry, _camera, -1 * 0.7, h * 1.1, nearZ );
  41030. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  41031. // cross
  41032. setPoint( 'cf1', pointMap, geometry, _camera, -1, 0, 1 );
  41033. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  41034. setPoint( 'cf3', pointMap, geometry, _camera, 0, -1, 1 );
  41035. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  41036. setPoint( 'cn1', pointMap, geometry, _camera, -1, 0, nearZ );
  41037. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  41038. setPoint( 'cn3', pointMap, geometry, _camera, 0, -1, nearZ );
  41039. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  41040. geometry.getAttribute( 'position' ).needsUpdate = true;
  41041. }
  41042. /**
  41043. * Frees the GPU-related resources allocated by this instance. Call this
  41044. * method whenever this instance is no longer used in your app.
  41045. */
  41046. dispose() {
  41047. this.geometry.dispose();
  41048. this.material.dispose();
  41049. }
  41050. }
  41051. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  41052. _vector.set( x, y, z ).unproject( camera );
  41053. const points = pointMap[ point ];
  41054. if ( points !== undefined ) {
  41055. const position = geometry.getAttribute( 'position' );
  41056. for ( let i = 0, l = points.length; i < l; i ++ ) {
  41057. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  41058. }
  41059. }
  41060. }
  41061. const _box = /*@__PURE__*/ new Box3();
  41062. /**
  41063. * Helper object to graphically show the world-axis-aligned bounding box
  41064. * around an object. The actual bounding box is handled with {@link Box3},
  41065. * this is just a visual helper for debugging. It can be automatically
  41066. * resized with {@link BoxHelper#update} when the object it's created from
  41067. * is transformed. Note that the object must have a geometry for this to work,
  41068. * so it won't work with sprites.
  41069. *
  41070. * ```js
  41071. * const sphere = new THREE.SphereGeometry();
  41072. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  41073. * const box = new THREE.BoxHelper( object, 0xffff00 );
  41074. * scene.add( box );
  41075. * ```
  41076. *
  41077. * @augments LineSegments
  41078. */
  41079. class BoxHelper extends LineSegments {
  41080. /**
  41081. * Constructs a new box helper.
  41082. *
  41083. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  41084. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41085. */
  41086. constructor( object, color = 0xffff00 ) {
  41087. 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 ] );
  41088. const positions = new Float32Array( 8 * 3 );
  41089. const geometry = new BufferGeometry();
  41090. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41091. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  41092. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41093. /**
  41094. * The 3D object being visualized.
  41095. *
  41096. * @type {Object3D}
  41097. */
  41098. this.object = object;
  41099. this.type = 'BoxHelper';
  41100. this.matrixAutoUpdate = false;
  41101. this.update();
  41102. }
  41103. /**
  41104. * Updates the helper's geometry to match the dimensions of the object,
  41105. * including any children.
  41106. */
  41107. update() {
  41108. if ( this.object !== undefined ) {
  41109. _box.setFromObject( this.object );
  41110. }
  41111. if ( _box.isEmpty() ) return;
  41112. const min = _box.min;
  41113. const max = _box.max;
  41114. /*
  41115. 5____4
  41116. 1/___0/|
  41117. | 6__|_7
  41118. 2/___3/
  41119. 0: max.x, max.y, max.z
  41120. 1: min.x, max.y, max.z
  41121. 2: min.x, min.y, max.z
  41122. 3: max.x, min.y, max.z
  41123. 4: max.x, max.y, min.z
  41124. 5: min.x, max.y, min.z
  41125. 6: min.x, min.y, min.z
  41126. 7: max.x, min.y, min.z
  41127. */
  41128. const position = this.geometry.attributes.position;
  41129. const array = position.array;
  41130. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  41131. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  41132. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  41133. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  41134. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  41135. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  41136. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  41137. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  41138. position.needsUpdate = true;
  41139. this.geometry.computeBoundingSphere();
  41140. }
  41141. /**
  41142. * Updates the wireframe box for the passed object.
  41143. *
  41144. * @param {Object3D} object - The 3D object to create the helper for.
  41145. * @return {BoxHelper} A reference to this instance.
  41146. */
  41147. setFromObject( object ) {
  41148. this.object = object;
  41149. this.update();
  41150. return this;
  41151. }
  41152. copy( source, recursive ) {
  41153. super.copy( source, recursive );
  41154. this.object = source.object;
  41155. return this;
  41156. }
  41157. /**
  41158. * Frees the GPU-related resources allocated by this instance. Call this
  41159. * method whenever this instance is no longer used in your app.
  41160. */
  41161. dispose() {
  41162. this.geometry.dispose();
  41163. this.material.dispose();
  41164. }
  41165. }
  41166. /**
  41167. * A helper object to visualize an instance of {@link Box3}.
  41168. *
  41169. * ```js
  41170. * const box = new THREE.Box3();
  41171. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  41172. *
  41173. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  41174. * scene.add( helper )
  41175. * ```
  41176. *
  41177. * @augments LineSegments
  41178. */
  41179. class Box3Helper extends LineSegments {
  41180. /**
  41181. * Constructs a new box3 helper.
  41182. *
  41183. * @param {Box3} box - The box to visualize.
  41184. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41185. */
  41186. constructor( box, color = 0xffff00 ) {
  41187. 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 ] );
  41188. 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 ];
  41189. const geometry = new BufferGeometry();
  41190. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41191. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41192. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41193. /**
  41194. * The box being visualized.
  41195. *
  41196. * @type {Box3}
  41197. */
  41198. this.box = box;
  41199. this.type = 'Box3Helper';
  41200. this.geometry.computeBoundingSphere();
  41201. }
  41202. updateMatrixWorld( force ) {
  41203. const box = this.box;
  41204. if ( box.isEmpty() ) return;
  41205. box.getCenter( this.position );
  41206. box.getSize( this.scale );
  41207. this.scale.multiplyScalar( 0.5 );
  41208. super.updateMatrixWorld( force );
  41209. }
  41210. /**
  41211. * Frees the GPU-related resources allocated by this instance. Call this
  41212. * method whenever this instance is no longer used in your app.
  41213. */
  41214. dispose() {
  41215. this.geometry.dispose();
  41216. this.material.dispose();
  41217. }
  41218. }
  41219. /**
  41220. * A helper object to visualize an instance of {@link Plane}.
  41221. *
  41222. * ```js
  41223. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  41224. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  41225. * scene.add( helper );
  41226. * ```
  41227. *
  41228. * @augments Line
  41229. */
  41230. class PlaneHelper extends Line {
  41231. /**
  41232. * Constructs a new plane helper.
  41233. *
  41234. * @param {Plane} plane - The plane to be visualized.
  41235. * @param {number} [size=1] - The side length of plane helper.
  41236. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  41237. */
  41238. constructor( plane, size = 1, hex = 0xffff00 ) {
  41239. const color = hex;
  41240. 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 ];
  41241. const geometry = new BufferGeometry();
  41242. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41243. geometry.computeBoundingSphere();
  41244. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41245. this.type = 'PlaneHelper';
  41246. /**
  41247. * The plane being visualized.
  41248. *
  41249. * @type {Plane}
  41250. */
  41251. this.plane = plane;
  41252. /**
  41253. * The side length of plane helper.
  41254. *
  41255. * @type {number}
  41256. * @default 1
  41257. */
  41258. this.size = size;
  41259. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  41260. const geometry2 = new BufferGeometry();
  41261. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  41262. geometry2.computeBoundingSphere();
  41263. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  41264. }
  41265. updateMatrixWorld( force ) {
  41266. this.position.set( 0, 0, 0 );
  41267. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  41268. this.lookAt( this.plane.normal );
  41269. this.translateZ( - this.plane.constant );
  41270. super.updateMatrixWorld( force );
  41271. }
  41272. /**
  41273. * Updates the helper to match the position and direction of the
  41274. * light being visualized.
  41275. */
  41276. dispose() {
  41277. this.geometry.dispose();
  41278. this.material.dispose();
  41279. this.children[ 0 ].geometry.dispose();
  41280. this.children[ 0 ].material.dispose();
  41281. }
  41282. }
  41283. const _axis = /*@__PURE__*/ new Vector3();
  41284. let _lineGeometry, _coneGeometry;
  41285. /**
  41286. * An 3D arrow object for visualizing directions.
  41287. *
  41288. * ```js
  41289. * const dir = new THREE.Vector3( 1, 2, 0 );
  41290. *
  41291. * //normalize the direction vector (convert to vector of length 1)
  41292. * dir.normalize();
  41293. *
  41294. * const origin = new THREE.Vector3( 0, 0, 0 );
  41295. * const length = 1;
  41296. * const hex = 0xffff00;
  41297. *
  41298. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  41299. * scene.add( arrowHelper );
  41300. * ```
  41301. *
  41302. * @augments Object3D
  41303. */
  41304. class ArrowHelper extends Object3D {
  41305. /**
  41306. * Constructs a new arrow helper.
  41307. *
  41308. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  41309. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  41310. * @param {number} [length=1] - Length of the arrow in world units.
  41311. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  41312. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  41313. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  41314. */
  41315. 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 ) {
  41316. super();
  41317. this.type = 'ArrowHelper';
  41318. if ( _lineGeometry === undefined ) {
  41319. _lineGeometry = new BufferGeometry();
  41320. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  41321. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  41322. _coneGeometry.translate( 0, -0.5, 0 );
  41323. }
  41324. this.position.copy( origin );
  41325. /**
  41326. * The line part of the arrow helper.
  41327. *
  41328. * @type {Line}
  41329. */
  41330. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41331. this.line.matrixAutoUpdate = false;
  41332. this.add( this.line );
  41333. /**
  41334. * The cone part of the arrow helper.
  41335. *
  41336. * @type {Mesh}
  41337. */
  41338. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  41339. this.cone.matrixAutoUpdate = false;
  41340. this.add( this.cone );
  41341. this.setDirection( dir );
  41342. this.setLength( length, headLength, headWidth );
  41343. }
  41344. /**
  41345. * Sets the direction of the helper.
  41346. *
  41347. * @param {Vector3} dir - The normalized direction vector.
  41348. */
  41349. setDirection( dir ) {
  41350. // dir is assumed to be normalized
  41351. if ( dir.y > 0.99999 ) {
  41352. this.quaternion.set( 0, 0, 0, 1 );
  41353. } else if ( dir.y < -0.99999 ) {
  41354. this.quaternion.set( 1, 0, 0, 0 );
  41355. } else {
  41356. _axis.set( dir.z, 0, - dir.x ).normalize();
  41357. const radians = Math.acos( dir.y );
  41358. this.quaternion.setFromAxisAngle( _axis, radians );
  41359. }
  41360. }
  41361. /**
  41362. * Sets the length of the helper.
  41363. *
  41364. * @param {number} length - Length of the arrow in world units.
  41365. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  41366. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  41367. */
  41368. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  41369. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  41370. this.line.updateMatrix();
  41371. this.cone.scale.set( headWidth, headLength, headWidth );
  41372. this.cone.position.y = length;
  41373. this.cone.updateMatrix();
  41374. }
  41375. /**
  41376. * Sets the color of the helper.
  41377. *
  41378. * @param {number|Color|string} color - The color to set.
  41379. */
  41380. setColor( color ) {
  41381. this.line.material.color.set( color );
  41382. this.cone.material.color.set( color );
  41383. }
  41384. copy( source ) {
  41385. super.copy( source, false );
  41386. this.line.copy( source.line );
  41387. this.cone.copy( source.cone );
  41388. return this;
  41389. }
  41390. /**
  41391. * Frees the GPU-related resources allocated by this instance. Call this
  41392. * method whenever this instance is no longer used in your app.
  41393. */
  41394. dispose() {
  41395. this.line.geometry.dispose();
  41396. this.line.material.dispose();
  41397. this.cone.geometry.dispose();
  41398. this.cone.material.dispose();
  41399. }
  41400. }
  41401. /**
  41402. * An axis object to visualize the 3 axes in a simple way.
  41403. * The X axis is red. The Y axis is green. The Z axis is blue.
  41404. *
  41405. * ```js
  41406. * const axesHelper = new THREE.AxesHelper( 5 );
  41407. * scene.add( axesHelper );
  41408. * ```
  41409. *
  41410. * @augments LineSegments
  41411. */
  41412. class AxesHelper extends LineSegments {
  41413. /**
  41414. * Constructs a new axes helper.
  41415. *
  41416. * @param {number} [size=1] - Size of the lines representing the axes.
  41417. */
  41418. constructor( size = 1 ) {
  41419. const vertices = [
  41420. 0, 0, 0, size, 0, 0,
  41421. 0, 0, 0, 0, size, 0,
  41422. 0, 0, 0, 0, 0, size
  41423. ];
  41424. const colors = [
  41425. 1, 0, 0, 1, 0.6, 0,
  41426. 0, 1, 0, 0.6, 1, 0,
  41427. 0, 0, 1, 0, 0.6, 1
  41428. ];
  41429. const geometry = new BufferGeometry();
  41430. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41431. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41432. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41433. super( geometry, material );
  41434. this.type = 'AxesHelper';
  41435. }
  41436. /**
  41437. * Defines the colors of the axes helper.
  41438. *
  41439. * @param {number|Color|string} xAxisColor - The color for the x axis.
  41440. * @param {number|Color|string} yAxisColor - The color for the y axis.
  41441. * @param {number|Color|string} zAxisColor - The color for the z axis.
  41442. * @return {AxesHelper} A reference to this axes helper.
  41443. */
  41444. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  41445. const color = new Color();
  41446. const array = this.geometry.attributes.color.array;
  41447. color.set( xAxisColor );
  41448. color.toArray( array, 0 );
  41449. color.toArray( array, 3 );
  41450. color.set( yAxisColor );
  41451. color.toArray( array, 6 );
  41452. color.toArray( array, 9 );
  41453. color.set( zAxisColor );
  41454. color.toArray( array, 12 );
  41455. color.toArray( array, 15 );
  41456. this.geometry.attributes.color.needsUpdate = true;
  41457. return this;
  41458. }
  41459. /**
  41460. * Frees the GPU-related resources allocated by this instance. Call this
  41461. * method whenever this instance is no longer used in your app.
  41462. */
  41463. dispose() {
  41464. this.geometry.dispose();
  41465. this.material.dispose();
  41466. }
  41467. }
  41468. /**
  41469. * This class is used to convert a series of paths to an array of
  41470. * shapes. It is specifically used in context of fonts and SVG.
  41471. */
  41472. class ShapePath {
  41473. /**
  41474. * Constructs a new shape path.
  41475. */
  41476. constructor() {
  41477. this.type = 'ShapePath';
  41478. /**
  41479. * The color of the shape.
  41480. *
  41481. * @type {Color}
  41482. */
  41483. this.color = new Color();
  41484. /**
  41485. * The paths that have been generated for this shape.
  41486. *
  41487. * @type {Array<Path>}
  41488. * @default null
  41489. */
  41490. this.subPaths = [];
  41491. /**
  41492. * The current path that is being generated.
  41493. *
  41494. * @type {?Path}
  41495. * @default null
  41496. */
  41497. this.currentPath = null;
  41498. }
  41499. /**
  41500. * Creates a new path and moves it current point to the given one.
  41501. *
  41502. * @param {number} x - The x coordinate.
  41503. * @param {number} y - The y coordinate.
  41504. * @return {ShapePath} A reference to this shape path.
  41505. */
  41506. moveTo( x, y ) {
  41507. this.currentPath = new Path();
  41508. this.subPaths.push( this.currentPath );
  41509. this.currentPath.moveTo( x, y );
  41510. return this;
  41511. }
  41512. /**
  41513. * Adds an instance of {@link LineCurve} to the path by connecting
  41514. * the current point with the given one.
  41515. *
  41516. * @param {number} x - The x coordinate of the end point.
  41517. * @param {number} y - The y coordinate of the end point.
  41518. * @return {ShapePath} A reference to this shape path.
  41519. */
  41520. lineTo( x, y ) {
  41521. this.currentPath.lineTo( x, y );
  41522. return this;
  41523. }
  41524. /**
  41525. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  41526. * the current point with the given one.
  41527. *
  41528. * @param {number} aCPx - The x coordinate of the control point.
  41529. * @param {number} aCPy - The y coordinate of the control point.
  41530. * @param {number} aX - The x coordinate of the end point.
  41531. * @param {number} aY - The y coordinate of the end point.
  41532. * @return {ShapePath} A reference to this shape path.
  41533. */
  41534. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  41535. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  41536. return this;
  41537. }
  41538. /**
  41539. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  41540. * the current point with the given one.
  41541. *
  41542. * @param {number} aCP1x - The x coordinate of the first control point.
  41543. * @param {number} aCP1y - The y coordinate of the first control point.
  41544. * @param {number} aCP2x - The x coordinate of the second control point.
  41545. * @param {number} aCP2y - The y coordinate of the second control point.
  41546. * @param {number} aX - The x coordinate of the end point.
  41547. * @param {number} aY - The y coordinate of the end point.
  41548. * @return {ShapePath} A reference to this shape path.
  41549. */
  41550. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  41551. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  41552. return this;
  41553. }
  41554. /**
  41555. * Adds an instance of {@link SplineCurve} to the path by connecting
  41556. * the current point with the given list of points.
  41557. *
  41558. * @param {Array<Vector2>} pts - An array of points in 2D space.
  41559. * @return {ShapePath} A reference to this shape path.
  41560. */
  41561. splineThru( pts ) {
  41562. this.currentPath.splineThru( pts );
  41563. return this;
  41564. }
  41565. /**
  41566. * Converts the paths into an array of shapes.
  41567. *
  41568. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  41569. * If this flag is set to `true`, then those are flipped.
  41570. * @return {Array<Shape>} An array of shapes.
  41571. */
  41572. toShapes( isCCW ) {
  41573. function toShapesNoHoles( inSubpaths ) {
  41574. const shapes = [];
  41575. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  41576. const tmpPath = inSubpaths[ i ];
  41577. const tmpShape = new Shape();
  41578. tmpShape.curves = tmpPath.curves;
  41579. shapes.push( tmpShape );
  41580. }
  41581. return shapes;
  41582. }
  41583. function isPointInsidePolygon( inPt, inPolygon ) {
  41584. const polyLen = inPolygon.length;
  41585. // inPt on polygon contour => immediate success or
  41586. // toggling of inside/outside at every single! intersection point of an edge
  41587. // with the horizontal line through inPt, left of inPt
  41588. // not counting lowerY endpoints of edges and whole edges on that line
  41589. let inside = false;
  41590. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  41591. let edgeLowPt = inPolygon[ p ];
  41592. let edgeHighPt = inPolygon[ q ];
  41593. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  41594. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  41595. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  41596. // not parallel
  41597. if ( edgeDy < 0 ) {
  41598. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  41599. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  41600. }
  41601. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  41602. if ( inPt.y === edgeLowPt.y ) {
  41603. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  41604. // continue; // no intersection or edgeLowPt => doesn't count !!!
  41605. } else {
  41606. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  41607. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  41608. if ( perpEdge < 0 ) continue;
  41609. inside = ! inside; // true intersection left of inPt
  41610. }
  41611. } else {
  41612. // parallel or collinear
  41613. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  41614. // edge lies on the same horizontal line as inPt
  41615. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  41616. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  41617. // continue;
  41618. }
  41619. }
  41620. return inside;
  41621. }
  41622. const isClockWise = ShapeUtils.isClockWise;
  41623. const subPaths = this.subPaths;
  41624. if ( subPaths.length === 0 ) return [];
  41625. let solid, tmpPath, tmpShape;
  41626. const shapes = [];
  41627. if ( subPaths.length === 1 ) {
  41628. tmpPath = subPaths[ 0 ];
  41629. tmpShape = new Shape();
  41630. tmpShape.curves = tmpPath.curves;
  41631. shapes.push( tmpShape );
  41632. return shapes;
  41633. }
  41634. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  41635. holesFirst = isCCW ? ! holesFirst : holesFirst;
  41636. // console.log("Holes first", holesFirst);
  41637. const betterShapeHoles = [];
  41638. const newShapes = [];
  41639. let newShapeHoles = [];
  41640. let mainIdx = 0;
  41641. let tmpPoints;
  41642. newShapes[ mainIdx ] = undefined;
  41643. newShapeHoles[ mainIdx ] = [];
  41644. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  41645. tmpPath = subPaths[ i ];
  41646. tmpPoints = tmpPath.getPoints();
  41647. solid = isClockWise( tmpPoints );
  41648. solid = isCCW ? ! solid : solid;
  41649. if ( solid ) {
  41650. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  41651. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  41652. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  41653. if ( holesFirst ) mainIdx ++;
  41654. newShapeHoles[ mainIdx ] = [];
  41655. //console.log('cw', i);
  41656. } else {
  41657. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  41658. //console.log('ccw', i);
  41659. }
  41660. }
  41661. // only Holes? -> probably all Shapes with wrong orientation
  41662. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  41663. if ( newShapes.length > 1 ) {
  41664. let ambiguous = false;
  41665. let toChange = 0;
  41666. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  41667. betterShapeHoles[ sIdx ] = [];
  41668. }
  41669. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  41670. const sho = newShapeHoles[ sIdx ];
  41671. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  41672. const ho = sho[ hIdx ];
  41673. let hole_unassigned = true;
  41674. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  41675. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  41676. if ( sIdx !== s2Idx ) toChange ++;
  41677. if ( hole_unassigned ) {
  41678. hole_unassigned = false;
  41679. betterShapeHoles[ s2Idx ].push( ho );
  41680. } else {
  41681. ambiguous = true;
  41682. }
  41683. }
  41684. }
  41685. if ( hole_unassigned ) {
  41686. betterShapeHoles[ sIdx ].push( ho );
  41687. }
  41688. }
  41689. }
  41690. if ( toChange > 0 && ambiguous === false ) {
  41691. newShapeHoles = betterShapeHoles;
  41692. }
  41693. }
  41694. let tmpHoles;
  41695. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  41696. tmpShape = newShapes[ i ].s;
  41697. shapes.push( tmpShape );
  41698. tmpHoles = newShapeHoles[ i ];
  41699. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  41700. tmpShape.holes.push( tmpHoles[ j ].h );
  41701. }
  41702. }
  41703. //console.log("shape", shapes);
  41704. return shapes;
  41705. }
  41706. }
  41707. /**
  41708. * Abstract base class for controls.
  41709. *
  41710. * @abstract
  41711. * @augments EventDispatcher
  41712. */
  41713. class Controls extends EventDispatcher {
  41714. /**
  41715. * Constructs a new controls instance.
  41716. *
  41717. * @param {Object3D} object - The object that is managed by the controls.
  41718. * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
  41719. */
  41720. constructor( object, domElement = null ) {
  41721. super();
  41722. /**
  41723. * The object that is managed by the controls.
  41724. *
  41725. * @type {Object3D}
  41726. */
  41727. this.object = object;
  41728. /**
  41729. * The HTML element used for event listeners.
  41730. *
  41731. * @type {?HTMLDOMElement}
  41732. * @default null
  41733. */
  41734. this.domElement = domElement;
  41735. /**
  41736. * Whether the controls responds to user input or not.
  41737. *
  41738. * @type {boolean}
  41739. * @default true
  41740. */
  41741. this.enabled = true;
  41742. /**
  41743. * The internal state of the controls.
  41744. *
  41745. * @type {number}
  41746. * @default -1
  41747. */
  41748. this.state = -1;
  41749. /**
  41750. * This object defines the keyboard input of the controls.
  41751. *
  41752. * @type {Object}
  41753. */
  41754. this.keys = {};
  41755. /**
  41756. * This object defines what type of actions are assigned to the available mouse buttons.
  41757. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  41758. *
  41759. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  41760. */
  41761. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  41762. /**
  41763. * This object defines what type of actions are assigned to what kind of touch interaction.
  41764. * It depends on the control implementation what kind of touch interaction and actions are supported.
  41765. *
  41766. * @type {{ONE: ?number, TWO: ?number}}
  41767. */
  41768. this.touches = { ONE: null, TWO: null };
  41769. }
  41770. /**
  41771. * Connects the controls to the DOM. This method has so called "side effects" since
  41772. * it adds the module's event listeners to the DOM.
  41773. *
  41774. * @param {HTMLDOMElement} element - The DOM element to connect to.
  41775. */
  41776. connect( element ) {
  41777. if ( element === undefined ) {
  41778. console.warn( 'THREE.Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  41779. return;
  41780. }
  41781. if ( this.domElement !== null ) this.disconnect();
  41782. this.domElement = element;
  41783. }
  41784. /**
  41785. * Disconnects the controls from the DOM.
  41786. */
  41787. disconnect() {}
  41788. /**
  41789. * Call this method if you no longer want use to the controls. It frees all internal
  41790. * resources and removes all event listeners.
  41791. */
  41792. dispose() {}
  41793. /**
  41794. * Controls should implement this method if they have to update their internal state
  41795. * per simulation step.
  41796. *
  41797. * @param {number} [delta] - The time delta in seconds.
  41798. */
  41799. update( /* delta */ ) {}
  41800. }
  41801. /**
  41802. * Scales the texture as large as possible within its surface without cropping
  41803. * or stretching the texture. The method preserves the original aspect ratio of
  41804. * the texture. Akin to CSS `object-fit: contain`
  41805. *
  41806. * @param {Texture} texture - The texture.
  41807. * @param {number} aspect - The texture's aspect ratio.
  41808. * @return {Texture} The updated texture.
  41809. */
  41810. function contain( texture, aspect ) {
  41811. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  41812. if ( imageAspect > aspect ) {
  41813. texture.repeat.x = 1;
  41814. texture.repeat.y = imageAspect / aspect;
  41815. texture.offset.x = 0;
  41816. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  41817. } else {
  41818. texture.repeat.x = aspect / imageAspect;
  41819. texture.repeat.y = 1;
  41820. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  41821. texture.offset.y = 0;
  41822. }
  41823. return texture;
  41824. }
  41825. /**
  41826. * Scales the texture to the smallest possible size to fill the surface, leaving
  41827. * no empty space. The method preserves the original aspect ratio of the texture.
  41828. * Akin to CSS `object-fit: cover`.
  41829. *
  41830. * @param {Texture} texture - The texture.
  41831. * @param {number} aspect - The texture's aspect ratio.
  41832. * @return {Texture} The updated texture.
  41833. */
  41834. function cover( texture, aspect ) {
  41835. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  41836. if ( imageAspect > aspect ) {
  41837. texture.repeat.x = aspect / imageAspect;
  41838. texture.repeat.y = 1;
  41839. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  41840. texture.offset.y = 0;
  41841. } else {
  41842. texture.repeat.x = 1;
  41843. texture.repeat.y = imageAspect / aspect;
  41844. texture.offset.x = 0;
  41845. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  41846. }
  41847. return texture;
  41848. }
  41849. /**
  41850. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  41851. *
  41852. * @param {Texture} texture - The texture.
  41853. * @return {Texture} The updated texture.
  41854. */
  41855. function fill( texture ) {
  41856. texture.repeat.x = 1;
  41857. texture.repeat.y = 1;
  41858. texture.offset.x = 0;
  41859. texture.offset.y = 0;
  41860. return texture;
  41861. }
  41862. /**
  41863. * Determines how many bytes must be used to represent the texture.
  41864. *
  41865. * @param {number} width - The width of the texture.
  41866. * @param {number} height - The height of the texture.
  41867. * @param {number} format - The texture's format.
  41868. * @param {number} type - The texture's type.
  41869. * @return {number} The byte length.
  41870. */
  41871. function getByteLength( width, height, format, type ) {
  41872. const typeByteLength = getTextureTypeByteLength( type );
  41873. switch ( format ) {
  41874. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  41875. case AlphaFormat:
  41876. return width * height;
  41877. case RedFormat:
  41878. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  41879. case RedIntegerFormat:
  41880. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  41881. case RGFormat:
  41882. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  41883. case RGIntegerFormat:
  41884. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  41885. case RGBFormat:
  41886. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  41887. case RGBAFormat:
  41888. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  41889. case RGBAIntegerFormat:
  41890. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  41891. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  41892. case RGB_S3TC_DXT1_Format:
  41893. case RGBA_S3TC_DXT1_Format:
  41894. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  41895. case RGBA_S3TC_DXT3_Format:
  41896. case RGBA_S3TC_DXT5_Format:
  41897. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  41898. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  41899. case RGB_PVRTC_2BPPV1_Format:
  41900. case RGBA_PVRTC_2BPPV1_Format:
  41901. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  41902. case RGB_PVRTC_4BPPV1_Format:
  41903. case RGBA_PVRTC_4BPPV1_Format:
  41904. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  41905. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  41906. case RGB_ETC1_Format:
  41907. case RGB_ETC2_Format:
  41908. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  41909. case RGBA_ETC2_EAC_Format:
  41910. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  41911. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  41912. case RGBA_ASTC_4x4_Format:
  41913. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  41914. case RGBA_ASTC_5x4_Format:
  41915. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  41916. case RGBA_ASTC_5x5_Format:
  41917. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  41918. case RGBA_ASTC_6x5_Format:
  41919. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  41920. case RGBA_ASTC_6x6_Format:
  41921. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  41922. case RGBA_ASTC_8x5_Format:
  41923. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  41924. case RGBA_ASTC_8x6_Format:
  41925. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  41926. case RGBA_ASTC_8x8_Format:
  41927. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  41928. case RGBA_ASTC_10x5_Format:
  41929. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  41930. case RGBA_ASTC_10x6_Format:
  41931. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  41932. case RGBA_ASTC_10x8_Format:
  41933. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  41934. case RGBA_ASTC_10x10_Format:
  41935. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  41936. case RGBA_ASTC_12x10_Format:
  41937. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  41938. case RGBA_ASTC_12x12_Format:
  41939. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  41940. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  41941. case RGBA_BPTC_Format:
  41942. case RGB_BPTC_SIGNED_Format:
  41943. case RGB_BPTC_UNSIGNED_Format:
  41944. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  41945. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  41946. case RED_RGTC1_Format:
  41947. case SIGNED_RED_RGTC1_Format:
  41948. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  41949. case RED_GREEN_RGTC2_Format:
  41950. case SIGNED_RED_GREEN_RGTC2_Format:
  41951. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  41952. }
  41953. throw new Error(
  41954. `Unable to determine texture byte length for ${format} format.`,
  41955. );
  41956. }
  41957. function getTextureTypeByteLength( type ) {
  41958. switch ( type ) {
  41959. case UnsignedByteType:
  41960. case ByteType:
  41961. return { byteLength: 1, components: 1 };
  41962. case UnsignedShortType:
  41963. case ShortType:
  41964. case HalfFloatType:
  41965. return { byteLength: 2, components: 1 };
  41966. case UnsignedShort4444Type:
  41967. case UnsignedShort5551Type:
  41968. return { byteLength: 2, components: 4 };
  41969. case UnsignedIntType:
  41970. case IntType:
  41971. case FloatType:
  41972. return { byteLength: 4, components: 1 };
  41973. case UnsignedInt5999Type:
  41974. return { byteLength: 4, components: 3 };
  41975. }
  41976. throw new Error( `Unknown texture type ${type}.` );
  41977. }
  41978. /**
  41979. * A class containing utility functions for textures.
  41980. *
  41981. * @hideconstructor
  41982. */
  41983. class TextureUtils {
  41984. /**
  41985. * Scales the texture as large as possible within its surface without cropping
  41986. * or stretching the texture. The method preserves the original aspect ratio of
  41987. * the texture. Akin to CSS `object-fit: contain`
  41988. *
  41989. * @param {Texture} texture - The texture.
  41990. * @param {number} aspect - The texture's aspect ratio.
  41991. * @return {Texture} The updated texture.
  41992. */
  41993. static contain( texture, aspect ) {
  41994. return contain( texture, aspect );
  41995. }
  41996. /**
  41997. * Scales the texture to the smallest possible size to fill the surface, leaving
  41998. * no empty space. The method preserves the original aspect ratio of the texture.
  41999. * Akin to CSS `object-fit: cover`.
  42000. *
  42001. * @param {Texture} texture - The texture.
  42002. * @param {number} aspect - The texture's aspect ratio.
  42003. * @return {Texture} The updated texture.
  42004. */
  42005. static cover( texture, aspect ) {
  42006. return cover( texture, aspect );
  42007. }
  42008. /**
  42009. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42010. *
  42011. * @param {Texture} texture - The texture.
  42012. * @return {Texture} The updated texture.
  42013. */
  42014. static fill( texture ) {
  42015. return fill( texture );
  42016. }
  42017. /**
  42018. * Determines how many bytes must be used to represent the texture.
  42019. *
  42020. * @param {number} width - The width of the texture.
  42021. * @param {number} height - The height of the texture.
  42022. * @param {number} format - The texture's format.
  42023. * @param {number} type - The texture's type.
  42024. * @return {number} The byte length.
  42025. */
  42026. static getByteLength( width, height, format, type ) {
  42027. return getByteLength( width, height, format, type );
  42028. }
  42029. }
  42030. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  42031. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  42032. revision: REVISION,
  42033. } } ) );
  42034. }
  42035. if ( typeof window !== 'undefined' ) {
  42036. if ( window.__THREE__ ) {
  42037. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  42038. } else {
  42039. window.__THREE__ = REVISION;
  42040. }
  42041. }
  42042. function WebGLAnimation() {
  42043. let context = null;
  42044. let isAnimating = false;
  42045. let animationLoop = null;
  42046. let requestId = null;
  42047. function onAnimationFrame( time, frame ) {
  42048. animationLoop( time, frame );
  42049. requestId = context.requestAnimationFrame( onAnimationFrame );
  42050. }
  42051. return {
  42052. start: function () {
  42053. if ( isAnimating === true ) return;
  42054. if ( animationLoop === null ) return;
  42055. requestId = context.requestAnimationFrame( onAnimationFrame );
  42056. isAnimating = true;
  42057. },
  42058. stop: function () {
  42059. context.cancelAnimationFrame( requestId );
  42060. isAnimating = false;
  42061. },
  42062. setAnimationLoop: function ( callback ) {
  42063. animationLoop = callback;
  42064. },
  42065. setContext: function ( value ) {
  42066. context = value;
  42067. }
  42068. };
  42069. }
  42070. function WebGLAttributes( gl ) {
  42071. const buffers = new WeakMap();
  42072. function createBuffer( attribute, bufferType ) {
  42073. const array = attribute.array;
  42074. const usage = attribute.usage;
  42075. const size = array.byteLength;
  42076. const buffer = gl.createBuffer();
  42077. gl.bindBuffer( bufferType, buffer );
  42078. gl.bufferData( bufferType, array, usage );
  42079. attribute.onUploadCallback();
  42080. let type;
  42081. if ( array instanceof Float32Array ) {
  42082. type = gl.FLOAT;
  42083. } else if ( array instanceof Uint16Array ) {
  42084. if ( attribute.isFloat16BufferAttribute ) {
  42085. type = gl.HALF_FLOAT;
  42086. } else {
  42087. type = gl.UNSIGNED_SHORT;
  42088. }
  42089. } else if ( array instanceof Int16Array ) {
  42090. type = gl.SHORT;
  42091. } else if ( array instanceof Uint32Array ) {
  42092. type = gl.UNSIGNED_INT;
  42093. } else if ( array instanceof Int32Array ) {
  42094. type = gl.INT;
  42095. } else if ( array instanceof Int8Array ) {
  42096. type = gl.BYTE;
  42097. } else if ( array instanceof Uint8Array ) {
  42098. type = gl.UNSIGNED_BYTE;
  42099. } else if ( array instanceof Uint8ClampedArray ) {
  42100. type = gl.UNSIGNED_BYTE;
  42101. } else {
  42102. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  42103. }
  42104. return {
  42105. buffer: buffer,
  42106. type: type,
  42107. bytesPerElement: array.BYTES_PER_ELEMENT,
  42108. version: attribute.version,
  42109. size: size
  42110. };
  42111. }
  42112. function updateBuffer( buffer, attribute, bufferType ) {
  42113. const array = attribute.array;
  42114. const updateRanges = attribute.updateRanges;
  42115. gl.bindBuffer( bufferType, buffer );
  42116. if ( updateRanges.length === 0 ) {
  42117. // Not using update ranges
  42118. gl.bufferSubData( bufferType, 0, array );
  42119. } else {
  42120. // Before applying update ranges, we merge any adjacent / overlapping
  42121. // ranges to reduce load on `gl.bufferSubData`. Empirically, this has led
  42122. // to performance improvements for applications which make heavy use of
  42123. // update ranges. Likely due to GPU command overhead.
  42124. //
  42125. // Note that to reduce garbage collection between frames, we merge the
  42126. // update ranges in-place. This is safe because this method will clear the
  42127. // update ranges once updated.
  42128. updateRanges.sort( ( a, b ) => a.start - b.start );
  42129. // To merge the update ranges in-place, we work from left to right in the
  42130. // existing updateRanges array, merging ranges. This may result in a final
  42131. // array which is smaller than the original. This index tracks the last
  42132. // index representing a merged range, any data after this index can be
  42133. // trimmed once the merge algorithm is completed.
  42134. let mergeIndex = 0;
  42135. for ( let i = 1; i < updateRanges.length; i ++ ) {
  42136. const previousRange = updateRanges[ mergeIndex ];
  42137. const range = updateRanges[ i ];
  42138. // We add one here to merge adjacent ranges. This is safe because ranges
  42139. // operate over positive integers.
  42140. if ( range.start <= previousRange.start + previousRange.count + 1 ) {
  42141. previousRange.count = Math.max(
  42142. previousRange.count,
  42143. range.start + range.count - previousRange.start
  42144. );
  42145. } else {
  42146. ++ mergeIndex;
  42147. updateRanges[ mergeIndex ] = range;
  42148. }
  42149. }
  42150. // Trim the array to only contain the merged ranges.
  42151. updateRanges.length = mergeIndex + 1;
  42152. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  42153. const range = updateRanges[ i ];
  42154. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  42155. array, range.start, range.count );
  42156. }
  42157. attribute.clearUpdateRanges();
  42158. }
  42159. attribute.onUploadCallback();
  42160. }
  42161. //
  42162. function get( attribute ) {
  42163. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42164. return buffers.get( attribute );
  42165. }
  42166. function remove( attribute ) {
  42167. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42168. const data = buffers.get( attribute );
  42169. if ( data ) {
  42170. gl.deleteBuffer( data.buffer );
  42171. buffers.delete( attribute );
  42172. }
  42173. }
  42174. function update( attribute, bufferType ) {
  42175. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42176. if ( attribute.isGLBufferAttribute ) {
  42177. const cached = buffers.get( attribute );
  42178. if ( ! cached || cached.version < attribute.version ) {
  42179. buffers.set( attribute, {
  42180. buffer: attribute.buffer,
  42181. type: attribute.type,
  42182. bytesPerElement: attribute.elementSize,
  42183. version: attribute.version
  42184. } );
  42185. }
  42186. return;
  42187. }
  42188. const data = buffers.get( attribute );
  42189. if ( data === undefined ) {
  42190. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  42191. } else if ( data.version < attribute.version ) {
  42192. if ( data.size !== attribute.array.byteLength ) {
  42193. 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.' );
  42194. }
  42195. updateBuffer( data.buffer, attribute, bufferType );
  42196. data.version = attribute.version;
  42197. }
  42198. }
  42199. return {
  42200. get: get,
  42201. remove: remove,
  42202. update: update
  42203. };
  42204. }
  42205. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  42206. 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";
  42207. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  42208. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  42209. 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";
  42210. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  42211. 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";
  42212. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  42213. 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";
  42214. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif";
  42215. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  42216. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  42217. 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";
  42218. 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";
  42219. 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";
  42220. 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";
  42221. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  42222. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  42223. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  42224. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  42225. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  42226. 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";
  42227. 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";
  42228. 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";
  42229. 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";
  42230. 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";
  42231. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  42232. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  42233. 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";
  42234. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  42235. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  42236. 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}";
  42237. 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";
  42238. 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";
  42239. 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";
  42240. 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";
  42241. 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";
  42242. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  42243. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  42244. 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";
  42245. 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";
  42246. 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}";
  42247. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  42248. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  42249. 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";
  42250. 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";
  42251. 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";
  42252. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  42253. 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";
  42254. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  42255. 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";
  42256. 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";
  42257. 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}";
  42258. 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";
  42259. 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";
  42260. 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";
  42261. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  42262. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  42263. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  42264. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif";
  42265. 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";
  42266. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  42267. 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";
  42268. 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";
  42269. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  42270. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  42271. 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";
  42272. 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";
  42273. 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";
  42274. 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";
  42275. 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";
  42276. 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;";
  42277. 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";
  42278. 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";
  42279. 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";
  42280. 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";
  42281. 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";
  42282. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  42283. 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";
  42284. 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";
  42285. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  42286. 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 );";
  42287. 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}";
  42288. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  42289. 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;";
  42290. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  42291. 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";
  42292. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  42293. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  42294. 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\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\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\tfloat hard_shadow = step( compare , distribution.x );\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";
  42295. 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";
  42296. 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";
  42297. 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}";
  42298. 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";
  42299. 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";
  42300. 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";
  42301. 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";
  42302. 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";
  42303. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  42304. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  42305. 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; }";
  42306. 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";
  42307. 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";
  42308. 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";
  42309. 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";
  42310. 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";
  42311. 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";
  42312. 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}";
  42313. 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}";
  42314. 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}";
  42315. 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}";
  42316. 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}";
  42317. 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}";
  42318. 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}";
  42319. 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\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\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}";
  42320. 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}";
  42321. 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}";
  42322. 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}";
  42323. 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}";
  42324. 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}";
  42325. 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}";
  42326. 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}";
  42327. 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}";
  42328. 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}";
  42329. 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}";
  42330. 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}";
  42331. 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}";
  42332. 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}";
  42333. 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}";
  42334. 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}";
  42335. 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}";
  42336. 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}";
  42337. 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}";
  42338. 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}";
  42339. 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}";
  42340. 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}";
  42341. 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}";
  42342. 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}";
  42343. 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}";
  42344. 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}";
  42345. 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}";
  42346. const ShaderChunk = {
  42347. alphahash_fragment: alphahash_fragment,
  42348. alphahash_pars_fragment: alphahash_pars_fragment,
  42349. alphamap_fragment: alphamap_fragment,
  42350. alphamap_pars_fragment: alphamap_pars_fragment,
  42351. alphatest_fragment: alphatest_fragment,
  42352. alphatest_pars_fragment: alphatest_pars_fragment,
  42353. aomap_fragment: aomap_fragment,
  42354. aomap_pars_fragment: aomap_pars_fragment,
  42355. batching_pars_vertex: batching_pars_vertex,
  42356. batching_vertex: batching_vertex,
  42357. begin_vertex: begin_vertex,
  42358. beginnormal_vertex: beginnormal_vertex,
  42359. bsdfs: bsdfs,
  42360. iridescence_fragment: iridescence_fragment,
  42361. bumpmap_pars_fragment: bumpmap_pars_fragment,
  42362. clipping_planes_fragment: clipping_planes_fragment,
  42363. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  42364. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  42365. clipping_planes_vertex: clipping_planes_vertex,
  42366. color_fragment: color_fragment,
  42367. color_pars_fragment: color_pars_fragment,
  42368. color_pars_vertex: color_pars_vertex,
  42369. color_vertex: color_vertex,
  42370. common: common,
  42371. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  42372. defaultnormal_vertex: defaultnormal_vertex,
  42373. displacementmap_pars_vertex: displacementmap_pars_vertex,
  42374. displacementmap_vertex: displacementmap_vertex,
  42375. emissivemap_fragment: emissivemap_fragment,
  42376. emissivemap_pars_fragment: emissivemap_pars_fragment,
  42377. colorspace_fragment: colorspace_fragment,
  42378. colorspace_pars_fragment: colorspace_pars_fragment,
  42379. envmap_fragment: envmap_fragment,
  42380. envmap_common_pars_fragment: envmap_common_pars_fragment,
  42381. envmap_pars_fragment: envmap_pars_fragment,
  42382. envmap_pars_vertex: envmap_pars_vertex,
  42383. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  42384. envmap_vertex: envmap_vertex,
  42385. fog_vertex: fog_vertex,
  42386. fog_pars_vertex: fog_pars_vertex,
  42387. fog_fragment: fog_fragment,
  42388. fog_pars_fragment: fog_pars_fragment,
  42389. gradientmap_pars_fragment: gradientmap_pars_fragment,
  42390. lightmap_pars_fragment: lightmap_pars_fragment,
  42391. lights_lambert_fragment: lights_lambert_fragment,
  42392. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  42393. lights_pars_begin: lights_pars_begin,
  42394. lights_toon_fragment: lights_toon_fragment,
  42395. lights_toon_pars_fragment: lights_toon_pars_fragment,
  42396. lights_phong_fragment: lights_phong_fragment,
  42397. lights_phong_pars_fragment: lights_phong_pars_fragment,
  42398. lights_physical_fragment: lights_physical_fragment,
  42399. lights_physical_pars_fragment: lights_physical_pars_fragment,
  42400. lights_fragment_begin: lights_fragment_begin,
  42401. lights_fragment_maps: lights_fragment_maps,
  42402. lights_fragment_end: lights_fragment_end,
  42403. logdepthbuf_fragment: logdepthbuf_fragment,
  42404. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  42405. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  42406. logdepthbuf_vertex: logdepthbuf_vertex,
  42407. map_fragment: map_fragment,
  42408. map_pars_fragment: map_pars_fragment,
  42409. map_particle_fragment: map_particle_fragment,
  42410. map_particle_pars_fragment: map_particle_pars_fragment,
  42411. metalnessmap_fragment: metalnessmap_fragment,
  42412. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  42413. morphinstance_vertex: morphinstance_vertex,
  42414. morphcolor_vertex: morphcolor_vertex,
  42415. morphnormal_vertex: morphnormal_vertex,
  42416. morphtarget_pars_vertex: morphtarget_pars_vertex,
  42417. morphtarget_vertex: morphtarget_vertex,
  42418. normal_fragment_begin: normal_fragment_begin,
  42419. normal_fragment_maps: normal_fragment_maps,
  42420. normal_pars_fragment: normal_pars_fragment,
  42421. normal_pars_vertex: normal_pars_vertex,
  42422. normal_vertex: normal_vertex,
  42423. normalmap_pars_fragment: normalmap_pars_fragment,
  42424. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  42425. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  42426. clearcoat_pars_fragment: clearcoat_pars_fragment,
  42427. iridescence_pars_fragment: iridescence_pars_fragment,
  42428. opaque_fragment: opaque_fragment,
  42429. packing: packing,
  42430. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  42431. project_vertex: project_vertex,
  42432. dithering_fragment: dithering_fragment,
  42433. dithering_pars_fragment: dithering_pars_fragment,
  42434. roughnessmap_fragment: roughnessmap_fragment,
  42435. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  42436. shadowmap_pars_fragment: shadowmap_pars_fragment,
  42437. shadowmap_pars_vertex: shadowmap_pars_vertex,
  42438. shadowmap_vertex: shadowmap_vertex,
  42439. shadowmask_pars_fragment: shadowmask_pars_fragment,
  42440. skinbase_vertex: skinbase_vertex,
  42441. skinning_pars_vertex: skinning_pars_vertex,
  42442. skinning_vertex: skinning_vertex,
  42443. skinnormal_vertex: skinnormal_vertex,
  42444. specularmap_fragment: specularmap_fragment,
  42445. specularmap_pars_fragment: specularmap_pars_fragment,
  42446. tonemapping_fragment: tonemapping_fragment,
  42447. tonemapping_pars_fragment: tonemapping_pars_fragment,
  42448. transmission_fragment: transmission_fragment,
  42449. transmission_pars_fragment: transmission_pars_fragment,
  42450. uv_pars_fragment: uv_pars_fragment,
  42451. uv_pars_vertex: uv_pars_vertex,
  42452. uv_vertex: uv_vertex,
  42453. worldpos_vertex: worldpos_vertex,
  42454. background_vert: vertex$h,
  42455. background_frag: fragment$h,
  42456. backgroundCube_vert: vertex$g,
  42457. backgroundCube_frag: fragment$g,
  42458. cube_vert: vertex$f,
  42459. cube_frag: fragment$f,
  42460. depth_vert: vertex$e,
  42461. depth_frag: fragment$e,
  42462. distanceRGBA_vert: vertex$d,
  42463. distanceRGBA_frag: fragment$d,
  42464. equirect_vert: vertex$c,
  42465. equirect_frag: fragment$c,
  42466. linedashed_vert: vertex$b,
  42467. linedashed_frag: fragment$b,
  42468. meshbasic_vert: vertex$a,
  42469. meshbasic_frag: fragment$a,
  42470. meshlambert_vert: vertex$9,
  42471. meshlambert_frag: fragment$9,
  42472. meshmatcap_vert: vertex$8,
  42473. meshmatcap_frag: fragment$8,
  42474. meshnormal_vert: vertex$7,
  42475. meshnormal_frag: fragment$7,
  42476. meshphong_vert: vertex$6,
  42477. meshphong_frag: fragment$6,
  42478. meshphysical_vert: vertex$5,
  42479. meshphysical_frag: fragment$5,
  42480. meshtoon_vert: vertex$4,
  42481. meshtoon_frag: fragment$4,
  42482. points_vert: vertex$3,
  42483. points_frag: fragment$3,
  42484. shadow_vert: vertex$2,
  42485. shadow_frag: fragment$2,
  42486. sprite_vert: vertex$1,
  42487. sprite_frag: fragment$1
  42488. };
  42489. // Uniforms library for shared webgl shaders
  42490. const UniformsLib = {
  42491. common: {
  42492. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  42493. opacity: { value: 1.0 },
  42494. map: { value: null },
  42495. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42496. alphaMap: { value: null },
  42497. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42498. alphaTest: { value: 0 }
  42499. },
  42500. specularmap: {
  42501. specularMap: { value: null },
  42502. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  42503. },
  42504. envmap: {
  42505. envMap: { value: null },
  42506. envMapRotation: { value: /*@__PURE__*/ new Matrix3() },
  42507. flipEnvMap: { value: -1 },
  42508. reflectivity: { value: 1.0 }, // basic, lambert, phong
  42509. ior: { value: 1.5 }, // physical
  42510. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  42511. },
  42512. aomap: {
  42513. aoMap: { value: null },
  42514. aoMapIntensity: { value: 1 },
  42515. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  42516. },
  42517. lightmap: {
  42518. lightMap: { value: null },
  42519. lightMapIntensity: { value: 1 },
  42520. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  42521. },
  42522. bumpmap: {
  42523. bumpMap: { value: null },
  42524. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42525. bumpScale: { value: 1 }
  42526. },
  42527. normalmap: {
  42528. normalMap: { value: null },
  42529. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42530. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  42531. },
  42532. displacementmap: {
  42533. displacementMap: { value: null },
  42534. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42535. displacementScale: { value: 1 },
  42536. displacementBias: { value: 0 }
  42537. },
  42538. emissivemap: {
  42539. emissiveMap: { value: null },
  42540. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  42541. },
  42542. metalnessmap: {
  42543. metalnessMap: { value: null },
  42544. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  42545. },
  42546. roughnessmap: {
  42547. roughnessMap: { value: null },
  42548. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  42549. },
  42550. gradientmap: {
  42551. gradientMap: { value: null }
  42552. },
  42553. fog: {
  42554. fogDensity: { value: 0.00025 },
  42555. fogNear: { value: 1 },
  42556. fogFar: { value: 2000 },
  42557. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  42558. },
  42559. lights: {
  42560. ambientLightColor: { value: [] },
  42561. lightProbe: { value: [] },
  42562. directionalLights: { value: [], properties: {
  42563. direction: {},
  42564. color: {}
  42565. } },
  42566. directionalLightShadows: { value: [], properties: {
  42567. shadowIntensity: 1,
  42568. shadowBias: {},
  42569. shadowNormalBias: {},
  42570. shadowRadius: {},
  42571. shadowMapSize: {}
  42572. } },
  42573. directionalShadowMap: { value: [] },
  42574. directionalShadowMatrix: { value: [] },
  42575. spotLights: { value: [], properties: {
  42576. color: {},
  42577. position: {},
  42578. direction: {},
  42579. distance: {},
  42580. coneCos: {},
  42581. penumbraCos: {},
  42582. decay: {}
  42583. } },
  42584. spotLightShadows: { value: [], properties: {
  42585. shadowIntensity: 1,
  42586. shadowBias: {},
  42587. shadowNormalBias: {},
  42588. shadowRadius: {},
  42589. shadowMapSize: {}
  42590. } },
  42591. spotLightMap: { value: [] },
  42592. spotShadowMap: { value: [] },
  42593. spotLightMatrix: { value: [] },
  42594. pointLights: { value: [], properties: {
  42595. color: {},
  42596. position: {},
  42597. decay: {},
  42598. distance: {}
  42599. } },
  42600. pointLightShadows: { value: [], properties: {
  42601. shadowIntensity: 1,
  42602. shadowBias: {},
  42603. shadowNormalBias: {},
  42604. shadowRadius: {},
  42605. shadowMapSize: {},
  42606. shadowCameraNear: {},
  42607. shadowCameraFar: {}
  42608. } },
  42609. pointShadowMap: { value: [] },
  42610. pointShadowMatrix: { value: [] },
  42611. hemisphereLights: { value: [], properties: {
  42612. direction: {},
  42613. skyColor: {},
  42614. groundColor: {}
  42615. } },
  42616. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  42617. rectAreaLights: { value: [], properties: {
  42618. color: {},
  42619. position: {},
  42620. width: {},
  42621. height: {}
  42622. } },
  42623. ltc_1: { value: null },
  42624. ltc_2: { value: null }
  42625. },
  42626. points: {
  42627. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  42628. opacity: { value: 1.0 },
  42629. size: { value: 1.0 },
  42630. scale: { value: 1.0 },
  42631. map: { value: null },
  42632. alphaMap: { value: null },
  42633. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42634. alphaTest: { value: 0 },
  42635. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  42636. },
  42637. sprite: {
  42638. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  42639. opacity: { value: 1.0 },
  42640. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  42641. rotation: { value: 0.0 },
  42642. map: { value: null },
  42643. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42644. alphaMap: { value: null },
  42645. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42646. alphaTest: { value: 0 }
  42647. }
  42648. };
  42649. const ShaderLib = {
  42650. basic: {
  42651. uniforms: /*@__PURE__*/ mergeUniforms( [
  42652. UniformsLib.common,
  42653. UniformsLib.specularmap,
  42654. UniformsLib.envmap,
  42655. UniformsLib.aomap,
  42656. UniformsLib.lightmap,
  42657. UniformsLib.fog
  42658. ] ),
  42659. vertexShader: ShaderChunk.meshbasic_vert,
  42660. fragmentShader: ShaderChunk.meshbasic_frag
  42661. },
  42662. lambert: {
  42663. uniforms: /*@__PURE__*/ mergeUniforms( [
  42664. UniformsLib.common,
  42665. UniformsLib.specularmap,
  42666. UniformsLib.envmap,
  42667. UniformsLib.aomap,
  42668. UniformsLib.lightmap,
  42669. UniformsLib.emissivemap,
  42670. UniformsLib.bumpmap,
  42671. UniformsLib.normalmap,
  42672. UniformsLib.displacementmap,
  42673. UniformsLib.fog,
  42674. UniformsLib.lights,
  42675. {
  42676. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  42677. }
  42678. ] ),
  42679. vertexShader: ShaderChunk.meshlambert_vert,
  42680. fragmentShader: ShaderChunk.meshlambert_frag
  42681. },
  42682. phong: {
  42683. uniforms: /*@__PURE__*/ mergeUniforms( [
  42684. UniformsLib.common,
  42685. UniformsLib.specularmap,
  42686. UniformsLib.envmap,
  42687. UniformsLib.aomap,
  42688. UniformsLib.lightmap,
  42689. UniformsLib.emissivemap,
  42690. UniformsLib.bumpmap,
  42691. UniformsLib.normalmap,
  42692. UniformsLib.displacementmap,
  42693. UniformsLib.fog,
  42694. UniformsLib.lights,
  42695. {
  42696. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  42697. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  42698. shininess: { value: 30 }
  42699. }
  42700. ] ),
  42701. vertexShader: ShaderChunk.meshphong_vert,
  42702. fragmentShader: ShaderChunk.meshphong_frag
  42703. },
  42704. standard: {
  42705. uniforms: /*@__PURE__*/ mergeUniforms( [
  42706. UniformsLib.common,
  42707. UniformsLib.envmap,
  42708. UniformsLib.aomap,
  42709. UniformsLib.lightmap,
  42710. UniformsLib.emissivemap,
  42711. UniformsLib.bumpmap,
  42712. UniformsLib.normalmap,
  42713. UniformsLib.displacementmap,
  42714. UniformsLib.roughnessmap,
  42715. UniformsLib.metalnessmap,
  42716. UniformsLib.fog,
  42717. UniformsLib.lights,
  42718. {
  42719. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  42720. roughness: { value: 1.0 },
  42721. metalness: { value: 0.0 },
  42722. envMapIntensity: { value: 1 }
  42723. }
  42724. ] ),
  42725. vertexShader: ShaderChunk.meshphysical_vert,
  42726. fragmentShader: ShaderChunk.meshphysical_frag
  42727. },
  42728. toon: {
  42729. uniforms: /*@__PURE__*/ mergeUniforms( [
  42730. UniformsLib.common,
  42731. UniformsLib.aomap,
  42732. UniformsLib.lightmap,
  42733. UniformsLib.emissivemap,
  42734. UniformsLib.bumpmap,
  42735. UniformsLib.normalmap,
  42736. UniformsLib.displacementmap,
  42737. UniformsLib.gradientmap,
  42738. UniformsLib.fog,
  42739. UniformsLib.lights,
  42740. {
  42741. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  42742. }
  42743. ] ),
  42744. vertexShader: ShaderChunk.meshtoon_vert,
  42745. fragmentShader: ShaderChunk.meshtoon_frag
  42746. },
  42747. matcap: {
  42748. uniforms: /*@__PURE__*/ mergeUniforms( [
  42749. UniformsLib.common,
  42750. UniformsLib.bumpmap,
  42751. UniformsLib.normalmap,
  42752. UniformsLib.displacementmap,
  42753. UniformsLib.fog,
  42754. {
  42755. matcap: { value: null }
  42756. }
  42757. ] ),
  42758. vertexShader: ShaderChunk.meshmatcap_vert,
  42759. fragmentShader: ShaderChunk.meshmatcap_frag
  42760. },
  42761. points: {
  42762. uniforms: /*@__PURE__*/ mergeUniforms( [
  42763. UniformsLib.points,
  42764. UniformsLib.fog
  42765. ] ),
  42766. vertexShader: ShaderChunk.points_vert,
  42767. fragmentShader: ShaderChunk.points_frag
  42768. },
  42769. dashed: {
  42770. uniforms: /*@__PURE__*/ mergeUniforms( [
  42771. UniformsLib.common,
  42772. UniformsLib.fog,
  42773. {
  42774. scale: { value: 1 },
  42775. dashSize: { value: 1 },
  42776. totalSize: { value: 2 }
  42777. }
  42778. ] ),
  42779. vertexShader: ShaderChunk.linedashed_vert,
  42780. fragmentShader: ShaderChunk.linedashed_frag
  42781. },
  42782. depth: {
  42783. uniforms: /*@__PURE__*/ mergeUniforms( [
  42784. UniformsLib.common,
  42785. UniformsLib.displacementmap
  42786. ] ),
  42787. vertexShader: ShaderChunk.depth_vert,
  42788. fragmentShader: ShaderChunk.depth_frag
  42789. },
  42790. normal: {
  42791. uniforms: /*@__PURE__*/ mergeUniforms( [
  42792. UniformsLib.common,
  42793. UniformsLib.bumpmap,
  42794. UniformsLib.normalmap,
  42795. UniformsLib.displacementmap,
  42796. {
  42797. opacity: { value: 1.0 }
  42798. }
  42799. ] ),
  42800. vertexShader: ShaderChunk.meshnormal_vert,
  42801. fragmentShader: ShaderChunk.meshnormal_frag
  42802. },
  42803. sprite: {
  42804. uniforms: /*@__PURE__*/ mergeUniforms( [
  42805. UniformsLib.sprite,
  42806. UniformsLib.fog
  42807. ] ),
  42808. vertexShader: ShaderChunk.sprite_vert,
  42809. fragmentShader: ShaderChunk.sprite_frag
  42810. },
  42811. background: {
  42812. uniforms: {
  42813. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  42814. t2D: { value: null },
  42815. backgroundIntensity: { value: 1 }
  42816. },
  42817. vertexShader: ShaderChunk.background_vert,
  42818. fragmentShader: ShaderChunk.background_frag
  42819. },
  42820. backgroundCube: {
  42821. uniforms: {
  42822. envMap: { value: null },
  42823. flipEnvMap: { value: -1 },
  42824. backgroundBlurriness: { value: 0 },
  42825. backgroundIntensity: { value: 1 },
  42826. backgroundRotation: { value: /*@__PURE__*/ new Matrix3() }
  42827. },
  42828. vertexShader: ShaderChunk.backgroundCube_vert,
  42829. fragmentShader: ShaderChunk.backgroundCube_frag
  42830. },
  42831. cube: {
  42832. uniforms: {
  42833. tCube: { value: null },
  42834. tFlip: { value: -1 },
  42835. opacity: { value: 1.0 }
  42836. },
  42837. vertexShader: ShaderChunk.cube_vert,
  42838. fragmentShader: ShaderChunk.cube_frag
  42839. },
  42840. equirect: {
  42841. uniforms: {
  42842. tEquirect: { value: null },
  42843. },
  42844. vertexShader: ShaderChunk.equirect_vert,
  42845. fragmentShader: ShaderChunk.equirect_frag
  42846. },
  42847. distanceRGBA: {
  42848. uniforms: /*@__PURE__*/ mergeUniforms( [
  42849. UniformsLib.common,
  42850. UniformsLib.displacementmap,
  42851. {
  42852. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  42853. nearDistance: { value: 1 },
  42854. farDistance: { value: 1000 }
  42855. }
  42856. ] ),
  42857. vertexShader: ShaderChunk.distanceRGBA_vert,
  42858. fragmentShader: ShaderChunk.distanceRGBA_frag
  42859. },
  42860. shadow: {
  42861. uniforms: /*@__PURE__*/ mergeUniforms( [
  42862. UniformsLib.lights,
  42863. UniformsLib.fog,
  42864. {
  42865. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  42866. opacity: { value: 1.0 }
  42867. },
  42868. ] ),
  42869. vertexShader: ShaderChunk.shadow_vert,
  42870. fragmentShader: ShaderChunk.shadow_frag
  42871. }
  42872. };
  42873. ShaderLib.physical = {
  42874. uniforms: /*@__PURE__*/ mergeUniforms( [
  42875. ShaderLib.standard.uniforms,
  42876. {
  42877. clearcoat: { value: 0 },
  42878. clearcoatMap: { value: null },
  42879. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42880. clearcoatNormalMap: { value: null },
  42881. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42882. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  42883. clearcoatRoughness: { value: 0 },
  42884. clearcoatRoughnessMap: { value: null },
  42885. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42886. dispersion: { value: 0 },
  42887. iridescence: { value: 0 },
  42888. iridescenceMap: { value: null },
  42889. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42890. iridescenceIOR: { value: 1.3 },
  42891. iridescenceThicknessMinimum: { value: 100 },
  42892. iridescenceThicknessMaximum: { value: 400 },
  42893. iridescenceThicknessMap: { value: null },
  42894. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42895. sheen: { value: 0 },
  42896. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  42897. sheenColorMap: { value: null },
  42898. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42899. sheenRoughness: { value: 1 },
  42900. sheenRoughnessMap: { value: null },
  42901. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42902. transmission: { value: 0 },
  42903. transmissionMap: { value: null },
  42904. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42905. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  42906. transmissionSamplerMap: { value: null },
  42907. thickness: { value: 0 },
  42908. thicknessMap: { value: null },
  42909. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42910. attenuationDistance: { value: 0 },
  42911. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  42912. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  42913. specularColorMap: { value: null },
  42914. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42915. specularIntensity: { value: 1 },
  42916. specularIntensityMap: { value: null },
  42917. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42918. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  42919. anisotropyMap: { value: null },
  42920. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42921. }
  42922. ] ),
  42923. vertexShader: ShaderChunk.meshphysical_vert,
  42924. fragmentShader: ShaderChunk.meshphysical_frag
  42925. };
  42926. const _rgb = { r: 0, b: 0, g: 0 };
  42927. const _e1$1 = /*@__PURE__*/ new Euler();
  42928. const _m1$1 = /*@__PURE__*/ new Matrix4();
  42929. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  42930. const clearColor = new Color( 0x000000 );
  42931. let clearAlpha = alpha === true ? 0 : 1;
  42932. let planeMesh;
  42933. let boxMesh;
  42934. let currentBackground = null;
  42935. let currentBackgroundVersion = 0;
  42936. let currentTonemapping = null;
  42937. function getBackground( scene ) {
  42938. let background = scene.isScene === true ? scene.background : null;
  42939. if ( background && background.isTexture ) {
  42940. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  42941. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  42942. }
  42943. return background;
  42944. }
  42945. function render( scene ) {
  42946. let forceClear = false;
  42947. const background = getBackground( scene );
  42948. if ( background === null ) {
  42949. setClear( clearColor, clearAlpha );
  42950. } else if ( background && background.isColor ) {
  42951. setClear( background, 1 );
  42952. forceClear = true;
  42953. }
  42954. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  42955. if ( environmentBlendMode === 'additive' ) {
  42956. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  42957. } else if ( environmentBlendMode === 'alpha-blend' ) {
  42958. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  42959. }
  42960. if ( renderer.autoClear || forceClear ) {
  42961. // buffers might not be writable which is required to ensure a correct clear
  42962. state.buffers.depth.setTest( true );
  42963. state.buffers.depth.setMask( true );
  42964. state.buffers.color.setMask( true );
  42965. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  42966. }
  42967. }
  42968. function addToRenderList( renderList, scene ) {
  42969. const background = getBackground( scene );
  42970. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  42971. if ( boxMesh === undefined ) {
  42972. boxMesh = new Mesh(
  42973. new BoxGeometry( 1, 1, 1 ),
  42974. new ShaderMaterial( {
  42975. name: 'BackgroundCubeMaterial',
  42976. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  42977. vertexShader: ShaderLib.backgroundCube.vertexShader,
  42978. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  42979. side: BackSide,
  42980. depthTest: false,
  42981. depthWrite: false,
  42982. fog: false,
  42983. allowOverride: false
  42984. } )
  42985. );
  42986. boxMesh.geometry.deleteAttribute( 'normal' );
  42987. boxMesh.geometry.deleteAttribute( 'uv' );
  42988. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  42989. this.matrixWorld.copyPosition( camera.matrixWorld );
  42990. };
  42991. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  42992. Object.defineProperty( boxMesh.material, 'envMap', {
  42993. get: function () {
  42994. return this.uniforms.envMap.value;
  42995. }
  42996. } );
  42997. objects.update( boxMesh );
  42998. }
  42999. _e1$1.copy( scene.backgroundRotation );
  43000. // accommodate left-handed frame
  43001. _e1$1.x *= -1; _e1$1.y *= -1; _e1$1.z *= -1;
  43002. if ( background.isCubeTexture && background.isRenderTargetTexture === false ) {
  43003. // environment maps which are not cube render targets or PMREMs follow a different convention
  43004. _e1$1.y *= -1;
  43005. _e1$1.z *= -1;
  43006. }
  43007. boxMesh.material.uniforms.envMap.value = background;
  43008. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? -1 : 1;
  43009. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  43010. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  43011. boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) );
  43012. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  43013. if ( currentBackground !== background ||
  43014. currentBackgroundVersion !== background.version ||
  43015. currentTonemapping !== renderer.toneMapping ) {
  43016. boxMesh.material.needsUpdate = true;
  43017. currentBackground = background;
  43018. currentBackgroundVersion = background.version;
  43019. currentTonemapping = renderer.toneMapping;
  43020. }
  43021. boxMesh.layers.enableAll();
  43022. // push to the pre-sorted opaque render list
  43023. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  43024. } else if ( background && background.isTexture ) {
  43025. if ( planeMesh === undefined ) {
  43026. planeMesh = new Mesh(
  43027. new PlaneGeometry( 2, 2 ),
  43028. new ShaderMaterial( {
  43029. name: 'BackgroundMaterial',
  43030. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  43031. vertexShader: ShaderLib.background.vertexShader,
  43032. fragmentShader: ShaderLib.background.fragmentShader,
  43033. side: FrontSide,
  43034. depthTest: false,
  43035. depthWrite: false,
  43036. fog: false,
  43037. allowOverride: false
  43038. } )
  43039. );
  43040. planeMesh.geometry.deleteAttribute( 'normal' );
  43041. // add "map" material property so the renderer can evaluate it like for built-in materials
  43042. Object.defineProperty( planeMesh.material, 'map', {
  43043. get: function () {
  43044. return this.uniforms.t2D.value;
  43045. }
  43046. } );
  43047. objects.update( planeMesh );
  43048. }
  43049. planeMesh.material.uniforms.t2D.value = background;
  43050. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  43051. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  43052. if ( background.matrixAutoUpdate === true ) {
  43053. background.updateMatrix();
  43054. }
  43055. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  43056. if ( currentBackground !== background ||
  43057. currentBackgroundVersion !== background.version ||
  43058. currentTonemapping !== renderer.toneMapping ) {
  43059. planeMesh.material.needsUpdate = true;
  43060. currentBackground = background;
  43061. currentBackgroundVersion = background.version;
  43062. currentTonemapping = renderer.toneMapping;
  43063. }
  43064. planeMesh.layers.enableAll();
  43065. // push to the pre-sorted opaque render list
  43066. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  43067. }
  43068. }
  43069. function setClear( color, alpha ) {
  43070. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  43071. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  43072. }
  43073. function dispose() {
  43074. if ( boxMesh !== undefined ) {
  43075. boxMesh.geometry.dispose();
  43076. boxMesh.material.dispose();
  43077. boxMesh = undefined;
  43078. }
  43079. if ( planeMesh !== undefined ) {
  43080. planeMesh.geometry.dispose();
  43081. planeMesh.material.dispose();
  43082. planeMesh = undefined;
  43083. }
  43084. }
  43085. return {
  43086. getClearColor: function () {
  43087. return clearColor;
  43088. },
  43089. setClearColor: function ( color, alpha = 1 ) {
  43090. clearColor.set( color );
  43091. clearAlpha = alpha;
  43092. setClear( clearColor, clearAlpha );
  43093. },
  43094. getClearAlpha: function () {
  43095. return clearAlpha;
  43096. },
  43097. setClearAlpha: function ( alpha ) {
  43098. clearAlpha = alpha;
  43099. setClear( clearColor, clearAlpha );
  43100. },
  43101. render: render,
  43102. addToRenderList: addToRenderList,
  43103. dispose: dispose
  43104. };
  43105. }
  43106. function WebGLBindingStates( gl, attributes ) {
  43107. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  43108. const bindingStates = {};
  43109. const defaultState = createBindingState( null );
  43110. let currentState = defaultState;
  43111. let forceUpdate = false;
  43112. function setup( object, material, program, geometry, index ) {
  43113. let updateBuffers = false;
  43114. const state = getBindingState( geometry, program, material );
  43115. if ( currentState !== state ) {
  43116. currentState = state;
  43117. bindVertexArrayObject( currentState.object );
  43118. }
  43119. updateBuffers = needsUpdate( object, geometry, program, index );
  43120. if ( updateBuffers ) saveCache( object, geometry, program, index );
  43121. if ( index !== null ) {
  43122. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  43123. }
  43124. if ( updateBuffers || forceUpdate ) {
  43125. forceUpdate = false;
  43126. setupVertexAttributes( object, material, program, geometry );
  43127. if ( index !== null ) {
  43128. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  43129. }
  43130. }
  43131. }
  43132. function createVertexArrayObject() {
  43133. return gl.createVertexArray();
  43134. }
  43135. function bindVertexArrayObject( vao ) {
  43136. return gl.bindVertexArray( vao );
  43137. }
  43138. function deleteVertexArrayObject( vao ) {
  43139. return gl.deleteVertexArray( vao );
  43140. }
  43141. function getBindingState( geometry, program, material ) {
  43142. const wireframe = ( material.wireframe === true );
  43143. let programMap = bindingStates[ geometry.id ];
  43144. if ( programMap === undefined ) {
  43145. programMap = {};
  43146. bindingStates[ geometry.id ] = programMap;
  43147. }
  43148. let stateMap = programMap[ program.id ];
  43149. if ( stateMap === undefined ) {
  43150. stateMap = {};
  43151. programMap[ program.id ] = stateMap;
  43152. }
  43153. let state = stateMap[ wireframe ];
  43154. if ( state === undefined ) {
  43155. state = createBindingState( createVertexArrayObject() );
  43156. stateMap[ wireframe ] = state;
  43157. }
  43158. return state;
  43159. }
  43160. function createBindingState( vao ) {
  43161. const newAttributes = [];
  43162. const enabledAttributes = [];
  43163. const attributeDivisors = [];
  43164. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  43165. newAttributes[ i ] = 0;
  43166. enabledAttributes[ i ] = 0;
  43167. attributeDivisors[ i ] = 0;
  43168. }
  43169. return {
  43170. // for backward compatibility on non-VAO support browser
  43171. geometry: null,
  43172. program: null,
  43173. wireframe: false,
  43174. newAttributes: newAttributes,
  43175. enabledAttributes: enabledAttributes,
  43176. attributeDivisors: attributeDivisors,
  43177. object: vao,
  43178. attributes: {},
  43179. index: null
  43180. };
  43181. }
  43182. function needsUpdate( object, geometry, program, index ) {
  43183. const cachedAttributes = currentState.attributes;
  43184. const geometryAttributes = geometry.attributes;
  43185. let attributesNum = 0;
  43186. const programAttributes = program.getAttributes();
  43187. for ( const name in programAttributes ) {
  43188. const programAttribute = programAttributes[ name ];
  43189. if ( programAttribute.location >= 0 ) {
  43190. const cachedAttribute = cachedAttributes[ name ];
  43191. let geometryAttribute = geometryAttributes[ name ];
  43192. if ( geometryAttribute === undefined ) {
  43193. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  43194. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  43195. }
  43196. if ( cachedAttribute === undefined ) return true;
  43197. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  43198. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  43199. attributesNum ++;
  43200. }
  43201. }
  43202. if ( currentState.attributesNum !== attributesNum ) return true;
  43203. if ( currentState.index !== index ) return true;
  43204. return false;
  43205. }
  43206. function saveCache( object, geometry, program, index ) {
  43207. const cache = {};
  43208. const attributes = geometry.attributes;
  43209. let attributesNum = 0;
  43210. const programAttributes = program.getAttributes();
  43211. for ( const name in programAttributes ) {
  43212. const programAttribute = programAttributes[ name ];
  43213. if ( programAttribute.location >= 0 ) {
  43214. let attribute = attributes[ name ];
  43215. if ( attribute === undefined ) {
  43216. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  43217. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  43218. }
  43219. const data = {};
  43220. data.attribute = attribute;
  43221. if ( attribute && attribute.data ) {
  43222. data.data = attribute.data;
  43223. }
  43224. cache[ name ] = data;
  43225. attributesNum ++;
  43226. }
  43227. }
  43228. currentState.attributes = cache;
  43229. currentState.attributesNum = attributesNum;
  43230. currentState.index = index;
  43231. }
  43232. function initAttributes() {
  43233. const newAttributes = currentState.newAttributes;
  43234. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  43235. newAttributes[ i ] = 0;
  43236. }
  43237. }
  43238. function enableAttribute( attribute ) {
  43239. enableAttributeAndDivisor( attribute, 0 );
  43240. }
  43241. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  43242. const newAttributes = currentState.newAttributes;
  43243. const enabledAttributes = currentState.enabledAttributes;
  43244. const attributeDivisors = currentState.attributeDivisors;
  43245. newAttributes[ attribute ] = 1;
  43246. if ( enabledAttributes[ attribute ] === 0 ) {
  43247. gl.enableVertexAttribArray( attribute );
  43248. enabledAttributes[ attribute ] = 1;
  43249. }
  43250. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  43251. gl.vertexAttribDivisor( attribute, meshPerAttribute );
  43252. attributeDivisors[ attribute ] = meshPerAttribute;
  43253. }
  43254. }
  43255. function disableUnusedAttributes() {
  43256. const newAttributes = currentState.newAttributes;
  43257. const enabledAttributes = currentState.enabledAttributes;
  43258. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  43259. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  43260. gl.disableVertexAttribArray( i );
  43261. enabledAttributes[ i ] = 0;
  43262. }
  43263. }
  43264. }
  43265. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  43266. if ( integer === true ) {
  43267. gl.vertexAttribIPointer( index, size, type, stride, offset );
  43268. } else {
  43269. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  43270. }
  43271. }
  43272. function setupVertexAttributes( object, material, program, geometry ) {
  43273. initAttributes();
  43274. const geometryAttributes = geometry.attributes;
  43275. const programAttributes = program.getAttributes();
  43276. const materialDefaultAttributeValues = material.defaultAttributeValues;
  43277. for ( const name in programAttributes ) {
  43278. const programAttribute = programAttributes[ name ];
  43279. if ( programAttribute.location >= 0 ) {
  43280. let geometryAttribute = geometryAttributes[ name ];
  43281. if ( geometryAttribute === undefined ) {
  43282. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  43283. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  43284. }
  43285. if ( geometryAttribute !== undefined ) {
  43286. const normalized = geometryAttribute.normalized;
  43287. const size = geometryAttribute.itemSize;
  43288. const attribute = attributes.get( geometryAttribute );
  43289. // TODO Attribute may not be available on context restore
  43290. if ( attribute === undefined ) continue;
  43291. const buffer = attribute.buffer;
  43292. const type = attribute.type;
  43293. const bytesPerElement = attribute.bytesPerElement;
  43294. // check for integer attributes
  43295. const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType );
  43296. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  43297. const data = geometryAttribute.data;
  43298. const stride = data.stride;
  43299. const offset = geometryAttribute.offset;
  43300. if ( data.isInstancedInterleavedBuffer ) {
  43301. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43302. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  43303. }
  43304. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  43305. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  43306. }
  43307. } else {
  43308. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43309. enableAttribute( programAttribute.location + i );
  43310. }
  43311. }
  43312. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  43313. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43314. vertexAttribPointer(
  43315. programAttribute.location + i,
  43316. size / programAttribute.locationSize,
  43317. type,
  43318. normalized,
  43319. stride * bytesPerElement,
  43320. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  43321. integer
  43322. );
  43323. }
  43324. } else {
  43325. if ( geometryAttribute.isInstancedBufferAttribute ) {
  43326. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43327. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  43328. }
  43329. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  43330. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  43331. }
  43332. } else {
  43333. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43334. enableAttribute( programAttribute.location + i );
  43335. }
  43336. }
  43337. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  43338. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43339. vertexAttribPointer(
  43340. programAttribute.location + i,
  43341. size / programAttribute.locationSize,
  43342. type,
  43343. normalized,
  43344. size * bytesPerElement,
  43345. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  43346. integer
  43347. );
  43348. }
  43349. }
  43350. } else if ( materialDefaultAttributeValues !== undefined ) {
  43351. const value = materialDefaultAttributeValues[ name ];
  43352. if ( value !== undefined ) {
  43353. switch ( value.length ) {
  43354. case 2:
  43355. gl.vertexAttrib2fv( programAttribute.location, value );
  43356. break;
  43357. case 3:
  43358. gl.vertexAttrib3fv( programAttribute.location, value );
  43359. break;
  43360. case 4:
  43361. gl.vertexAttrib4fv( programAttribute.location, value );
  43362. break;
  43363. default:
  43364. gl.vertexAttrib1fv( programAttribute.location, value );
  43365. }
  43366. }
  43367. }
  43368. }
  43369. }
  43370. disableUnusedAttributes();
  43371. }
  43372. function dispose() {
  43373. reset();
  43374. for ( const geometryId in bindingStates ) {
  43375. const programMap = bindingStates[ geometryId ];
  43376. for ( const programId in programMap ) {
  43377. const stateMap = programMap[ programId ];
  43378. for ( const wireframe in stateMap ) {
  43379. deleteVertexArrayObject( stateMap[ wireframe ].object );
  43380. delete stateMap[ wireframe ];
  43381. }
  43382. delete programMap[ programId ];
  43383. }
  43384. delete bindingStates[ geometryId ];
  43385. }
  43386. }
  43387. function releaseStatesOfGeometry( geometry ) {
  43388. if ( bindingStates[ geometry.id ] === undefined ) return;
  43389. const programMap = bindingStates[ geometry.id ];
  43390. for ( const programId in programMap ) {
  43391. const stateMap = programMap[ programId ];
  43392. for ( const wireframe in stateMap ) {
  43393. deleteVertexArrayObject( stateMap[ wireframe ].object );
  43394. delete stateMap[ wireframe ];
  43395. }
  43396. delete programMap[ programId ];
  43397. }
  43398. delete bindingStates[ geometry.id ];
  43399. }
  43400. function releaseStatesOfProgram( program ) {
  43401. for ( const geometryId in bindingStates ) {
  43402. const programMap = bindingStates[ geometryId ];
  43403. if ( programMap[ program.id ] === undefined ) continue;
  43404. const stateMap = programMap[ program.id ];
  43405. for ( const wireframe in stateMap ) {
  43406. deleteVertexArrayObject( stateMap[ wireframe ].object );
  43407. delete stateMap[ wireframe ];
  43408. }
  43409. delete programMap[ program.id ];
  43410. }
  43411. }
  43412. function reset() {
  43413. resetDefaultState();
  43414. forceUpdate = true;
  43415. if ( currentState === defaultState ) return;
  43416. currentState = defaultState;
  43417. bindVertexArrayObject( currentState.object );
  43418. }
  43419. // for backward-compatibility
  43420. function resetDefaultState() {
  43421. defaultState.geometry = null;
  43422. defaultState.program = null;
  43423. defaultState.wireframe = false;
  43424. }
  43425. return {
  43426. setup: setup,
  43427. reset: reset,
  43428. resetDefaultState: resetDefaultState,
  43429. dispose: dispose,
  43430. releaseStatesOfGeometry: releaseStatesOfGeometry,
  43431. releaseStatesOfProgram: releaseStatesOfProgram,
  43432. initAttributes: initAttributes,
  43433. enableAttribute: enableAttribute,
  43434. disableUnusedAttributes: disableUnusedAttributes
  43435. };
  43436. }
  43437. function WebGLBufferRenderer( gl, extensions, info ) {
  43438. let mode;
  43439. function setMode( value ) {
  43440. mode = value;
  43441. }
  43442. function render( start, count ) {
  43443. gl.drawArrays( mode, start, count );
  43444. info.update( count, mode, 1 );
  43445. }
  43446. function renderInstances( start, count, primcount ) {
  43447. if ( primcount === 0 ) return;
  43448. gl.drawArraysInstanced( mode, start, count, primcount );
  43449. info.update( count, mode, primcount );
  43450. }
  43451. function renderMultiDraw( starts, counts, drawCount ) {
  43452. if ( drawCount === 0 ) return;
  43453. const extension = extensions.get( 'WEBGL_multi_draw' );
  43454. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  43455. let elementCount = 0;
  43456. for ( let i = 0; i < drawCount; i ++ ) {
  43457. elementCount += counts[ i ];
  43458. }
  43459. info.update( elementCount, mode, 1 );
  43460. }
  43461. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  43462. if ( drawCount === 0 ) return;
  43463. const extension = extensions.get( 'WEBGL_multi_draw' );
  43464. if ( extension === null ) {
  43465. for ( let i = 0; i < starts.length; i ++ ) {
  43466. renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  43467. }
  43468. } else {
  43469. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  43470. let elementCount = 0;
  43471. for ( let i = 0; i < drawCount; i ++ ) {
  43472. elementCount += counts[ i ] * primcount[ i ];
  43473. }
  43474. info.update( elementCount, mode, 1 );
  43475. }
  43476. }
  43477. //
  43478. this.setMode = setMode;
  43479. this.render = render;
  43480. this.renderInstances = renderInstances;
  43481. this.renderMultiDraw = renderMultiDraw;
  43482. this.renderMultiDrawInstances = renderMultiDrawInstances;
  43483. }
  43484. function WebGLCapabilities( gl, extensions, parameters, utils ) {
  43485. let maxAnisotropy;
  43486. function getMaxAnisotropy() {
  43487. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  43488. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  43489. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  43490. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  43491. } else {
  43492. maxAnisotropy = 0;
  43493. }
  43494. return maxAnisotropy;
  43495. }
  43496. function textureFormatReadable( textureFormat ) {
  43497. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  43498. return false;
  43499. }
  43500. return true;
  43501. }
  43502. function textureTypeReadable( textureType ) {
  43503. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) );
  43504. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  43505. textureType !== FloatType && ! halfFloatSupportedByExt ) {
  43506. return false;
  43507. }
  43508. return true;
  43509. }
  43510. function getMaxPrecision( precision ) {
  43511. if ( precision === 'highp' ) {
  43512. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  43513. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  43514. return 'highp';
  43515. }
  43516. precision = 'mediump';
  43517. }
  43518. if ( precision === 'mediump' ) {
  43519. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  43520. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  43521. return 'mediump';
  43522. }
  43523. }
  43524. return 'lowp';
  43525. }
  43526. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  43527. const maxPrecision = getMaxPrecision( precision );
  43528. if ( maxPrecision !== precision ) {
  43529. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  43530. precision = maxPrecision;
  43531. }
  43532. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  43533. const reverseDepthBuffer = parameters.reverseDepthBuffer === true && extensions.has( 'EXT_clip_control' );
  43534. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  43535. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  43536. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  43537. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  43538. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  43539. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  43540. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  43541. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  43542. const vertexTextures = maxVertexTextures > 0;
  43543. const maxSamples = gl.getParameter( gl.MAX_SAMPLES );
  43544. return {
  43545. isWebGL2: true, // keeping this for backwards compatibility
  43546. getMaxAnisotropy: getMaxAnisotropy,
  43547. getMaxPrecision: getMaxPrecision,
  43548. textureFormatReadable: textureFormatReadable,
  43549. textureTypeReadable: textureTypeReadable,
  43550. precision: precision,
  43551. logarithmicDepthBuffer: logarithmicDepthBuffer,
  43552. reverseDepthBuffer: reverseDepthBuffer,
  43553. maxTextures: maxTextures,
  43554. maxVertexTextures: maxVertexTextures,
  43555. maxTextureSize: maxTextureSize,
  43556. maxCubemapSize: maxCubemapSize,
  43557. maxAttributes: maxAttributes,
  43558. maxVertexUniforms: maxVertexUniforms,
  43559. maxVaryings: maxVaryings,
  43560. maxFragmentUniforms: maxFragmentUniforms,
  43561. vertexTextures: vertexTextures,
  43562. maxSamples: maxSamples
  43563. };
  43564. }
  43565. function WebGLClipping( properties ) {
  43566. const scope = this;
  43567. let globalState = null,
  43568. numGlobalPlanes = 0,
  43569. localClippingEnabled = false,
  43570. renderingShadows = false;
  43571. const plane = new Plane(),
  43572. viewNormalMatrix = new Matrix3(),
  43573. uniform = { value: null, needsUpdate: false };
  43574. this.uniform = uniform;
  43575. this.numPlanes = 0;
  43576. this.numIntersection = 0;
  43577. this.init = function ( planes, enableLocalClipping ) {
  43578. const enabled =
  43579. planes.length !== 0 ||
  43580. enableLocalClipping ||
  43581. // enable state of previous frame - the clipping code has to
  43582. // run another frame in order to reset the state:
  43583. numGlobalPlanes !== 0 ||
  43584. localClippingEnabled;
  43585. localClippingEnabled = enableLocalClipping;
  43586. numGlobalPlanes = planes.length;
  43587. return enabled;
  43588. };
  43589. this.beginShadows = function () {
  43590. renderingShadows = true;
  43591. projectPlanes( null );
  43592. };
  43593. this.endShadows = function () {
  43594. renderingShadows = false;
  43595. };
  43596. this.setGlobalState = function ( planes, camera ) {
  43597. globalState = projectPlanes( planes, camera, 0 );
  43598. };
  43599. this.setState = function ( material, camera, useCache ) {
  43600. const planes = material.clippingPlanes,
  43601. clipIntersection = material.clipIntersection,
  43602. clipShadows = material.clipShadows;
  43603. const materialProperties = properties.get( material );
  43604. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  43605. // there's no local clipping
  43606. if ( renderingShadows ) {
  43607. // there's no global clipping
  43608. projectPlanes( null );
  43609. } else {
  43610. resetGlobalState();
  43611. }
  43612. } else {
  43613. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  43614. lGlobal = nGlobal * 4;
  43615. let dstArray = materialProperties.clippingState || null;
  43616. uniform.value = dstArray; // ensure unique state
  43617. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  43618. for ( let i = 0; i !== lGlobal; ++ i ) {
  43619. dstArray[ i ] = globalState[ i ];
  43620. }
  43621. materialProperties.clippingState = dstArray;
  43622. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  43623. this.numPlanes += nGlobal;
  43624. }
  43625. };
  43626. function resetGlobalState() {
  43627. if ( uniform.value !== globalState ) {
  43628. uniform.value = globalState;
  43629. uniform.needsUpdate = numGlobalPlanes > 0;
  43630. }
  43631. scope.numPlanes = numGlobalPlanes;
  43632. scope.numIntersection = 0;
  43633. }
  43634. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  43635. const nPlanes = planes !== null ? planes.length : 0;
  43636. let dstArray = null;
  43637. if ( nPlanes !== 0 ) {
  43638. dstArray = uniform.value;
  43639. if ( skipTransform !== true || dstArray === null ) {
  43640. const flatSize = dstOffset + nPlanes * 4,
  43641. viewMatrix = camera.matrixWorldInverse;
  43642. viewNormalMatrix.getNormalMatrix( viewMatrix );
  43643. if ( dstArray === null || dstArray.length < flatSize ) {
  43644. dstArray = new Float32Array( flatSize );
  43645. }
  43646. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  43647. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  43648. plane.normal.toArray( dstArray, i4 );
  43649. dstArray[ i4 + 3 ] = plane.constant;
  43650. }
  43651. }
  43652. uniform.value = dstArray;
  43653. uniform.needsUpdate = true;
  43654. }
  43655. scope.numPlanes = nPlanes;
  43656. scope.numIntersection = 0;
  43657. return dstArray;
  43658. }
  43659. }
  43660. function WebGLCubeMaps( renderer ) {
  43661. let cubemaps = new WeakMap();
  43662. function mapTextureMapping( texture, mapping ) {
  43663. if ( mapping === EquirectangularReflectionMapping ) {
  43664. texture.mapping = CubeReflectionMapping;
  43665. } else if ( mapping === EquirectangularRefractionMapping ) {
  43666. texture.mapping = CubeRefractionMapping;
  43667. }
  43668. return texture;
  43669. }
  43670. function get( texture ) {
  43671. if ( texture && texture.isTexture ) {
  43672. const mapping = texture.mapping;
  43673. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  43674. if ( cubemaps.has( texture ) ) {
  43675. const cubemap = cubemaps.get( texture ).texture;
  43676. return mapTextureMapping( cubemap, texture.mapping );
  43677. } else {
  43678. const image = texture.image;
  43679. if ( image && image.height > 0 ) {
  43680. const renderTarget = new WebGLCubeRenderTarget( image.height );
  43681. renderTarget.fromEquirectangularTexture( renderer, texture );
  43682. cubemaps.set( texture, renderTarget );
  43683. texture.addEventListener( 'dispose', onTextureDispose );
  43684. return mapTextureMapping( renderTarget.texture, texture.mapping );
  43685. } else {
  43686. // image not yet ready. try the conversion next frame
  43687. return null;
  43688. }
  43689. }
  43690. }
  43691. }
  43692. return texture;
  43693. }
  43694. function onTextureDispose( event ) {
  43695. const texture = event.target;
  43696. texture.removeEventListener( 'dispose', onTextureDispose );
  43697. const cubemap = cubemaps.get( texture );
  43698. if ( cubemap !== undefined ) {
  43699. cubemaps.delete( texture );
  43700. cubemap.dispose();
  43701. }
  43702. }
  43703. function dispose() {
  43704. cubemaps = new WeakMap();
  43705. }
  43706. return {
  43707. get: get,
  43708. dispose: dispose
  43709. };
  43710. }
  43711. const LOD_MIN = 4;
  43712. // The standard deviations (radians) associated with the extra mips. These are
  43713. // chosen to approximate a Trowbridge-Reitz distribution function times the
  43714. // geometric shadowing function. These sigma values squared must match the
  43715. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  43716. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  43717. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  43718. // samples and exit early, but not recompile the shader.
  43719. const MAX_SAMPLES = 20;
  43720. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  43721. const _clearColor = /*@__PURE__*/ new Color();
  43722. let _oldTarget = null;
  43723. let _oldActiveCubeFace = 0;
  43724. let _oldActiveMipmapLevel = 0;
  43725. let _oldXrEnabled = false;
  43726. // Golden Ratio
  43727. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  43728. const INV_PHI = 1 / PHI;
  43729. // Vertices of a dodecahedron (except the opposites, which represent the
  43730. // same axis), used as axis directions evenly spread on a sphere.
  43731. const _axisDirections = [
  43732. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  43733. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  43734. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  43735. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  43736. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  43737. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  43738. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  43739. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  43740. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  43741. /*@__PURE__*/ new Vector3( 1, 1, 1 ) ];
  43742. const _origin = /*@__PURE__*/ new Vector3();
  43743. /**
  43744. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  43745. * (PMREM) from a cubeMap environment texture. This allows different levels of
  43746. * blur to be quickly accessed based on material roughness. It is packed into a
  43747. * special CubeUV format that allows us to perform custom interpolation so that
  43748. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  43749. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  43750. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  43751. * higher roughness levels. In this way we maintain resolution to smoothly
  43752. * interpolate diffuse lighting while limiting sampling computation.
  43753. *
  43754. * Paper: Fast, Accurate Image-Based Lighting:
  43755. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  43756. */
  43757. class PMREMGenerator {
  43758. /**
  43759. * Constructs a new PMREM generator.
  43760. *
  43761. * @param {WebGLRenderer} renderer - The renderer.
  43762. */
  43763. constructor( renderer ) {
  43764. this._renderer = renderer;
  43765. this._pingPongRenderTarget = null;
  43766. this._lodMax = 0;
  43767. this._cubeSize = 0;
  43768. this._lodPlanes = [];
  43769. this._sizeLods = [];
  43770. this._sigmas = [];
  43771. this._blurMaterial = null;
  43772. this._cubemapMaterial = null;
  43773. this._equirectMaterial = null;
  43774. this._compileMaterial( this._blurMaterial );
  43775. }
  43776. /**
  43777. * Generates a PMREM from a supplied Scene, which can be faster than using an
  43778. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  43779. * in radians to be applied to the scene before PMREM generation. Optional near
  43780. * and far planes ensure the scene is rendered in its entirety.
  43781. *
  43782. * @param {Scene} scene - The scene to be captured.
  43783. * @param {number} [sigma=0] - The blur radius in radians.
  43784. * @param {number} [near=0.1] - The near plane distance.
  43785. * @param {number} [far=100] - The far plane distance.
  43786. * @param {Object} [options={}] - The configuration options.
  43787. * @param {number} [options.size=256] - The texture size of the PMREM.
  43788. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  43789. * @return {WebGLRenderTarget} The resulting PMREM.
  43790. */
  43791. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  43792. const {
  43793. size = 256,
  43794. position = _origin,
  43795. } = options;
  43796. _oldTarget = this._renderer.getRenderTarget();
  43797. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  43798. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  43799. _oldXrEnabled = this._renderer.xr.enabled;
  43800. this._renderer.xr.enabled = false;
  43801. this._setSize( size );
  43802. const cubeUVRenderTarget = this._allocateTargets();
  43803. cubeUVRenderTarget.depthBuffer = true;
  43804. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  43805. if ( sigma > 0 ) {
  43806. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  43807. }
  43808. this._applyPMREM( cubeUVRenderTarget );
  43809. this._cleanup( cubeUVRenderTarget );
  43810. return cubeUVRenderTarget;
  43811. }
  43812. /**
  43813. * Generates a PMREM from an equirectangular texture, which can be either LDR
  43814. * or HDR. The ideal input image size is 1k (1024 x 512),
  43815. * as this matches best with the 256 x 256 cubemap output.
  43816. *
  43817. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  43818. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  43819. * @return {WebGLRenderTarget} The resulting PMREM.
  43820. */
  43821. fromEquirectangular( equirectangular, renderTarget = null ) {
  43822. return this._fromTexture( equirectangular, renderTarget );
  43823. }
  43824. /**
  43825. * Generates a PMREM from an cubemap texture, which can be either LDR
  43826. * or HDR. The ideal input cube size is 256 x 256,
  43827. * as this matches best with the 256 x 256 cubemap output.
  43828. *
  43829. * @param {Texture} cubemap - The cubemap texture to be converted.
  43830. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  43831. * @return {WebGLRenderTarget} The resulting PMREM.
  43832. */
  43833. fromCubemap( cubemap, renderTarget = null ) {
  43834. return this._fromTexture( cubemap, renderTarget );
  43835. }
  43836. /**
  43837. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  43838. * your texture's network fetch for increased concurrency.
  43839. */
  43840. compileCubemapShader() {
  43841. if ( this._cubemapMaterial === null ) {
  43842. this._cubemapMaterial = _getCubemapMaterial();
  43843. this._compileMaterial( this._cubemapMaterial );
  43844. }
  43845. }
  43846. /**
  43847. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  43848. * your texture's network fetch for increased concurrency.
  43849. */
  43850. compileEquirectangularShader() {
  43851. if ( this._equirectMaterial === null ) {
  43852. this._equirectMaterial = _getEquirectMaterial();
  43853. this._compileMaterial( this._equirectMaterial );
  43854. }
  43855. }
  43856. /**
  43857. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  43858. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  43859. * one of them will cause any others to also become unusable.
  43860. */
  43861. dispose() {
  43862. this._dispose();
  43863. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  43864. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  43865. }
  43866. // private interface
  43867. _setSize( cubeSize ) {
  43868. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  43869. this._cubeSize = Math.pow( 2, this._lodMax );
  43870. }
  43871. _dispose() {
  43872. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  43873. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  43874. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  43875. this._lodPlanes[ i ].dispose();
  43876. }
  43877. }
  43878. _cleanup( outputTarget ) {
  43879. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  43880. this._renderer.xr.enabled = _oldXrEnabled;
  43881. outputTarget.scissorTest = false;
  43882. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  43883. }
  43884. _fromTexture( texture, renderTarget ) {
  43885. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  43886. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  43887. } else { // Equirectangular
  43888. this._setSize( texture.image.width / 4 );
  43889. }
  43890. _oldTarget = this._renderer.getRenderTarget();
  43891. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  43892. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  43893. _oldXrEnabled = this._renderer.xr.enabled;
  43894. this._renderer.xr.enabled = false;
  43895. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  43896. this._textureToCubeUV( texture, cubeUVRenderTarget );
  43897. this._applyPMREM( cubeUVRenderTarget );
  43898. this._cleanup( cubeUVRenderTarget );
  43899. return cubeUVRenderTarget;
  43900. }
  43901. _allocateTargets() {
  43902. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  43903. const height = 4 * this._cubeSize;
  43904. const params = {
  43905. magFilter: LinearFilter,
  43906. minFilter: LinearFilter,
  43907. generateMipmaps: false,
  43908. type: HalfFloatType,
  43909. format: RGBAFormat,
  43910. colorSpace: LinearSRGBColorSpace,
  43911. depthBuffer: false
  43912. };
  43913. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  43914. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  43915. if ( this._pingPongRenderTarget !== null ) {
  43916. this._dispose();
  43917. }
  43918. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  43919. const { _lodMax } = this;
  43920. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  43921. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  43922. }
  43923. return cubeUVRenderTarget;
  43924. }
  43925. _compileMaterial( material ) {
  43926. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  43927. this._renderer.compile( tmpMesh, _flatCamera );
  43928. }
  43929. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  43930. const fov = 90;
  43931. const aspect = 1;
  43932. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  43933. const upSign = [ 1, -1, 1, 1, 1, 1 ];
  43934. const forwardSign = [ 1, 1, 1, -1, -1, -1 ];
  43935. const renderer = this._renderer;
  43936. const originalAutoClear = renderer.autoClear;
  43937. const toneMapping = renderer.toneMapping;
  43938. renderer.getClearColor( _clearColor );
  43939. renderer.toneMapping = NoToneMapping;
  43940. renderer.autoClear = false;
  43941. const backgroundMaterial = new MeshBasicMaterial( {
  43942. name: 'PMREM.Background',
  43943. side: BackSide,
  43944. depthWrite: false,
  43945. depthTest: false,
  43946. } );
  43947. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  43948. let useSolidColor = false;
  43949. const background = scene.background;
  43950. if ( background ) {
  43951. if ( background.isColor ) {
  43952. backgroundMaterial.color.copy( background );
  43953. scene.background = null;
  43954. useSolidColor = true;
  43955. }
  43956. } else {
  43957. backgroundMaterial.color.copy( _clearColor );
  43958. useSolidColor = true;
  43959. }
  43960. for ( let i = 0; i < 6; i ++ ) {
  43961. const col = i % 3;
  43962. if ( col === 0 ) {
  43963. cubeCamera.up.set( 0, upSign[ i ], 0 );
  43964. cubeCamera.position.set( position.x, position.y, position.z );
  43965. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  43966. } else if ( col === 1 ) {
  43967. cubeCamera.up.set( 0, 0, upSign[ i ] );
  43968. cubeCamera.position.set( position.x, position.y, position.z );
  43969. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  43970. } else {
  43971. cubeCamera.up.set( 0, upSign[ i ], 0 );
  43972. cubeCamera.position.set( position.x, position.y, position.z );
  43973. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  43974. }
  43975. const size = this._cubeSize;
  43976. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  43977. renderer.setRenderTarget( cubeUVRenderTarget );
  43978. if ( useSolidColor ) {
  43979. renderer.render( backgroundBox, cubeCamera );
  43980. }
  43981. renderer.render( scene, cubeCamera );
  43982. }
  43983. backgroundBox.geometry.dispose();
  43984. backgroundBox.material.dispose();
  43985. renderer.toneMapping = toneMapping;
  43986. renderer.autoClear = originalAutoClear;
  43987. scene.background = background;
  43988. }
  43989. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  43990. const renderer = this._renderer;
  43991. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  43992. if ( isCubeTexture ) {
  43993. if ( this._cubemapMaterial === null ) {
  43994. this._cubemapMaterial = _getCubemapMaterial();
  43995. }
  43996. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? -1 : 1;
  43997. } else {
  43998. if ( this._equirectMaterial === null ) {
  43999. this._equirectMaterial = _getEquirectMaterial();
  44000. }
  44001. }
  44002. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  44003. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  44004. const uniforms = material.uniforms;
  44005. uniforms[ 'envMap' ].value = texture;
  44006. const size = this._cubeSize;
  44007. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  44008. renderer.setRenderTarget( cubeUVRenderTarget );
  44009. renderer.render( mesh, _flatCamera );
  44010. }
  44011. _applyPMREM( cubeUVRenderTarget ) {
  44012. const renderer = this._renderer;
  44013. const autoClear = renderer.autoClear;
  44014. renderer.autoClear = false;
  44015. const n = this._lodPlanes.length;
  44016. for ( let i = 1; i < n; i ++ ) {
  44017. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  44018. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  44019. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  44020. }
  44021. renderer.autoClear = autoClear;
  44022. }
  44023. /**
  44024. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  44025. * vertically and horizontally, but this breaks down on a cube. Here we apply
  44026. * the blur latitudinally (around the poles), and then longitudinally (towards
  44027. * the poles) to approximate the orthogonally-separable blur. It is least
  44028. * accurate at the poles, but still does a decent job.
  44029. *
  44030. * @private
  44031. * @param {WebGLRenderTarget} cubeUVRenderTarget
  44032. * @param {number} lodIn
  44033. * @param {number} lodOut
  44034. * @param {number} sigma
  44035. * @param {Vector3} [poleAxis]
  44036. */
  44037. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  44038. const pingPongRenderTarget = this._pingPongRenderTarget;
  44039. this._halfBlur(
  44040. cubeUVRenderTarget,
  44041. pingPongRenderTarget,
  44042. lodIn,
  44043. lodOut,
  44044. sigma,
  44045. 'latitudinal',
  44046. poleAxis );
  44047. this._halfBlur(
  44048. pingPongRenderTarget,
  44049. cubeUVRenderTarget,
  44050. lodOut,
  44051. lodOut,
  44052. sigma,
  44053. 'longitudinal',
  44054. poleAxis );
  44055. }
  44056. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  44057. const renderer = this._renderer;
  44058. const blurMaterial = this._blurMaterial;
  44059. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  44060. console.error(
  44061. 'blur direction must be either latitudinal or longitudinal!' );
  44062. }
  44063. // Number of standard deviations at which to cut off the discrete approximation.
  44064. const STANDARD_DEVIATIONS = 3;
  44065. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  44066. const blurUniforms = blurMaterial.uniforms;
  44067. const pixels = this._sizeLods[ lodIn ] - 1;
  44068. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  44069. const sigmaPixels = sigmaRadians / radiansPerPixel;
  44070. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  44071. if ( samples > MAX_SAMPLES ) {
  44072. console.warn( `sigmaRadians, ${
  44073. sigmaRadians}, is too large and will clip, as it requested ${
  44074. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  44075. }
  44076. const weights = [];
  44077. let sum = 0;
  44078. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  44079. const x = i / sigmaPixels;
  44080. const weight = Math.exp( - x * x / 2 );
  44081. weights.push( weight );
  44082. if ( i === 0 ) {
  44083. sum += weight;
  44084. } else if ( i < samples ) {
  44085. sum += 2 * weight;
  44086. }
  44087. }
  44088. for ( let i = 0; i < weights.length; i ++ ) {
  44089. weights[ i ] = weights[ i ] / sum;
  44090. }
  44091. blurUniforms[ 'envMap' ].value = targetIn.texture;
  44092. blurUniforms[ 'samples' ].value = samples;
  44093. blurUniforms[ 'weights' ].value = weights;
  44094. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  44095. if ( poleAxis ) {
  44096. blurUniforms[ 'poleAxis' ].value = poleAxis;
  44097. }
  44098. const { _lodMax } = this;
  44099. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  44100. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  44101. const outputSize = this._sizeLods[ lodOut ];
  44102. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  44103. const y = 4 * ( this._cubeSize - outputSize );
  44104. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  44105. renderer.setRenderTarget( targetOut );
  44106. renderer.render( blurMesh, _flatCamera );
  44107. }
  44108. }
  44109. function _createPlanes( lodMax ) {
  44110. const lodPlanes = [];
  44111. const sizeLods = [];
  44112. const sigmas = [];
  44113. let lod = lodMax;
  44114. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  44115. for ( let i = 0; i < totalLods; i ++ ) {
  44116. const sizeLod = Math.pow( 2, lod );
  44117. sizeLods.push( sizeLod );
  44118. let sigma = 1.0 / sizeLod;
  44119. if ( i > lodMax - LOD_MIN ) {
  44120. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  44121. } else if ( i === 0 ) {
  44122. sigma = 0;
  44123. }
  44124. sigmas.push( sigma );
  44125. const texelSize = 1.0 / ( sizeLod - 2 );
  44126. const min = - texelSize;
  44127. const max = 1 + texelSize;
  44128. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  44129. const cubeFaces = 6;
  44130. const vertices = 6;
  44131. const positionSize = 3;
  44132. const uvSize = 2;
  44133. const faceIndexSize = 1;
  44134. const position = new Float32Array( positionSize * vertices * cubeFaces );
  44135. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  44136. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  44137. for ( let face = 0; face < cubeFaces; face ++ ) {
  44138. const x = ( face % 3 ) * 2 / 3 - 1;
  44139. const y = face > 2 ? 0 : -1;
  44140. const coordinates = [
  44141. x, y, 0,
  44142. x + 2 / 3, y, 0,
  44143. x + 2 / 3, y + 1, 0,
  44144. x, y, 0,
  44145. x + 2 / 3, y + 1, 0,
  44146. x, y + 1, 0
  44147. ];
  44148. position.set( coordinates, positionSize * vertices * face );
  44149. uv.set( uv1, uvSize * vertices * face );
  44150. const fill = [ face, face, face, face, face, face ];
  44151. faceIndex.set( fill, faceIndexSize * vertices * face );
  44152. }
  44153. const planes = new BufferGeometry();
  44154. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  44155. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  44156. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  44157. lodPlanes.push( planes );
  44158. if ( lod > LOD_MIN ) {
  44159. lod --;
  44160. }
  44161. }
  44162. return { lodPlanes, sizeLods, sigmas };
  44163. }
  44164. function _createRenderTarget( width, height, params ) {
  44165. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  44166. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  44167. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  44168. cubeUVRenderTarget.scissorTest = true;
  44169. return cubeUVRenderTarget;
  44170. }
  44171. function _setViewport( target, x, y, width, height ) {
  44172. target.viewport.set( x, y, width, height );
  44173. target.scissor.set( x, y, width, height );
  44174. }
  44175. function _getBlurShader( lodMax, width, height ) {
  44176. const weights = new Float32Array( MAX_SAMPLES );
  44177. const poleAxis = new Vector3( 0, 1, 0 );
  44178. const shaderMaterial = new ShaderMaterial( {
  44179. name: 'SphericalGaussianBlur',
  44180. defines: {
  44181. 'n': MAX_SAMPLES,
  44182. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  44183. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  44184. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  44185. },
  44186. uniforms: {
  44187. 'envMap': { value: null },
  44188. 'samples': { value: 1 },
  44189. 'weights': { value: weights },
  44190. 'latitudinal': { value: false },
  44191. 'dTheta': { value: 0 },
  44192. 'mipInt': { value: 0 },
  44193. 'poleAxis': { value: poleAxis }
  44194. },
  44195. vertexShader: _getCommonVertexShader(),
  44196. fragmentShader: /* glsl */`
  44197. precision mediump float;
  44198. precision mediump int;
  44199. varying vec3 vOutputDirection;
  44200. uniform sampler2D envMap;
  44201. uniform int samples;
  44202. uniform float weights[ n ];
  44203. uniform bool latitudinal;
  44204. uniform float dTheta;
  44205. uniform float mipInt;
  44206. uniform vec3 poleAxis;
  44207. #define ENVMAP_TYPE_CUBE_UV
  44208. #include <cube_uv_reflection_fragment>
  44209. vec3 getSample( float theta, vec3 axis ) {
  44210. float cosTheta = cos( theta );
  44211. // Rodrigues' axis-angle rotation
  44212. vec3 sampleDirection = vOutputDirection * cosTheta
  44213. + cross( axis, vOutputDirection ) * sin( theta )
  44214. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  44215. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  44216. }
  44217. void main() {
  44218. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  44219. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  44220. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  44221. }
  44222. axis = normalize( axis );
  44223. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  44224. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  44225. for ( int i = 1; i < n; i++ ) {
  44226. if ( i >= samples ) {
  44227. break;
  44228. }
  44229. float theta = dTheta * float( i );
  44230. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  44231. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  44232. }
  44233. }
  44234. `,
  44235. blending: NoBlending,
  44236. depthTest: false,
  44237. depthWrite: false
  44238. } );
  44239. return shaderMaterial;
  44240. }
  44241. function _getEquirectMaterial() {
  44242. return new ShaderMaterial( {
  44243. name: 'EquirectangularToCubeUV',
  44244. uniforms: {
  44245. 'envMap': { value: null }
  44246. },
  44247. vertexShader: _getCommonVertexShader(),
  44248. fragmentShader: /* glsl */`
  44249. precision mediump float;
  44250. precision mediump int;
  44251. varying vec3 vOutputDirection;
  44252. uniform sampler2D envMap;
  44253. #include <common>
  44254. void main() {
  44255. vec3 outputDirection = normalize( vOutputDirection );
  44256. vec2 uv = equirectUv( outputDirection );
  44257. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  44258. }
  44259. `,
  44260. blending: NoBlending,
  44261. depthTest: false,
  44262. depthWrite: false
  44263. } );
  44264. }
  44265. function _getCubemapMaterial() {
  44266. return new ShaderMaterial( {
  44267. name: 'CubemapToCubeUV',
  44268. uniforms: {
  44269. 'envMap': { value: null },
  44270. 'flipEnvMap': { value: -1 }
  44271. },
  44272. vertexShader: _getCommonVertexShader(),
  44273. fragmentShader: /* glsl */`
  44274. precision mediump float;
  44275. precision mediump int;
  44276. uniform float flipEnvMap;
  44277. varying vec3 vOutputDirection;
  44278. uniform samplerCube envMap;
  44279. void main() {
  44280. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  44281. }
  44282. `,
  44283. blending: NoBlending,
  44284. depthTest: false,
  44285. depthWrite: false
  44286. } );
  44287. }
  44288. function _getCommonVertexShader() {
  44289. return /* glsl */`
  44290. precision mediump float;
  44291. precision mediump int;
  44292. attribute float faceIndex;
  44293. varying vec3 vOutputDirection;
  44294. // RH coordinate system; PMREM face-indexing convention
  44295. vec3 getDirection( vec2 uv, float face ) {
  44296. uv = 2.0 * uv - 1.0;
  44297. vec3 direction = vec3( uv, 1.0 );
  44298. if ( face == 0.0 ) {
  44299. direction = direction.zyx; // ( 1, v, u ) pos x
  44300. } else if ( face == 1.0 ) {
  44301. direction = direction.xzy;
  44302. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  44303. } else if ( face == 2.0 ) {
  44304. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  44305. } else if ( face == 3.0 ) {
  44306. direction = direction.zyx;
  44307. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  44308. } else if ( face == 4.0 ) {
  44309. direction = direction.xzy;
  44310. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  44311. } else if ( face == 5.0 ) {
  44312. direction.z *= -1.0; // ( u, v, -1 ) neg z
  44313. }
  44314. return direction;
  44315. }
  44316. void main() {
  44317. vOutputDirection = getDirection( uv, faceIndex );
  44318. gl_Position = vec4( position, 1.0 );
  44319. }
  44320. `;
  44321. }
  44322. function WebGLCubeUVMaps( renderer ) {
  44323. let cubeUVmaps = new WeakMap();
  44324. let pmremGenerator = null;
  44325. function get( texture ) {
  44326. if ( texture && texture.isTexture ) {
  44327. const mapping = texture.mapping;
  44328. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  44329. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  44330. // equirect/cube map to cubeUV conversion
  44331. if ( isEquirectMap || isCubeMap ) {
  44332. let renderTarget = cubeUVmaps.get( texture );
  44333. const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0;
  44334. if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) {
  44335. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  44336. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  44337. renderTarget.texture.pmremVersion = texture.pmremVersion;
  44338. cubeUVmaps.set( texture, renderTarget );
  44339. return renderTarget.texture;
  44340. } else {
  44341. if ( renderTarget !== undefined ) {
  44342. return renderTarget.texture;
  44343. } else {
  44344. const image = texture.image;
  44345. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  44346. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  44347. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  44348. renderTarget.texture.pmremVersion = texture.pmremVersion;
  44349. cubeUVmaps.set( texture, renderTarget );
  44350. texture.addEventListener( 'dispose', onTextureDispose );
  44351. return renderTarget.texture;
  44352. } else {
  44353. // image not yet ready. try the conversion next frame
  44354. return null;
  44355. }
  44356. }
  44357. }
  44358. }
  44359. }
  44360. return texture;
  44361. }
  44362. function isCubeTextureComplete( image ) {
  44363. let count = 0;
  44364. const length = 6;
  44365. for ( let i = 0; i < length; i ++ ) {
  44366. if ( image[ i ] !== undefined ) count ++;
  44367. }
  44368. return count === length;
  44369. }
  44370. function onTextureDispose( event ) {
  44371. const texture = event.target;
  44372. texture.removeEventListener( 'dispose', onTextureDispose );
  44373. const cubemapUV = cubeUVmaps.get( texture );
  44374. if ( cubemapUV !== undefined ) {
  44375. cubeUVmaps.delete( texture );
  44376. cubemapUV.dispose();
  44377. }
  44378. }
  44379. function dispose() {
  44380. cubeUVmaps = new WeakMap();
  44381. if ( pmremGenerator !== null ) {
  44382. pmremGenerator.dispose();
  44383. pmremGenerator = null;
  44384. }
  44385. }
  44386. return {
  44387. get: get,
  44388. dispose: dispose
  44389. };
  44390. }
  44391. function WebGLExtensions( gl ) {
  44392. const extensions = {};
  44393. function getExtension( name ) {
  44394. if ( extensions[ name ] !== undefined ) {
  44395. return extensions[ name ];
  44396. }
  44397. let extension;
  44398. switch ( name ) {
  44399. case 'WEBGL_depth_texture':
  44400. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  44401. break;
  44402. case 'EXT_texture_filter_anisotropic':
  44403. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  44404. break;
  44405. case 'WEBGL_compressed_texture_s3tc':
  44406. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  44407. break;
  44408. case 'WEBGL_compressed_texture_pvrtc':
  44409. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  44410. break;
  44411. default:
  44412. extension = gl.getExtension( name );
  44413. }
  44414. extensions[ name ] = extension;
  44415. return extension;
  44416. }
  44417. return {
  44418. has: function ( name ) {
  44419. return getExtension( name ) !== null;
  44420. },
  44421. init: function () {
  44422. getExtension( 'EXT_color_buffer_float' );
  44423. getExtension( 'WEBGL_clip_cull_distance' );
  44424. getExtension( 'OES_texture_float_linear' );
  44425. getExtension( 'EXT_color_buffer_half_float' );
  44426. getExtension( 'WEBGL_multisampled_render_to_texture' );
  44427. getExtension( 'WEBGL_render_shared_exponent' );
  44428. },
  44429. get: function ( name ) {
  44430. const extension = getExtension( name );
  44431. if ( extension === null ) {
  44432. warnOnce( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  44433. }
  44434. return extension;
  44435. }
  44436. };
  44437. }
  44438. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  44439. const geometries = {};
  44440. const wireframeAttributes = new WeakMap();
  44441. function onGeometryDispose( event ) {
  44442. const geometry = event.target;
  44443. if ( geometry.index !== null ) {
  44444. attributes.remove( geometry.index );
  44445. }
  44446. for ( const name in geometry.attributes ) {
  44447. attributes.remove( geometry.attributes[ name ] );
  44448. }
  44449. geometry.removeEventListener( 'dispose', onGeometryDispose );
  44450. delete geometries[ geometry.id ];
  44451. const attribute = wireframeAttributes.get( geometry );
  44452. if ( attribute ) {
  44453. attributes.remove( attribute );
  44454. wireframeAttributes.delete( geometry );
  44455. }
  44456. bindingStates.releaseStatesOfGeometry( geometry );
  44457. if ( geometry.isInstancedBufferGeometry === true ) {
  44458. delete geometry._maxInstanceCount;
  44459. }
  44460. //
  44461. info.memory.geometries --;
  44462. }
  44463. function get( object, geometry ) {
  44464. if ( geometries[ geometry.id ] === true ) return geometry;
  44465. geometry.addEventListener( 'dispose', onGeometryDispose );
  44466. geometries[ geometry.id ] = true;
  44467. info.memory.geometries ++;
  44468. return geometry;
  44469. }
  44470. function update( geometry ) {
  44471. const geometryAttributes = geometry.attributes;
  44472. // Updating index buffer in VAO now. See WebGLBindingStates.
  44473. for ( const name in geometryAttributes ) {
  44474. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  44475. }
  44476. }
  44477. function updateWireframeAttribute( geometry ) {
  44478. const indices = [];
  44479. const geometryIndex = geometry.index;
  44480. const geometryPosition = geometry.attributes.position;
  44481. let version = 0;
  44482. if ( geometryIndex !== null ) {
  44483. const array = geometryIndex.array;
  44484. version = geometryIndex.version;
  44485. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  44486. const a = array[ i + 0 ];
  44487. const b = array[ i + 1 ];
  44488. const c = array[ i + 2 ];
  44489. indices.push( a, b, b, c, c, a );
  44490. }
  44491. } else if ( geometryPosition !== undefined ) {
  44492. const array = geometryPosition.array;
  44493. version = geometryPosition.version;
  44494. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  44495. const a = i + 0;
  44496. const b = i + 1;
  44497. const c = i + 2;
  44498. indices.push( a, b, b, c, c, a );
  44499. }
  44500. } else {
  44501. return;
  44502. }
  44503. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  44504. attribute.version = version;
  44505. // Updating index buffer in VAO now. See WebGLBindingStates
  44506. //
  44507. const previousAttribute = wireframeAttributes.get( geometry );
  44508. if ( previousAttribute ) attributes.remove( previousAttribute );
  44509. //
  44510. wireframeAttributes.set( geometry, attribute );
  44511. }
  44512. function getWireframeAttribute( geometry ) {
  44513. const currentAttribute = wireframeAttributes.get( geometry );
  44514. if ( currentAttribute ) {
  44515. const geometryIndex = geometry.index;
  44516. if ( geometryIndex !== null ) {
  44517. // if the attribute is obsolete, create a new one
  44518. if ( currentAttribute.version < geometryIndex.version ) {
  44519. updateWireframeAttribute( geometry );
  44520. }
  44521. }
  44522. } else {
  44523. updateWireframeAttribute( geometry );
  44524. }
  44525. return wireframeAttributes.get( geometry );
  44526. }
  44527. return {
  44528. get: get,
  44529. update: update,
  44530. getWireframeAttribute: getWireframeAttribute
  44531. };
  44532. }
  44533. function WebGLIndexedBufferRenderer( gl, extensions, info ) {
  44534. let mode;
  44535. function setMode( value ) {
  44536. mode = value;
  44537. }
  44538. let type, bytesPerElement;
  44539. function setIndex( value ) {
  44540. type = value.type;
  44541. bytesPerElement = value.bytesPerElement;
  44542. }
  44543. function render( start, count ) {
  44544. gl.drawElements( mode, count, type, start * bytesPerElement );
  44545. info.update( count, mode, 1 );
  44546. }
  44547. function renderInstances( start, count, primcount ) {
  44548. if ( primcount === 0 ) return;
  44549. gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount );
  44550. info.update( count, mode, primcount );
  44551. }
  44552. function renderMultiDraw( starts, counts, drawCount ) {
  44553. if ( drawCount === 0 ) return;
  44554. const extension = extensions.get( 'WEBGL_multi_draw' );
  44555. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  44556. let elementCount = 0;
  44557. for ( let i = 0; i < drawCount; i ++ ) {
  44558. elementCount += counts[ i ];
  44559. }
  44560. info.update( elementCount, mode, 1 );
  44561. }
  44562. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  44563. if ( drawCount === 0 ) return;
  44564. const extension = extensions.get( 'WEBGL_multi_draw' );
  44565. if ( extension === null ) {
  44566. for ( let i = 0; i < starts.length; i ++ ) {
  44567. renderInstances( starts[ i ] / bytesPerElement, counts[ i ], primcount[ i ] );
  44568. }
  44569. } else {
  44570. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, type, starts, 0, primcount, 0, drawCount );
  44571. let elementCount = 0;
  44572. for ( let i = 0; i < drawCount; i ++ ) {
  44573. elementCount += counts[ i ] * primcount[ i ];
  44574. }
  44575. info.update( elementCount, mode, 1 );
  44576. }
  44577. }
  44578. //
  44579. this.setMode = setMode;
  44580. this.setIndex = setIndex;
  44581. this.render = render;
  44582. this.renderInstances = renderInstances;
  44583. this.renderMultiDraw = renderMultiDraw;
  44584. this.renderMultiDrawInstances = renderMultiDrawInstances;
  44585. }
  44586. function WebGLInfo( gl ) {
  44587. const memory = {
  44588. geometries: 0,
  44589. textures: 0
  44590. };
  44591. const render = {
  44592. frame: 0,
  44593. calls: 0,
  44594. triangles: 0,
  44595. points: 0,
  44596. lines: 0
  44597. };
  44598. function update( count, mode, instanceCount ) {
  44599. render.calls ++;
  44600. switch ( mode ) {
  44601. case gl.TRIANGLES:
  44602. render.triangles += instanceCount * ( count / 3 );
  44603. break;
  44604. case gl.LINES:
  44605. render.lines += instanceCount * ( count / 2 );
  44606. break;
  44607. case gl.LINE_STRIP:
  44608. render.lines += instanceCount * ( count - 1 );
  44609. break;
  44610. case gl.LINE_LOOP:
  44611. render.lines += instanceCount * count;
  44612. break;
  44613. case gl.POINTS:
  44614. render.points += instanceCount * count;
  44615. break;
  44616. default:
  44617. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  44618. break;
  44619. }
  44620. }
  44621. function reset() {
  44622. render.calls = 0;
  44623. render.triangles = 0;
  44624. render.points = 0;
  44625. render.lines = 0;
  44626. }
  44627. return {
  44628. memory: memory,
  44629. render: render,
  44630. programs: null,
  44631. autoReset: true,
  44632. reset: reset,
  44633. update: update
  44634. };
  44635. }
  44636. function WebGLMorphtargets( gl, capabilities, textures ) {
  44637. const morphTextures = new WeakMap();
  44638. const morph = new Vector4();
  44639. function update( object, geometry, program ) {
  44640. const objectInfluences = object.morphTargetInfluences;
  44641. // the following encodes morph targets into an array of data textures. Each layer represents a single morph target.
  44642. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  44643. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  44644. let entry = morphTextures.get( geometry );
  44645. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  44646. if ( entry !== undefined ) entry.texture.dispose();
  44647. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  44648. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  44649. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  44650. const morphTargets = geometry.morphAttributes.position || [];
  44651. const morphNormals = geometry.morphAttributes.normal || [];
  44652. const morphColors = geometry.morphAttributes.color || [];
  44653. let vertexDataCount = 0;
  44654. if ( hasMorphPosition === true ) vertexDataCount = 1;
  44655. if ( hasMorphNormals === true ) vertexDataCount = 2;
  44656. if ( hasMorphColors === true ) vertexDataCount = 3;
  44657. let width = geometry.attributes.position.count * vertexDataCount;
  44658. let height = 1;
  44659. if ( width > capabilities.maxTextureSize ) {
  44660. height = Math.ceil( width / capabilities.maxTextureSize );
  44661. width = capabilities.maxTextureSize;
  44662. }
  44663. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  44664. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  44665. texture.type = FloatType;
  44666. texture.needsUpdate = true;
  44667. // fill buffer
  44668. const vertexDataStride = vertexDataCount * 4;
  44669. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  44670. const morphTarget = morphTargets[ i ];
  44671. const morphNormal = morphNormals[ i ];
  44672. const morphColor = morphColors[ i ];
  44673. const offset = width * height * 4 * i;
  44674. for ( let j = 0; j < morphTarget.count; j ++ ) {
  44675. const stride = j * vertexDataStride;
  44676. if ( hasMorphPosition === true ) {
  44677. morph.fromBufferAttribute( morphTarget, j );
  44678. buffer[ offset + stride + 0 ] = morph.x;
  44679. buffer[ offset + stride + 1 ] = morph.y;
  44680. buffer[ offset + stride + 2 ] = morph.z;
  44681. buffer[ offset + stride + 3 ] = 0;
  44682. }
  44683. if ( hasMorphNormals === true ) {
  44684. morph.fromBufferAttribute( morphNormal, j );
  44685. buffer[ offset + stride + 4 ] = morph.x;
  44686. buffer[ offset + stride + 5 ] = morph.y;
  44687. buffer[ offset + stride + 6 ] = morph.z;
  44688. buffer[ offset + stride + 7 ] = 0;
  44689. }
  44690. if ( hasMorphColors === true ) {
  44691. morph.fromBufferAttribute( morphColor, j );
  44692. buffer[ offset + stride + 8 ] = morph.x;
  44693. buffer[ offset + stride + 9 ] = morph.y;
  44694. buffer[ offset + stride + 10 ] = morph.z;
  44695. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  44696. }
  44697. }
  44698. }
  44699. entry = {
  44700. count: morphTargetsCount,
  44701. texture: texture,
  44702. size: new Vector2( width, height )
  44703. };
  44704. morphTextures.set( geometry, entry );
  44705. function disposeTexture() {
  44706. texture.dispose();
  44707. morphTextures.delete( geometry );
  44708. geometry.removeEventListener( 'dispose', disposeTexture );
  44709. }
  44710. geometry.addEventListener( 'dispose', disposeTexture );
  44711. }
  44712. //
  44713. if ( object.isInstancedMesh === true && object.morphTexture !== null ) {
  44714. program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures );
  44715. } else {
  44716. let morphInfluencesSum = 0;
  44717. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  44718. morphInfluencesSum += objectInfluences[ i ];
  44719. }
  44720. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  44721. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  44722. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  44723. }
  44724. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  44725. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  44726. }
  44727. return {
  44728. update: update
  44729. };
  44730. }
  44731. function WebGLObjects( gl, geometries, attributes, info ) {
  44732. let updateMap = new WeakMap();
  44733. function update( object ) {
  44734. const frame = info.render.frame;
  44735. const geometry = object.geometry;
  44736. const buffergeometry = geometries.get( object, geometry );
  44737. // Update once per frame
  44738. if ( updateMap.get( buffergeometry ) !== frame ) {
  44739. geometries.update( buffergeometry );
  44740. updateMap.set( buffergeometry, frame );
  44741. }
  44742. if ( object.isInstancedMesh ) {
  44743. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  44744. object.addEventListener( 'dispose', onInstancedMeshDispose );
  44745. }
  44746. if ( updateMap.get( object ) !== frame ) {
  44747. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  44748. if ( object.instanceColor !== null ) {
  44749. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  44750. }
  44751. updateMap.set( object, frame );
  44752. }
  44753. }
  44754. if ( object.isSkinnedMesh ) {
  44755. const skeleton = object.skeleton;
  44756. if ( updateMap.get( skeleton ) !== frame ) {
  44757. skeleton.update();
  44758. updateMap.set( skeleton, frame );
  44759. }
  44760. }
  44761. return buffergeometry;
  44762. }
  44763. function dispose() {
  44764. updateMap = new WeakMap();
  44765. }
  44766. function onInstancedMeshDispose( event ) {
  44767. const instancedMesh = event.target;
  44768. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  44769. attributes.remove( instancedMesh.instanceMatrix );
  44770. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  44771. }
  44772. return {
  44773. update: update,
  44774. dispose: dispose
  44775. };
  44776. }
  44777. /**
  44778. * Uniforms of a program.
  44779. * Those form a tree structure with a special top-level container for the root,
  44780. * which you get by calling 'new WebGLUniforms( gl, program )'.
  44781. *
  44782. *
  44783. * Properties of inner nodes including the top-level container:
  44784. *
  44785. * .seq - array of nested uniforms
  44786. * .map - nested uniforms by name
  44787. *
  44788. *
  44789. * Methods of all nodes except the top-level container:
  44790. *
  44791. * .setValue( gl, value, [textures] )
  44792. *
  44793. * uploads a uniform value(s)
  44794. * the 'textures' parameter is needed for sampler uniforms
  44795. *
  44796. *
  44797. * Static methods of the top-level container (textures factorizations):
  44798. *
  44799. * .upload( gl, seq, values, textures )
  44800. *
  44801. * sets uniforms in 'seq' to 'values[id].value'
  44802. *
  44803. * .seqWithValue( seq, values ) : filteredSeq
  44804. *
  44805. * filters 'seq' entries with corresponding entry in values
  44806. *
  44807. *
  44808. * Methods of the top-level container (textures factorizations):
  44809. *
  44810. * .setValue( gl, name, value, textures )
  44811. *
  44812. * sets uniform with name 'name' to 'value'
  44813. *
  44814. * .setOptional( gl, obj, prop )
  44815. *
  44816. * like .set for an optional property of the object
  44817. *
  44818. */
  44819. const emptyTexture = /*@__PURE__*/ new Texture();
  44820. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  44821. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  44822. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  44823. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  44824. // --- Utilities ---
  44825. // Array Caches (provide typed arrays for temporary by size)
  44826. const arrayCacheF32 = [];
  44827. const arrayCacheI32 = [];
  44828. // Float32Array caches used for uploading Matrix uniforms
  44829. const mat4array = new Float32Array( 16 );
  44830. const mat3array = new Float32Array( 9 );
  44831. const mat2array = new Float32Array( 4 );
  44832. // Flattening for arrays of vectors and matrices
  44833. function flatten( array, nBlocks, blockSize ) {
  44834. const firstElem = array[ 0 ];
  44835. if ( firstElem <= 0 || firstElem > 0 ) return array;
  44836. // unoptimized: ! isNaN( firstElem )
  44837. // see http://jacksondunstan.com/articles/983
  44838. const n = nBlocks * blockSize;
  44839. let r = arrayCacheF32[ n ];
  44840. if ( r === undefined ) {
  44841. r = new Float32Array( n );
  44842. arrayCacheF32[ n ] = r;
  44843. }
  44844. if ( nBlocks !== 0 ) {
  44845. firstElem.toArray( r, 0 );
  44846. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  44847. offset += blockSize;
  44848. array[ i ].toArray( r, offset );
  44849. }
  44850. }
  44851. return r;
  44852. }
  44853. function arraysEqual( a, b ) {
  44854. if ( a.length !== b.length ) return false;
  44855. for ( let i = 0, l = a.length; i < l; i ++ ) {
  44856. if ( a[ i ] !== b[ i ] ) return false;
  44857. }
  44858. return true;
  44859. }
  44860. function copyArray( a, b ) {
  44861. for ( let i = 0, l = b.length; i < l; i ++ ) {
  44862. a[ i ] = b[ i ];
  44863. }
  44864. }
  44865. // Texture unit allocation
  44866. function allocTexUnits( textures, n ) {
  44867. let r = arrayCacheI32[ n ];
  44868. if ( r === undefined ) {
  44869. r = new Int32Array( n );
  44870. arrayCacheI32[ n ] = r;
  44871. }
  44872. for ( let i = 0; i !== n; ++ i ) {
  44873. r[ i ] = textures.allocateTextureUnit();
  44874. }
  44875. return r;
  44876. }
  44877. // --- Setters ---
  44878. // Note: Defining these methods externally, because they come in a bunch
  44879. // and this way their names minify.
  44880. // Single scalar
  44881. function setValueV1f( gl, v ) {
  44882. const cache = this.cache;
  44883. if ( cache[ 0 ] === v ) return;
  44884. gl.uniform1f( this.addr, v );
  44885. cache[ 0 ] = v;
  44886. }
  44887. // Single float vector (from flat array or THREE.VectorN)
  44888. function setValueV2f( gl, v ) {
  44889. const cache = this.cache;
  44890. if ( v.x !== undefined ) {
  44891. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  44892. gl.uniform2f( this.addr, v.x, v.y );
  44893. cache[ 0 ] = v.x;
  44894. cache[ 1 ] = v.y;
  44895. }
  44896. } else {
  44897. if ( arraysEqual( cache, v ) ) return;
  44898. gl.uniform2fv( this.addr, v );
  44899. copyArray( cache, v );
  44900. }
  44901. }
  44902. function setValueV3f( gl, v ) {
  44903. const cache = this.cache;
  44904. if ( v.x !== undefined ) {
  44905. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  44906. gl.uniform3f( this.addr, v.x, v.y, v.z );
  44907. cache[ 0 ] = v.x;
  44908. cache[ 1 ] = v.y;
  44909. cache[ 2 ] = v.z;
  44910. }
  44911. } else if ( v.r !== undefined ) {
  44912. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  44913. gl.uniform3f( this.addr, v.r, v.g, v.b );
  44914. cache[ 0 ] = v.r;
  44915. cache[ 1 ] = v.g;
  44916. cache[ 2 ] = v.b;
  44917. }
  44918. } else {
  44919. if ( arraysEqual( cache, v ) ) return;
  44920. gl.uniform3fv( this.addr, v );
  44921. copyArray( cache, v );
  44922. }
  44923. }
  44924. function setValueV4f( gl, v ) {
  44925. const cache = this.cache;
  44926. if ( v.x !== undefined ) {
  44927. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  44928. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  44929. cache[ 0 ] = v.x;
  44930. cache[ 1 ] = v.y;
  44931. cache[ 2 ] = v.z;
  44932. cache[ 3 ] = v.w;
  44933. }
  44934. } else {
  44935. if ( arraysEqual( cache, v ) ) return;
  44936. gl.uniform4fv( this.addr, v );
  44937. copyArray( cache, v );
  44938. }
  44939. }
  44940. // Single matrix (from flat array or THREE.MatrixN)
  44941. function setValueM2( gl, v ) {
  44942. const cache = this.cache;
  44943. const elements = v.elements;
  44944. if ( elements === undefined ) {
  44945. if ( arraysEqual( cache, v ) ) return;
  44946. gl.uniformMatrix2fv( this.addr, false, v );
  44947. copyArray( cache, v );
  44948. } else {
  44949. if ( arraysEqual( cache, elements ) ) return;
  44950. mat2array.set( elements );
  44951. gl.uniformMatrix2fv( this.addr, false, mat2array );
  44952. copyArray( cache, elements );
  44953. }
  44954. }
  44955. function setValueM3( gl, v ) {
  44956. const cache = this.cache;
  44957. const elements = v.elements;
  44958. if ( elements === undefined ) {
  44959. if ( arraysEqual( cache, v ) ) return;
  44960. gl.uniformMatrix3fv( this.addr, false, v );
  44961. copyArray( cache, v );
  44962. } else {
  44963. if ( arraysEqual( cache, elements ) ) return;
  44964. mat3array.set( elements );
  44965. gl.uniformMatrix3fv( this.addr, false, mat3array );
  44966. copyArray( cache, elements );
  44967. }
  44968. }
  44969. function setValueM4( gl, v ) {
  44970. const cache = this.cache;
  44971. const elements = v.elements;
  44972. if ( elements === undefined ) {
  44973. if ( arraysEqual( cache, v ) ) return;
  44974. gl.uniformMatrix4fv( this.addr, false, v );
  44975. copyArray( cache, v );
  44976. } else {
  44977. if ( arraysEqual( cache, elements ) ) return;
  44978. mat4array.set( elements );
  44979. gl.uniformMatrix4fv( this.addr, false, mat4array );
  44980. copyArray( cache, elements );
  44981. }
  44982. }
  44983. // Single integer / boolean
  44984. function setValueV1i( gl, v ) {
  44985. const cache = this.cache;
  44986. if ( cache[ 0 ] === v ) return;
  44987. gl.uniform1i( this.addr, v );
  44988. cache[ 0 ] = v;
  44989. }
  44990. // Single integer / boolean vector (from flat array or THREE.VectorN)
  44991. function setValueV2i( gl, v ) {
  44992. const cache = this.cache;
  44993. if ( v.x !== undefined ) {
  44994. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  44995. gl.uniform2i( this.addr, v.x, v.y );
  44996. cache[ 0 ] = v.x;
  44997. cache[ 1 ] = v.y;
  44998. }
  44999. } else {
  45000. if ( arraysEqual( cache, v ) ) return;
  45001. gl.uniform2iv( this.addr, v );
  45002. copyArray( cache, v );
  45003. }
  45004. }
  45005. function setValueV3i( gl, v ) {
  45006. const cache = this.cache;
  45007. if ( v.x !== undefined ) {
  45008. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  45009. gl.uniform3i( this.addr, v.x, v.y, v.z );
  45010. cache[ 0 ] = v.x;
  45011. cache[ 1 ] = v.y;
  45012. cache[ 2 ] = v.z;
  45013. }
  45014. } else {
  45015. if ( arraysEqual( cache, v ) ) return;
  45016. gl.uniform3iv( this.addr, v );
  45017. copyArray( cache, v );
  45018. }
  45019. }
  45020. function setValueV4i( gl, v ) {
  45021. const cache = this.cache;
  45022. if ( v.x !== undefined ) {
  45023. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  45024. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  45025. cache[ 0 ] = v.x;
  45026. cache[ 1 ] = v.y;
  45027. cache[ 2 ] = v.z;
  45028. cache[ 3 ] = v.w;
  45029. }
  45030. } else {
  45031. if ( arraysEqual( cache, v ) ) return;
  45032. gl.uniform4iv( this.addr, v );
  45033. copyArray( cache, v );
  45034. }
  45035. }
  45036. // Single unsigned integer
  45037. function setValueV1ui( gl, v ) {
  45038. const cache = this.cache;
  45039. if ( cache[ 0 ] === v ) return;
  45040. gl.uniform1ui( this.addr, v );
  45041. cache[ 0 ] = v;
  45042. }
  45043. // Single unsigned integer vector (from flat array or THREE.VectorN)
  45044. function setValueV2ui( gl, v ) {
  45045. const cache = this.cache;
  45046. if ( v.x !== undefined ) {
  45047. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  45048. gl.uniform2ui( this.addr, v.x, v.y );
  45049. cache[ 0 ] = v.x;
  45050. cache[ 1 ] = v.y;
  45051. }
  45052. } else {
  45053. if ( arraysEqual( cache, v ) ) return;
  45054. gl.uniform2uiv( this.addr, v );
  45055. copyArray( cache, v );
  45056. }
  45057. }
  45058. function setValueV3ui( gl, v ) {
  45059. const cache = this.cache;
  45060. if ( v.x !== undefined ) {
  45061. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  45062. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  45063. cache[ 0 ] = v.x;
  45064. cache[ 1 ] = v.y;
  45065. cache[ 2 ] = v.z;
  45066. }
  45067. } else {
  45068. if ( arraysEqual( cache, v ) ) return;
  45069. gl.uniform3uiv( this.addr, v );
  45070. copyArray( cache, v );
  45071. }
  45072. }
  45073. function setValueV4ui( gl, v ) {
  45074. const cache = this.cache;
  45075. if ( v.x !== undefined ) {
  45076. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  45077. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  45078. cache[ 0 ] = v.x;
  45079. cache[ 1 ] = v.y;
  45080. cache[ 2 ] = v.z;
  45081. cache[ 3 ] = v.w;
  45082. }
  45083. } else {
  45084. if ( arraysEqual( cache, v ) ) return;
  45085. gl.uniform4uiv( this.addr, v );
  45086. copyArray( cache, v );
  45087. }
  45088. }
  45089. // Single texture (2D / Cube)
  45090. function setValueT1( gl, v, textures ) {
  45091. const cache = this.cache;
  45092. const unit = textures.allocateTextureUnit();
  45093. if ( cache[ 0 ] !== unit ) {
  45094. gl.uniform1i( this.addr, unit );
  45095. cache[ 0 ] = unit;
  45096. }
  45097. let emptyTexture2D;
  45098. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  45099. emptyShadowTexture.compareFunction = LessEqualCompare; // #28670
  45100. emptyTexture2D = emptyShadowTexture;
  45101. } else {
  45102. emptyTexture2D = emptyTexture;
  45103. }
  45104. textures.setTexture2D( v || emptyTexture2D, unit );
  45105. }
  45106. function setValueT3D1( gl, v, textures ) {
  45107. const cache = this.cache;
  45108. const unit = textures.allocateTextureUnit();
  45109. if ( cache[ 0 ] !== unit ) {
  45110. gl.uniform1i( this.addr, unit );
  45111. cache[ 0 ] = unit;
  45112. }
  45113. textures.setTexture3D( v || empty3dTexture, unit );
  45114. }
  45115. function setValueT6( gl, v, textures ) {
  45116. const cache = this.cache;
  45117. const unit = textures.allocateTextureUnit();
  45118. if ( cache[ 0 ] !== unit ) {
  45119. gl.uniform1i( this.addr, unit );
  45120. cache[ 0 ] = unit;
  45121. }
  45122. textures.setTextureCube( v || emptyCubeTexture, unit );
  45123. }
  45124. function setValueT2DArray1( gl, v, textures ) {
  45125. const cache = this.cache;
  45126. const unit = textures.allocateTextureUnit();
  45127. if ( cache[ 0 ] !== unit ) {
  45128. gl.uniform1i( this.addr, unit );
  45129. cache[ 0 ] = unit;
  45130. }
  45131. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  45132. }
  45133. // Helper to pick the right setter for the singular case
  45134. function getSingularSetter( type ) {
  45135. switch ( type ) {
  45136. case 0x1406: return setValueV1f; // FLOAT
  45137. case 0x8b50: return setValueV2f; // _VEC2
  45138. case 0x8b51: return setValueV3f; // _VEC3
  45139. case 0x8b52: return setValueV4f; // _VEC4
  45140. case 0x8b5a: return setValueM2; // _MAT2
  45141. case 0x8b5b: return setValueM3; // _MAT3
  45142. case 0x8b5c: return setValueM4; // _MAT4
  45143. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  45144. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  45145. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  45146. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  45147. case 0x1405: return setValueV1ui; // UINT
  45148. case 0x8dc6: return setValueV2ui; // _VEC2
  45149. case 0x8dc7: return setValueV3ui; // _VEC3
  45150. case 0x8dc8: return setValueV4ui; // _VEC4
  45151. case 0x8b5e: // SAMPLER_2D
  45152. case 0x8d66: // SAMPLER_EXTERNAL_OES
  45153. case 0x8dca: // INT_SAMPLER_2D
  45154. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  45155. case 0x8b62: // SAMPLER_2D_SHADOW
  45156. return setValueT1;
  45157. case 0x8b5f: // SAMPLER_3D
  45158. case 0x8dcb: // INT_SAMPLER_3D
  45159. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  45160. return setValueT3D1;
  45161. case 0x8b60: // SAMPLER_CUBE
  45162. case 0x8dcc: // INT_SAMPLER_CUBE
  45163. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  45164. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  45165. return setValueT6;
  45166. case 0x8dc1: // SAMPLER_2D_ARRAY
  45167. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  45168. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  45169. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  45170. return setValueT2DArray1;
  45171. }
  45172. }
  45173. // Array of scalars
  45174. function setValueV1fArray( gl, v ) {
  45175. gl.uniform1fv( this.addr, v );
  45176. }
  45177. // Array of vectors (from flat array or array of THREE.VectorN)
  45178. function setValueV2fArray( gl, v ) {
  45179. const data = flatten( v, this.size, 2 );
  45180. gl.uniform2fv( this.addr, data );
  45181. }
  45182. function setValueV3fArray( gl, v ) {
  45183. const data = flatten( v, this.size, 3 );
  45184. gl.uniform3fv( this.addr, data );
  45185. }
  45186. function setValueV4fArray( gl, v ) {
  45187. const data = flatten( v, this.size, 4 );
  45188. gl.uniform4fv( this.addr, data );
  45189. }
  45190. // Array of matrices (from flat array or array of THREE.MatrixN)
  45191. function setValueM2Array( gl, v ) {
  45192. const data = flatten( v, this.size, 4 );
  45193. gl.uniformMatrix2fv( this.addr, false, data );
  45194. }
  45195. function setValueM3Array( gl, v ) {
  45196. const data = flatten( v, this.size, 9 );
  45197. gl.uniformMatrix3fv( this.addr, false, data );
  45198. }
  45199. function setValueM4Array( gl, v ) {
  45200. const data = flatten( v, this.size, 16 );
  45201. gl.uniformMatrix4fv( this.addr, false, data );
  45202. }
  45203. // Array of integer / boolean
  45204. function setValueV1iArray( gl, v ) {
  45205. gl.uniform1iv( this.addr, v );
  45206. }
  45207. // Array of integer / boolean vectors (from flat array)
  45208. function setValueV2iArray( gl, v ) {
  45209. gl.uniform2iv( this.addr, v );
  45210. }
  45211. function setValueV3iArray( gl, v ) {
  45212. gl.uniform3iv( this.addr, v );
  45213. }
  45214. function setValueV4iArray( gl, v ) {
  45215. gl.uniform4iv( this.addr, v );
  45216. }
  45217. // Array of unsigned integer
  45218. function setValueV1uiArray( gl, v ) {
  45219. gl.uniform1uiv( this.addr, v );
  45220. }
  45221. // Array of unsigned integer vectors (from flat array)
  45222. function setValueV2uiArray( gl, v ) {
  45223. gl.uniform2uiv( this.addr, v );
  45224. }
  45225. function setValueV3uiArray( gl, v ) {
  45226. gl.uniform3uiv( this.addr, v );
  45227. }
  45228. function setValueV4uiArray( gl, v ) {
  45229. gl.uniform4uiv( this.addr, v );
  45230. }
  45231. // Array of textures (2D / 3D / Cube / 2DArray)
  45232. function setValueT1Array( gl, v, textures ) {
  45233. const cache = this.cache;
  45234. const n = v.length;
  45235. const units = allocTexUnits( textures, n );
  45236. if ( ! arraysEqual( cache, units ) ) {
  45237. gl.uniform1iv( this.addr, units );
  45238. copyArray( cache, units );
  45239. }
  45240. for ( let i = 0; i !== n; ++ i ) {
  45241. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  45242. }
  45243. }
  45244. function setValueT3DArray( gl, v, textures ) {
  45245. const cache = this.cache;
  45246. const n = v.length;
  45247. const units = allocTexUnits( textures, n );
  45248. if ( ! arraysEqual( cache, units ) ) {
  45249. gl.uniform1iv( this.addr, units );
  45250. copyArray( cache, units );
  45251. }
  45252. for ( let i = 0; i !== n; ++ i ) {
  45253. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  45254. }
  45255. }
  45256. function setValueT6Array( gl, v, textures ) {
  45257. const cache = this.cache;
  45258. const n = v.length;
  45259. const units = allocTexUnits( textures, n );
  45260. if ( ! arraysEqual( cache, units ) ) {
  45261. gl.uniform1iv( this.addr, units );
  45262. copyArray( cache, units );
  45263. }
  45264. for ( let i = 0; i !== n; ++ i ) {
  45265. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  45266. }
  45267. }
  45268. function setValueT2DArrayArray( gl, v, textures ) {
  45269. const cache = this.cache;
  45270. const n = v.length;
  45271. const units = allocTexUnits( textures, n );
  45272. if ( ! arraysEqual( cache, units ) ) {
  45273. gl.uniform1iv( this.addr, units );
  45274. copyArray( cache, units );
  45275. }
  45276. for ( let i = 0; i !== n; ++ i ) {
  45277. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  45278. }
  45279. }
  45280. // Helper to pick the right setter for a pure (bottom-level) array
  45281. function getPureArraySetter( type ) {
  45282. switch ( type ) {
  45283. case 0x1406: return setValueV1fArray; // FLOAT
  45284. case 0x8b50: return setValueV2fArray; // _VEC2
  45285. case 0x8b51: return setValueV3fArray; // _VEC3
  45286. case 0x8b52: return setValueV4fArray; // _VEC4
  45287. case 0x8b5a: return setValueM2Array; // _MAT2
  45288. case 0x8b5b: return setValueM3Array; // _MAT3
  45289. case 0x8b5c: return setValueM4Array; // _MAT4
  45290. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  45291. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  45292. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  45293. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  45294. case 0x1405: return setValueV1uiArray; // UINT
  45295. case 0x8dc6: return setValueV2uiArray; // _VEC2
  45296. case 0x8dc7: return setValueV3uiArray; // _VEC3
  45297. case 0x8dc8: return setValueV4uiArray; // _VEC4
  45298. case 0x8b5e: // SAMPLER_2D
  45299. case 0x8d66: // SAMPLER_EXTERNAL_OES
  45300. case 0x8dca: // INT_SAMPLER_2D
  45301. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  45302. case 0x8b62: // SAMPLER_2D_SHADOW
  45303. return setValueT1Array;
  45304. case 0x8b5f: // SAMPLER_3D
  45305. case 0x8dcb: // INT_SAMPLER_3D
  45306. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  45307. return setValueT3DArray;
  45308. case 0x8b60: // SAMPLER_CUBE
  45309. case 0x8dcc: // INT_SAMPLER_CUBE
  45310. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  45311. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  45312. return setValueT6Array;
  45313. case 0x8dc1: // SAMPLER_2D_ARRAY
  45314. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  45315. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  45316. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  45317. return setValueT2DArrayArray;
  45318. }
  45319. }
  45320. // --- Uniform Classes ---
  45321. class SingleUniform {
  45322. constructor( id, activeInfo, addr ) {
  45323. this.id = id;
  45324. this.addr = addr;
  45325. this.cache = [];
  45326. this.type = activeInfo.type;
  45327. this.setValue = getSingularSetter( activeInfo.type );
  45328. // this.path = activeInfo.name; // DEBUG
  45329. }
  45330. }
  45331. class PureArrayUniform {
  45332. constructor( id, activeInfo, addr ) {
  45333. this.id = id;
  45334. this.addr = addr;
  45335. this.cache = [];
  45336. this.type = activeInfo.type;
  45337. this.size = activeInfo.size;
  45338. this.setValue = getPureArraySetter( activeInfo.type );
  45339. // this.path = activeInfo.name; // DEBUG
  45340. }
  45341. }
  45342. class StructuredUniform {
  45343. constructor( id ) {
  45344. this.id = id;
  45345. this.seq = [];
  45346. this.map = {};
  45347. }
  45348. setValue( gl, value, textures ) {
  45349. const seq = this.seq;
  45350. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  45351. const u = seq[ i ];
  45352. u.setValue( gl, value[ u.id ], textures );
  45353. }
  45354. }
  45355. }
  45356. // --- Top-level ---
  45357. // Parser - builds up the property tree from the path strings
  45358. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  45359. // extracts
  45360. // - the identifier (member name or array index)
  45361. // - followed by an optional right bracket (found when array index)
  45362. // - followed by an optional left bracket or dot (type of subscript)
  45363. //
  45364. // Note: These portions can be read in a non-overlapping fashion and
  45365. // allow straightforward parsing of the hierarchy that WebGL encodes
  45366. // in the uniform names.
  45367. function addUniform( container, uniformObject ) {
  45368. container.seq.push( uniformObject );
  45369. container.map[ uniformObject.id ] = uniformObject;
  45370. }
  45371. function parseUniform( activeInfo, addr, container ) {
  45372. const path = activeInfo.name,
  45373. pathLength = path.length;
  45374. // reset RegExp object, because of the early exit of a previous run
  45375. RePathPart.lastIndex = 0;
  45376. while ( true ) {
  45377. const match = RePathPart.exec( path ),
  45378. matchEnd = RePathPart.lastIndex;
  45379. let id = match[ 1 ];
  45380. const idIsIndex = match[ 2 ] === ']',
  45381. subscript = match[ 3 ];
  45382. if ( idIsIndex ) id = id | 0; // convert to integer
  45383. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  45384. // bare name or "pure" bottom-level array "[0]" suffix
  45385. addUniform( container, subscript === undefined ?
  45386. new SingleUniform( id, activeInfo, addr ) :
  45387. new PureArrayUniform( id, activeInfo, addr ) );
  45388. break;
  45389. } else {
  45390. // step into inner node / create it in case it doesn't exist
  45391. const map = container.map;
  45392. let next = map[ id ];
  45393. if ( next === undefined ) {
  45394. next = new StructuredUniform( id );
  45395. addUniform( container, next );
  45396. }
  45397. container = next;
  45398. }
  45399. }
  45400. }
  45401. // Root Container
  45402. class WebGLUniforms {
  45403. constructor( gl, program ) {
  45404. this.seq = [];
  45405. this.map = {};
  45406. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  45407. for ( let i = 0; i < n; ++ i ) {
  45408. const info = gl.getActiveUniform( program, i ),
  45409. addr = gl.getUniformLocation( program, info.name );
  45410. parseUniform( info, addr, this );
  45411. }
  45412. }
  45413. setValue( gl, name, value, textures ) {
  45414. const u = this.map[ name ];
  45415. if ( u !== undefined ) u.setValue( gl, value, textures );
  45416. }
  45417. setOptional( gl, object, name ) {
  45418. const v = object[ name ];
  45419. if ( v !== undefined ) this.setValue( gl, name, v );
  45420. }
  45421. static upload( gl, seq, values, textures ) {
  45422. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  45423. const u = seq[ i ],
  45424. v = values[ u.id ];
  45425. if ( v.needsUpdate !== false ) {
  45426. // note: always updating when .needsUpdate is undefined
  45427. u.setValue( gl, v.value, textures );
  45428. }
  45429. }
  45430. }
  45431. static seqWithValue( seq, values ) {
  45432. const r = [];
  45433. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  45434. const u = seq[ i ];
  45435. if ( u.id in values ) r.push( u );
  45436. }
  45437. return r;
  45438. }
  45439. }
  45440. function WebGLShader( gl, type, string ) {
  45441. const shader = gl.createShader( type );
  45442. gl.shaderSource( shader, string );
  45443. gl.compileShader( shader );
  45444. return shader;
  45445. }
  45446. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  45447. const COMPLETION_STATUS_KHR = 0x91B1;
  45448. let programIdCount = 0;
  45449. function handleSource( string, errorLine ) {
  45450. const lines = string.split( '\n' );
  45451. const lines2 = [];
  45452. const from = Math.max( errorLine - 6, 0 );
  45453. const to = Math.min( errorLine + 6, lines.length );
  45454. for ( let i = from; i < to; i ++ ) {
  45455. const line = i + 1;
  45456. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  45457. }
  45458. return lines2.join( '\n' );
  45459. }
  45460. const _m0 = /*@__PURE__*/ new Matrix3();
  45461. function getEncodingComponents( colorSpace ) {
  45462. ColorManagement._getMatrix( _m0, ColorManagement.workingColorSpace, colorSpace );
  45463. const encodingMatrix = `mat3( ${ _m0.elements.map( ( v ) => v.toFixed( 4 ) ) } )`;
  45464. switch ( ColorManagement.getTransfer( colorSpace ) ) {
  45465. case LinearTransfer:
  45466. return [ encodingMatrix, 'LinearTransferOETF' ];
  45467. case SRGBTransfer:
  45468. return [ encodingMatrix, 'sRGBTransferOETF' ];
  45469. default:
  45470. console.warn( 'THREE.WebGLProgram: Unsupported color space: ', colorSpace );
  45471. return [ encodingMatrix, 'LinearTransferOETF' ];
  45472. }
  45473. }
  45474. function getShaderErrors( gl, shader, type ) {
  45475. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  45476. const errors = gl.getShaderInfoLog( shader ).trim();
  45477. if ( status && errors === '' ) return '';
  45478. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  45479. if ( errorMatches ) {
  45480. // --enable-privileged-webgl-extension
  45481. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  45482. const errorLine = parseInt( errorMatches[ 1 ] );
  45483. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  45484. } else {
  45485. return errors;
  45486. }
  45487. }
  45488. function getTexelEncodingFunction( functionName, colorSpace ) {
  45489. const components = getEncodingComponents( colorSpace );
  45490. return [
  45491. `vec4 ${functionName}( vec4 value ) {`,
  45492. ` return ${components[ 1 ]}( vec4( value.rgb * ${components[ 0 ]}, value.a ) );`,
  45493. '}',
  45494. ].join( '\n' );
  45495. }
  45496. function getToneMappingFunction( functionName, toneMapping ) {
  45497. let toneMappingName;
  45498. switch ( toneMapping ) {
  45499. case LinearToneMapping:
  45500. toneMappingName = 'Linear';
  45501. break;
  45502. case ReinhardToneMapping:
  45503. toneMappingName = 'Reinhard';
  45504. break;
  45505. case CineonToneMapping:
  45506. toneMappingName = 'Cineon';
  45507. break;
  45508. case ACESFilmicToneMapping:
  45509. toneMappingName = 'ACESFilmic';
  45510. break;
  45511. case AgXToneMapping:
  45512. toneMappingName = 'AgX';
  45513. break;
  45514. case NeutralToneMapping:
  45515. toneMappingName = 'Neutral';
  45516. break;
  45517. case CustomToneMapping:
  45518. toneMappingName = 'Custom';
  45519. break;
  45520. default:
  45521. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  45522. toneMappingName = 'Linear';
  45523. }
  45524. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  45525. }
  45526. const _v0 = /*@__PURE__*/ new Vector3();
  45527. function getLuminanceFunction() {
  45528. ColorManagement.getLuminanceCoefficients( _v0 );
  45529. const r = _v0.x.toFixed( 4 );
  45530. const g = _v0.y.toFixed( 4 );
  45531. const b = _v0.z.toFixed( 4 );
  45532. return [
  45533. 'float luminance( const in vec3 rgb ) {',
  45534. ` const vec3 weights = vec3( ${ r }, ${ g }, ${ b } );`,
  45535. ' return dot( weights, rgb );',
  45536. '}'
  45537. ].join( '\n' );
  45538. }
  45539. function generateVertexExtensions( parameters ) {
  45540. const chunks = [
  45541. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '',
  45542. parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '',
  45543. ];
  45544. return chunks.filter( filterEmptyLine ).join( '\n' );
  45545. }
  45546. function generateDefines( defines ) {
  45547. const chunks = [];
  45548. for ( const name in defines ) {
  45549. const value = defines[ name ];
  45550. if ( value === false ) continue;
  45551. chunks.push( '#define ' + name + ' ' + value );
  45552. }
  45553. return chunks.join( '\n' );
  45554. }
  45555. function fetchAttributeLocations( gl, program ) {
  45556. const attributes = {};
  45557. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  45558. for ( let i = 0; i < n; i ++ ) {
  45559. const info = gl.getActiveAttrib( program, i );
  45560. const name = info.name;
  45561. let locationSize = 1;
  45562. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  45563. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  45564. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  45565. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  45566. attributes[ name ] = {
  45567. type: info.type,
  45568. location: gl.getAttribLocation( program, name ),
  45569. locationSize: locationSize
  45570. };
  45571. }
  45572. return attributes;
  45573. }
  45574. function filterEmptyLine( string ) {
  45575. return string !== '';
  45576. }
  45577. function replaceLightNums( string, parameters ) {
  45578. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  45579. return string
  45580. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  45581. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  45582. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  45583. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  45584. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  45585. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  45586. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  45587. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  45588. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  45589. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  45590. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  45591. }
  45592. function replaceClippingPlaneNums( string, parameters ) {
  45593. return string
  45594. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  45595. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  45596. }
  45597. // Resolve Includes
  45598. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  45599. function resolveIncludes( string ) {
  45600. return string.replace( includePattern, includeReplacer );
  45601. }
  45602. const shaderChunkMap = new Map();
  45603. function includeReplacer( match, include ) {
  45604. let string = ShaderChunk[ include ];
  45605. if ( string === undefined ) {
  45606. const newInclude = shaderChunkMap.get( include );
  45607. if ( newInclude !== undefined ) {
  45608. string = ShaderChunk[ newInclude ];
  45609. console.warn( 'THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  45610. } else {
  45611. throw new Error( 'Can not resolve #include <' + include + '>' );
  45612. }
  45613. }
  45614. return resolveIncludes( string );
  45615. }
  45616. // Unroll Loops
  45617. 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;
  45618. function unrollLoops( string ) {
  45619. return string.replace( unrollLoopPattern, loopReplacer );
  45620. }
  45621. function loopReplacer( match, start, end, snippet ) {
  45622. let string = '';
  45623. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  45624. string += snippet
  45625. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  45626. .replace( /UNROLLED_LOOP_INDEX/g, i );
  45627. }
  45628. return string;
  45629. }
  45630. //
  45631. function generatePrecision( parameters ) {
  45632. let precisionstring = `precision ${parameters.precision} float;
  45633. precision ${parameters.precision} int;
  45634. precision ${parameters.precision} sampler2D;
  45635. precision ${parameters.precision} samplerCube;
  45636. precision ${parameters.precision} sampler3D;
  45637. precision ${parameters.precision} sampler2DArray;
  45638. precision ${parameters.precision} sampler2DShadow;
  45639. precision ${parameters.precision} samplerCubeShadow;
  45640. precision ${parameters.precision} sampler2DArrayShadow;
  45641. precision ${parameters.precision} isampler2D;
  45642. precision ${parameters.precision} isampler3D;
  45643. precision ${parameters.precision} isamplerCube;
  45644. precision ${parameters.precision} isampler2DArray;
  45645. precision ${parameters.precision} usampler2D;
  45646. precision ${parameters.precision} usampler3D;
  45647. precision ${parameters.precision} usamplerCube;
  45648. precision ${parameters.precision} usampler2DArray;
  45649. `;
  45650. if ( parameters.precision === 'highp' ) {
  45651. precisionstring += '\n#define HIGH_PRECISION';
  45652. } else if ( parameters.precision === 'mediump' ) {
  45653. precisionstring += '\n#define MEDIUM_PRECISION';
  45654. } else if ( parameters.precision === 'lowp' ) {
  45655. precisionstring += '\n#define LOW_PRECISION';
  45656. }
  45657. return precisionstring;
  45658. }
  45659. function generateShadowMapTypeDefine( parameters ) {
  45660. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  45661. if ( parameters.shadowMapType === PCFShadowMap ) {
  45662. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  45663. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  45664. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  45665. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  45666. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  45667. }
  45668. return shadowMapTypeDefine;
  45669. }
  45670. function generateEnvMapTypeDefine( parameters ) {
  45671. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  45672. if ( parameters.envMap ) {
  45673. switch ( parameters.envMapMode ) {
  45674. case CubeReflectionMapping:
  45675. case CubeRefractionMapping:
  45676. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  45677. break;
  45678. case CubeUVReflectionMapping:
  45679. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  45680. break;
  45681. }
  45682. }
  45683. return envMapTypeDefine;
  45684. }
  45685. function generateEnvMapModeDefine( parameters ) {
  45686. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  45687. if ( parameters.envMap ) {
  45688. switch ( parameters.envMapMode ) {
  45689. case CubeRefractionMapping:
  45690. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  45691. break;
  45692. }
  45693. }
  45694. return envMapModeDefine;
  45695. }
  45696. function generateEnvMapBlendingDefine( parameters ) {
  45697. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  45698. if ( parameters.envMap ) {
  45699. switch ( parameters.combine ) {
  45700. case MultiplyOperation:
  45701. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  45702. break;
  45703. case MixOperation:
  45704. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  45705. break;
  45706. case AddOperation:
  45707. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  45708. break;
  45709. }
  45710. }
  45711. return envMapBlendingDefine;
  45712. }
  45713. function generateCubeUVSize( parameters ) {
  45714. const imageHeight = parameters.envMapCubeUVHeight;
  45715. if ( imageHeight === null ) return null;
  45716. const maxMip = Math.log2( imageHeight ) - 2;
  45717. const texelHeight = 1.0 / imageHeight;
  45718. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  45719. return { texelWidth, texelHeight, maxMip };
  45720. }
  45721. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  45722. // TODO Send this event to Three.js DevTools
  45723. // console.log( 'WebGLProgram', cacheKey );
  45724. const gl = renderer.getContext();
  45725. const defines = parameters.defines;
  45726. let vertexShader = parameters.vertexShader;
  45727. let fragmentShader = parameters.fragmentShader;
  45728. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  45729. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  45730. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  45731. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  45732. const envMapCubeUVSize = generateCubeUVSize( parameters );
  45733. const customVertexExtensions = generateVertexExtensions( parameters );
  45734. const customDefines = generateDefines( defines );
  45735. const program = gl.createProgram();
  45736. let prefixVertex, prefixFragment;
  45737. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  45738. if ( parameters.isRawShaderMaterial ) {
  45739. prefixVertex = [
  45740. '#define SHADER_TYPE ' + parameters.shaderType,
  45741. '#define SHADER_NAME ' + parameters.shaderName,
  45742. customDefines
  45743. ].filter( filterEmptyLine ).join( '\n' );
  45744. if ( prefixVertex.length > 0 ) {
  45745. prefixVertex += '\n';
  45746. }
  45747. prefixFragment = [
  45748. '#define SHADER_TYPE ' + parameters.shaderType,
  45749. '#define SHADER_NAME ' + parameters.shaderName,
  45750. customDefines
  45751. ].filter( filterEmptyLine ).join( '\n' );
  45752. if ( prefixFragment.length > 0 ) {
  45753. prefixFragment += '\n';
  45754. }
  45755. } else {
  45756. prefixVertex = [
  45757. generatePrecision( parameters ),
  45758. '#define SHADER_TYPE ' + parameters.shaderType,
  45759. '#define SHADER_NAME ' + parameters.shaderName,
  45760. customDefines,
  45761. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  45762. parameters.batching ? '#define USE_BATCHING' : '',
  45763. parameters.batchingColor ? '#define USE_BATCHING_COLOR' : '',
  45764. parameters.instancing ? '#define USE_INSTANCING' : '',
  45765. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  45766. parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '',
  45767. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  45768. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  45769. parameters.map ? '#define USE_MAP' : '',
  45770. parameters.envMap ? '#define USE_ENVMAP' : '',
  45771. parameters.envMap ? '#define ' + envMapModeDefine : '',
  45772. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  45773. parameters.aoMap ? '#define USE_AOMAP' : '',
  45774. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  45775. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  45776. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  45777. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  45778. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  45779. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  45780. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  45781. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  45782. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  45783. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  45784. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  45785. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  45786. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  45787. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  45788. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  45789. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  45790. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  45791. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  45792. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  45793. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  45794. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  45795. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  45796. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  45797. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  45798. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  45799. //
  45800. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  45801. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  45802. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  45803. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  45804. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  45805. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  45806. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  45807. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  45808. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  45809. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  45810. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  45811. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  45812. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  45813. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  45814. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  45815. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  45816. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  45817. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  45818. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  45819. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  45820. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  45821. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  45822. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  45823. //
  45824. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  45825. parameters.vertexColors ? '#define USE_COLOR' : '',
  45826. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  45827. parameters.vertexUv1s ? '#define USE_UV1' : '',
  45828. parameters.vertexUv2s ? '#define USE_UV2' : '',
  45829. parameters.vertexUv3s ? '#define USE_UV3' : '',
  45830. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  45831. parameters.flatShading ? '#define FLAT_SHADED' : '',
  45832. parameters.skinning ? '#define USE_SKINNING' : '',
  45833. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  45834. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  45835. ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '',
  45836. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  45837. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  45838. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  45839. parameters.flipSided ? '#define FLIP_SIDED' : '',
  45840. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  45841. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  45842. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  45843. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  45844. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  45845. parameters.reverseDepthBuffer ? '#define USE_REVERSEDEPTHBUF' : '',
  45846. 'uniform mat4 modelMatrix;',
  45847. 'uniform mat4 modelViewMatrix;',
  45848. 'uniform mat4 projectionMatrix;',
  45849. 'uniform mat4 viewMatrix;',
  45850. 'uniform mat3 normalMatrix;',
  45851. 'uniform vec3 cameraPosition;',
  45852. 'uniform bool isOrthographic;',
  45853. '#ifdef USE_INSTANCING',
  45854. ' attribute mat4 instanceMatrix;',
  45855. '#endif',
  45856. '#ifdef USE_INSTANCING_COLOR',
  45857. ' attribute vec3 instanceColor;',
  45858. '#endif',
  45859. '#ifdef USE_INSTANCING_MORPH',
  45860. ' uniform sampler2D morphTexture;',
  45861. '#endif',
  45862. 'attribute vec3 position;',
  45863. 'attribute vec3 normal;',
  45864. 'attribute vec2 uv;',
  45865. '#ifdef USE_UV1',
  45866. ' attribute vec2 uv1;',
  45867. '#endif',
  45868. '#ifdef USE_UV2',
  45869. ' attribute vec2 uv2;',
  45870. '#endif',
  45871. '#ifdef USE_UV3',
  45872. ' attribute vec2 uv3;',
  45873. '#endif',
  45874. '#ifdef USE_TANGENT',
  45875. ' attribute vec4 tangent;',
  45876. '#endif',
  45877. '#if defined( USE_COLOR_ALPHA )',
  45878. ' attribute vec4 color;',
  45879. '#elif defined( USE_COLOR )',
  45880. ' attribute vec3 color;',
  45881. '#endif',
  45882. '#ifdef USE_SKINNING',
  45883. ' attribute vec4 skinIndex;',
  45884. ' attribute vec4 skinWeight;',
  45885. '#endif',
  45886. '\n'
  45887. ].filter( filterEmptyLine ).join( '\n' );
  45888. prefixFragment = [
  45889. generatePrecision( parameters ),
  45890. '#define SHADER_TYPE ' + parameters.shaderType,
  45891. '#define SHADER_NAME ' + parameters.shaderName,
  45892. customDefines,
  45893. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  45894. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  45895. parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '',
  45896. parameters.map ? '#define USE_MAP' : '',
  45897. parameters.matcap ? '#define USE_MATCAP' : '',
  45898. parameters.envMap ? '#define USE_ENVMAP' : '',
  45899. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  45900. parameters.envMap ? '#define ' + envMapModeDefine : '',
  45901. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  45902. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  45903. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  45904. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  45905. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  45906. parameters.aoMap ? '#define USE_AOMAP' : '',
  45907. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  45908. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  45909. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  45910. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  45911. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  45912. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  45913. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  45914. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  45915. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  45916. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  45917. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  45918. parameters.dispersion ? '#define USE_DISPERSION' : '',
  45919. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  45920. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  45921. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  45922. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  45923. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  45924. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  45925. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  45926. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  45927. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  45928. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  45929. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  45930. parameters.sheen ? '#define USE_SHEEN' : '',
  45931. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  45932. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  45933. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  45934. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  45935. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  45936. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  45937. parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? '#define USE_COLOR' : '',
  45938. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  45939. parameters.vertexUv1s ? '#define USE_UV1' : '',
  45940. parameters.vertexUv2s ? '#define USE_UV2' : '',
  45941. parameters.vertexUv3s ? '#define USE_UV3' : '',
  45942. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  45943. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  45944. parameters.flatShading ? '#define FLAT_SHADED' : '',
  45945. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  45946. parameters.flipSided ? '#define FLIP_SIDED' : '',
  45947. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  45948. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  45949. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  45950. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  45951. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  45952. parameters.decodeVideoTextureEmissive ? '#define DECODE_VIDEO_TEXTURE_EMISSIVE' : '',
  45953. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  45954. parameters.reverseDepthBuffer ? '#define USE_REVERSEDEPTHBUF' : '',
  45955. 'uniform mat4 viewMatrix;',
  45956. 'uniform vec3 cameraPosition;',
  45957. 'uniform bool isOrthographic;',
  45958. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  45959. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  45960. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  45961. parameters.dithering ? '#define DITHERING' : '',
  45962. parameters.opaque ? '#define OPAQUE' : '',
  45963. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  45964. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  45965. getLuminanceFunction(),
  45966. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  45967. '\n'
  45968. ].filter( filterEmptyLine ).join( '\n' );
  45969. }
  45970. vertexShader = resolveIncludes( vertexShader );
  45971. vertexShader = replaceLightNums( vertexShader, parameters );
  45972. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  45973. fragmentShader = resolveIncludes( fragmentShader );
  45974. fragmentShader = replaceLightNums( fragmentShader, parameters );
  45975. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  45976. vertexShader = unrollLoops( vertexShader );
  45977. fragmentShader = unrollLoops( fragmentShader );
  45978. if ( parameters.isRawShaderMaterial !== true ) {
  45979. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  45980. versionString = '#version 300 es\n';
  45981. prefixVertex = [
  45982. customVertexExtensions,
  45983. '#define attribute in',
  45984. '#define varying out',
  45985. '#define texture2D texture'
  45986. ].join( '\n' ) + '\n' + prefixVertex;
  45987. prefixFragment = [
  45988. '#define varying in',
  45989. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  45990. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  45991. '#define gl_FragDepthEXT gl_FragDepth',
  45992. '#define texture2D texture',
  45993. '#define textureCube texture',
  45994. '#define texture2DProj textureProj',
  45995. '#define texture2DLodEXT textureLod',
  45996. '#define texture2DProjLodEXT textureProjLod',
  45997. '#define textureCubeLodEXT textureLod',
  45998. '#define texture2DGradEXT textureGrad',
  45999. '#define texture2DProjGradEXT textureProjGrad',
  46000. '#define textureCubeGradEXT textureGrad'
  46001. ].join( '\n' ) + '\n' + prefixFragment;
  46002. }
  46003. const vertexGlsl = versionString + prefixVertex + vertexShader;
  46004. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  46005. // console.log( '*VERTEX*', vertexGlsl );
  46006. // console.log( '*FRAGMENT*', fragmentGlsl );
  46007. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  46008. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  46009. gl.attachShader( program, glVertexShader );
  46010. gl.attachShader( program, glFragmentShader );
  46011. // Force a particular attribute to index 0.
  46012. if ( parameters.index0AttributeName !== undefined ) {
  46013. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  46014. } else if ( parameters.morphTargets === true ) {
  46015. // programs with morphTargets displace position out of attribute 0
  46016. gl.bindAttribLocation( program, 0, 'position' );
  46017. }
  46018. gl.linkProgram( program );
  46019. function onFirstUse( self ) {
  46020. // check for link errors
  46021. if ( renderer.debug.checkShaderErrors ) {
  46022. const programLog = gl.getProgramInfoLog( program ).trim();
  46023. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  46024. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  46025. let runnable = true;
  46026. let haveDiagnostics = true;
  46027. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  46028. runnable = false;
  46029. if ( typeof renderer.debug.onShaderError === 'function' ) {
  46030. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  46031. } else {
  46032. // default error reporting
  46033. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  46034. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  46035. console.error(
  46036. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  46037. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  46038. 'Material Name: ' + self.name + '\n' +
  46039. 'Material Type: ' + self.type + '\n\n' +
  46040. 'Program Info Log: ' + programLog + '\n' +
  46041. vertexErrors + '\n' +
  46042. fragmentErrors
  46043. );
  46044. }
  46045. } else if ( programLog !== '' ) {
  46046. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  46047. } else if ( vertexLog === '' || fragmentLog === '' ) {
  46048. haveDiagnostics = false;
  46049. }
  46050. if ( haveDiagnostics ) {
  46051. self.diagnostics = {
  46052. runnable: runnable,
  46053. programLog: programLog,
  46054. vertexShader: {
  46055. log: vertexLog,
  46056. prefix: prefixVertex
  46057. },
  46058. fragmentShader: {
  46059. log: fragmentLog,
  46060. prefix: prefixFragment
  46061. }
  46062. };
  46063. }
  46064. }
  46065. // Clean up
  46066. // Crashes in iOS9 and iOS10. #18402
  46067. // gl.detachShader( program, glVertexShader );
  46068. // gl.detachShader( program, glFragmentShader );
  46069. gl.deleteShader( glVertexShader );
  46070. gl.deleteShader( glFragmentShader );
  46071. cachedUniforms = new WebGLUniforms( gl, program );
  46072. cachedAttributes = fetchAttributeLocations( gl, program );
  46073. }
  46074. // set up caching for uniform locations
  46075. let cachedUniforms;
  46076. this.getUniforms = function () {
  46077. if ( cachedUniforms === undefined ) {
  46078. // Populates cachedUniforms and cachedAttributes
  46079. onFirstUse( this );
  46080. }
  46081. return cachedUniforms;
  46082. };
  46083. // set up caching for attribute locations
  46084. let cachedAttributes;
  46085. this.getAttributes = function () {
  46086. if ( cachedAttributes === undefined ) {
  46087. // Populates cachedAttributes and cachedUniforms
  46088. onFirstUse( this );
  46089. }
  46090. return cachedAttributes;
  46091. };
  46092. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  46093. // flag the program as ready immediately. It may cause a stall when it's first used.
  46094. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  46095. this.isReady = function () {
  46096. if ( programReady === false ) {
  46097. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  46098. }
  46099. return programReady;
  46100. };
  46101. // free resource
  46102. this.destroy = function () {
  46103. bindingStates.releaseStatesOfProgram( this );
  46104. gl.deleteProgram( program );
  46105. this.program = undefined;
  46106. };
  46107. //
  46108. this.type = parameters.shaderType;
  46109. this.name = parameters.shaderName;
  46110. this.id = programIdCount ++;
  46111. this.cacheKey = cacheKey;
  46112. this.usedTimes = 1;
  46113. this.program = program;
  46114. this.vertexShader = glVertexShader;
  46115. this.fragmentShader = glFragmentShader;
  46116. return this;
  46117. }
  46118. let _id = 0;
  46119. class WebGLShaderCache {
  46120. constructor() {
  46121. this.shaderCache = new Map();
  46122. this.materialCache = new Map();
  46123. }
  46124. update( material ) {
  46125. const vertexShader = material.vertexShader;
  46126. const fragmentShader = material.fragmentShader;
  46127. const vertexShaderStage = this._getShaderStage( vertexShader );
  46128. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  46129. const materialShaders = this._getShaderCacheForMaterial( material );
  46130. if ( materialShaders.has( vertexShaderStage ) === false ) {
  46131. materialShaders.add( vertexShaderStage );
  46132. vertexShaderStage.usedTimes ++;
  46133. }
  46134. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  46135. materialShaders.add( fragmentShaderStage );
  46136. fragmentShaderStage.usedTimes ++;
  46137. }
  46138. return this;
  46139. }
  46140. remove( material ) {
  46141. const materialShaders = this.materialCache.get( material );
  46142. for ( const shaderStage of materialShaders ) {
  46143. shaderStage.usedTimes --;
  46144. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  46145. }
  46146. this.materialCache.delete( material );
  46147. return this;
  46148. }
  46149. getVertexShaderID( material ) {
  46150. return this._getShaderStage( material.vertexShader ).id;
  46151. }
  46152. getFragmentShaderID( material ) {
  46153. return this._getShaderStage( material.fragmentShader ).id;
  46154. }
  46155. dispose() {
  46156. this.shaderCache.clear();
  46157. this.materialCache.clear();
  46158. }
  46159. _getShaderCacheForMaterial( material ) {
  46160. const cache = this.materialCache;
  46161. let set = cache.get( material );
  46162. if ( set === undefined ) {
  46163. set = new Set();
  46164. cache.set( material, set );
  46165. }
  46166. return set;
  46167. }
  46168. _getShaderStage( code ) {
  46169. const cache = this.shaderCache;
  46170. let stage = cache.get( code );
  46171. if ( stage === undefined ) {
  46172. stage = new WebGLShaderStage( code );
  46173. cache.set( code, stage );
  46174. }
  46175. return stage;
  46176. }
  46177. }
  46178. class WebGLShaderStage {
  46179. constructor( code ) {
  46180. this.id = _id ++;
  46181. this.code = code;
  46182. this.usedTimes = 0;
  46183. }
  46184. }
  46185. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  46186. const _programLayers = new Layers();
  46187. const _customShaders = new WebGLShaderCache();
  46188. const _activeChannels = new Set();
  46189. const programs = [];
  46190. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  46191. const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  46192. let precision = capabilities.precision;
  46193. const shaderIDs = {
  46194. MeshDepthMaterial: 'depth',
  46195. MeshDistanceMaterial: 'distanceRGBA',
  46196. MeshNormalMaterial: 'normal',
  46197. MeshBasicMaterial: 'basic',
  46198. MeshLambertMaterial: 'lambert',
  46199. MeshPhongMaterial: 'phong',
  46200. MeshToonMaterial: 'toon',
  46201. MeshStandardMaterial: 'physical',
  46202. MeshPhysicalMaterial: 'physical',
  46203. MeshMatcapMaterial: 'matcap',
  46204. LineBasicMaterial: 'basic',
  46205. LineDashedMaterial: 'dashed',
  46206. PointsMaterial: 'points',
  46207. ShadowMaterial: 'shadow',
  46208. SpriteMaterial: 'sprite'
  46209. };
  46210. function getChannel( value ) {
  46211. _activeChannels.add( value );
  46212. if ( value === 0 ) return 'uv';
  46213. return `uv${ value }`;
  46214. }
  46215. function getParameters( material, lights, shadows, scene, object ) {
  46216. const fog = scene.fog;
  46217. const geometry = object.geometry;
  46218. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  46219. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  46220. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  46221. const shaderID = shaderIDs[ material.type ];
  46222. // heuristics to create shader parameters according to lights in the scene
  46223. // (not to blow over maxLights budget)
  46224. if ( material.precision !== null ) {
  46225. precision = capabilities.getMaxPrecision( material.precision );
  46226. if ( precision !== material.precision ) {
  46227. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  46228. }
  46229. }
  46230. //
  46231. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  46232. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  46233. let morphTextureStride = 0;
  46234. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  46235. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  46236. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  46237. //
  46238. let vertexShader, fragmentShader;
  46239. let customVertexShaderID, customFragmentShaderID;
  46240. if ( shaderID ) {
  46241. const shader = ShaderLib[ shaderID ];
  46242. vertexShader = shader.vertexShader;
  46243. fragmentShader = shader.fragmentShader;
  46244. } else {
  46245. vertexShader = material.vertexShader;
  46246. fragmentShader = material.fragmentShader;
  46247. _customShaders.update( material );
  46248. customVertexShaderID = _customShaders.getVertexShaderID( material );
  46249. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  46250. }
  46251. const currentRenderTarget = renderer.getRenderTarget();
  46252. const reverseDepthBuffer = renderer.state.buffers.depth.getReversed();
  46253. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  46254. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  46255. const HAS_MAP = !! material.map;
  46256. const HAS_MATCAP = !! material.matcap;
  46257. const HAS_ENVMAP = !! envMap;
  46258. const HAS_AOMAP = !! material.aoMap;
  46259. const HAS_LIGHTMAP = !! material.lightMap;
  46260. const HAS_BUMPMAP = !! material.bumpMap;
  46261. const HAS_NORMALMAP = !! material.normalMap;
  46262. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  46263. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  46264. const HAS_METALNESSMAP = !! material.metalnessMap;
  46265. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  46266. const HAS_ANISOTROPY = material.anisotropy > 0;
  46267. const HAS_CLEARCOAT = material.clearcoat > 0;
  46268. const HAS_DISPERSION = material.dispersion > 0;
  46269. const HAS_IRIDESCENCE = material.iridescence > 0;
  46270. const HAS_SHEEN = material.sheen > 0;
  46271. const HAS_TRANSMISSION = material.transmission > 0;
  46272. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  46273. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  46274. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  46275. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  46276. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  46277. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  46278. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  46279. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  46280. const HAS_SPECULARMAP = !! material.specularMap;
  46281. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  46282. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  46283. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  46284. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  46285. const HAS_GRADIENTMAP = !! material.gradientMap;
  46286. const HAS_ALPHAMAP = !! material.alphaMap;
  46287. const HAS_ALPHATEST = material.alphaTest > 0;
  46288. const HAS_ALPHAHASH = !! material.alphaHash;
  46289. const HAS_EXTENSIONS = !! material.extensions;
  46290. let toneMapping = NoToneMapping;
  46291. if ( material.toneMapped ) {
  46292. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  46293. toneMapping = renderer.toneMapping;
  46294. }
  46295. }
  46296. const parameters = {
  46297. shaderID: shaderID,
  46298. shaderType: material.type,
  46299. shaderName: material.name,
  46300. vertexShader: vertexShader,
  46301. fragmentShader: fragmentShader,
  46302. defines: material.defines,
  46303. customVertexShaderID: customVertexShaderID,
  46304. customFragmentShaderID: customFragmentShaderID,
  46305. isRawShaderMaterial: material.isRawShaderMaterial === true,
  46306. glslVersion: material.glslVersion,
  46307. precision: precision,
  46308. batching: IS_BATCHEDMESH,
  46309. batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null,
  46310. instancing: IS_INSTANCEDMESH,
  46311. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  46312. instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
  46313. supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
  46314. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  46315. alphaToCoverage: !! material.alphaToCoverage,
  46316. map: HAS_MAP,
  46317. matcap: HAS_MATCAP,
  46318. envMap: HAS_ENVMAP,
  46319. envMapMode: HAS_ENVMAP && envMap.mapping,
  46320. envMapCubeUVHeight: envMapCubeUVHeight,
  46321. aoMap: HAS_AOMAP,
  46322. lightMap: HAS_LIGHTMAP,
  46323. bumpMap: HAS_BUMPMAP,
  46324. normalMap: HAS_NORMALMAP,
  46325. displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
  46326. emissiveMap: HAS_EMISSIVEMAP,
  46327. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  46328. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  46329. metalnessMap: HAS_METALNESSMAP,
  46330. roughnessMap: HAS_ROUGHNESSMAP,
  46331. anisotropy: HAS_ANISOTROPY,
  46332. anisotropyMap: HAS_ANISOTROPYMAP,
  46333. clearcoat: HAS_CLEARCOAT,
  46334. clearcoatMap: HAS_CLEARCOATMAP,
  46335. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  46336. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  46337. dispersion: HAS_DISPERSION,
  46338. iridescence: HAS_IRIDESCENCE,
  46339. iridescenceMap: HAS_IRIDESCENCEMAP,
  46340. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  46341. sheen: HAS_SHEEN,
  46342. sheenColorMap: HAS_SHEEN_COLORMAP,
  46343. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  46344. specularMap: HAS_SPECULARMAP,
  46345. specularColorMap: HAS_SPECULAR_COLORMAP,
  46346. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  46347. transmission: HAS_TRANSMISSION,
  46348. transmissionMap: HAS_TRANSMISSIONMAP,
  46349. thicknessMap: HAS_THICKNESSMAP,
  46350. gradientMap: HAS_GRADIENTMAP,
  46351. opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
  46352. alphaMap: HAS_ALPHAMAP,
  46353. alphaTest: HAS_ALPHATEST,
  46354. alphaHash: HAS_ALPHAHASH,
  46355. combine: material.combine,
  46356. //
  46357. mapUv: HAS_MAP && getChannel( material.map.channel ),
  46358. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  46359. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  46360. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  46361. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  46362. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  46363. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  46364. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  46365. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  46366. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  46367. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  46368. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  46369. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  46370. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  46371. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  46372. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  46373. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  46374. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  46375. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  46376. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  46377. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  46378. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  46379. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  46380. //
  46381. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  46382. vertexColors: material.vertexColors,
  46383. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  46384. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  46385. fog: !! fog,
  46386. useFog: material.fog === true,
  46387. fogExp2: ( !! fog && fog.isFogExp2 ),
  46388. flatShading: material.flatShading === true,
  46389. sizeAttenuation: material.sizeAttenuation === true,
  46390. logarithmicDepthBuffer: logarithmicDepthBuffer,
  46391. reverseDepthBuffer: reverseDepthBuffer,
  46392. skinning: object.isSkinnedMesh === true,
  46393. morphTargets: geometry.morphAttributes.position !== undefined,
  46394. morphNormals: geometry.morphAttributes.normal !== undefined,
  46395. morphColors: geometry.morphAttributes.color !== undefined,
  46396. morphTargetsCount: morphTargetsCount,
  46397. morphTextureStride: morphTextureStride,
  46398. numDirLights: lights.directional.length,
  46399. numPointLights: lights.point.length,
  46400. numSpotLights: lights.spot.length,
  46401. numSpotLightMaps: lights.spotLightMap.length,
  46402. numRectAreaLights: lights.rectArea.length,
  46403. numHemiLights: lights.hemi.length,
  46404. numDirLightShadows: lights.directionalShadowMap.length,
  46405. numPointLightShadows: lights.pointShadowMap.length,
  46406. numSpotLightShadows: lights.spotShadowMap.length,
  46407. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  46408. numLightProbes: lights.numLightProbes,
  46409. numClippingPlanes: clipping.numPlanes,
  46410. numClipIntersection: clipping.numIntersection,
  46411. dithering: material.dithering,
  46412. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  46413. shadowMapType: renderer.shadowMap.type,
  46414. toneMapping: toneMapping,
  46415. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  46416. decodeVideoTextureEmissive: HAS_EMISSIVEMAP && ( material.emissiveMap.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.emissiveMap.colorSpace ) === SRGBTransfer ),
  46417. premultipliedAlpha: material.premultipliedAlpha,
  46418. doubleSided: material.side === DoubleSide,
  46419. flipSided: material.side === BackSide,
  46420. useDepthPacking: material.depthPacking >= 0,
  46421. depthPacking: material.depthPacking || 0,
  46422. index0AttributeName: material.index0AttributeName,
  46423. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ),
  46424. extensionMultiDraw: ( HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH ) && extensions.has( 'WEBGL_multi_draw' ),
  46425. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  46426. customProgramCacheKey: material.customProgramCacheKey()
  46427. };
  46428. // the usage of getChannel() determines the active texture channels for this shader
  46429. parameters.vertexUv1s = _activeChannels.has( 1 );
  46430. parameters.vertexUv2s = _activeChannels.has( 2 );
  46431. parameters.vertexUv3s = _activeChannels.has( 3 );
  46432. _activeChannels.clear();
  46433. return parameters;
  46434. }
  46435. function getProgramCacheKey( parameters ) {
  46436. const array = [];
  46437. if ( parameters.shaderID ) {
  46438. array.push( parameters.shaderID );
  46439. } else {
  46440. array.push( parameters.customVertexShaderID );
  46441. array.push( parameters.customFragmentShaderID );
  46442. }
  46443. if ( parameters.defines !== undefined ) {
  46444. for ( const name in parameters.defines ) {
  46445. array.push( name );
  46446. array.push( parameters.defines[ name ] );
  46447. }
  46448. }
  46449. if ( parameters.isRawShaderMaterial === false ) {
  46450. getProgramCacheKeyParameters( array, parameters );
  46451. getProgramCacheKeyBooleans( array, parameters );
  46452. array.push( renderer.outputColorSpace );
  46453. }
  46454. array.push( parameters.customProgramCacheKey );
  46455. return array.join();
  46456. }
  46457. function getProgramCacheKeyParameters( array, parameters ) {
  46458. array.push( parameters.precision );
  46459. array.push( parameters.outputColorSpace );
  46460. array.push( parameters.envMapMode );
  46461. array.push( parameters.envMapCubeUVHeight );
  46462. array.push( parameters.mapUv );
  46463. array.push( parameters.alphaMapUv );
  46464. array.push( parameters.lightMapUv );
  46465. array.push( parameters.aoMapUv );
  46466. array.push( parameters.bumpMapUv );
  46467. array.push( parameters.normalMapUv );
  46468. array.push( parameters.displacementMapUv );
  46469. array.push( parameters.emissiveMapUv );
  46470. array.push( parameters.metalnessMapUv );
  46471. array.push( parameters.roughnessMapUv );
  46472. array.push( parameters.anisotropyMapUv );
  46473. array.push( parameters.clearcoatMapUv );
  46474. array.push( parameters.clearcoatNormalMapUv );
  46475. array.push( parameters.clearcoatRoughnessMapUv );
  46476. array.push( parameters.iridescenceMapUv );
  46477. array.push( parameters.iridescenceThicknessMapUv );
  46478. array.push( parameters.sheenColorMapUv );
  46479. array.push( parameters.sheenRoughnessMapUv );
  46480. array.push( parameters.specularMapUv );
  46481. array.push( parameters.specularColorMapUv );
  46482. array.push( parameters.specularIntensityMapUv );
  46483. array.push( parameters.transmissionMapUv );
  46484. array.push( parameters.thicknessMapUv );
  46485. array.push( parameters.combine );
  46486. array.push( parameters.fogExp2 );
  46487. array.push( parameters.sizeAttenuation );
  46488. array.push( parameters.morphTargetsCount );
  46489. array.push( parameters.morphAttributeCount );
  46490. array.push( parameters.numDirLights );
  46491. array.push( parameters.numPointLights );
  46492. array.push( parameters.numSpotLights );
  46493. array.push( parameters.numSpotLightMaps );
  46494. array.push( parameters.numHemiLights );
  46495. array.push( parameters.numRectAreaLights );
  46496. array.push( parameters.numDirLightShadows );
  46497. array.push( parameters.numPointLightShadows );
  46498. array.push( parameters.numSpotLightShadows );
  46499. array.push( parameters.numSpotLightShadowsWithMaps );
  46500. array.push( parameters.numLightProbes );
  46501. array.push( parameters.shadowMapType );
  46502. array.push( parameters.toneMapping );
  46503. array.push( parameters.numClippingPlanes );
  46504. array.push( parameters.numClipIntersection );
  46505. array.push( parameters.depthPacking );
  46506. }
  46507. function getProgramCacheKeyBooleans( array, parameters ) {
  46508. _programLayers.disableAll();
  46509. if ( parameters.supportsVertexTextures )
  46510. _programLayers.enable( 0 );
  46511. if ( parameters.instancing )
  46512. _programLayers.enable( 1 );
  46513. if ( parameters.instancingColor )
  46514. _programLayers.enable( 2 );
  46515. if ( parameters.instancingMorph )
  46516. _programLayers.enable( 3 );
  46517. if ( parameters.matcap )
  46518. _programLayers.enable( 4 );
  46519. if ( parameters.envMap )
  46520. _programLayers.enable( 5 );
  46521. if ( parameters.normalMapObjectSpace )
  46522. _programLayers.enable( 6 );
  46523. if ( parameters.normalMapTangentSpace )
  46524. _programLayers.enable( 7 );
  46525. if ( parameters.clearcoat )
  46526. _programLayers.enable( 8 );
  46527. if ( parameters.iridescence )
  46528. _programLayers.enable( 9 );
  46529. if ( parameters.alphaTest )
  46530. _programLayers.enable( 10 );
  46531. if ( parameters.vertexColors )
  46532. _programLayers.enable( 11 );
  46533. if ( parameters.vertexAlphas )
  46534. _programLayers.enable( 12 );
  46535. if ( parameters.vertexUv1s )
  46536. _programLayers.enable( 13 );
  46537. if ( parameters.vertexUv2s )
  46538. _programLayers.enable( 14 );
  46539. if ( parameters.vertexUv3s )
  46540. _programLayers.enable( 15 );
  46541. if ( parameters.vertexTangents )
  46542. _programLayers.enable( 16 );
  46543. if ( parameters.anisotropy )
  46544. _programLayers.enable( 17 );
  46545. if ( parameters.alphaHash )
  46546. _programLayers.enable( 18 );
  46547. if ( parameters.batching )
  46548. _programLayers.enable( 19 );
  46549. if ( parameters.dispersion )
  46550. _programLayers.enable( 20 );
  46551. if ( parameters.batchingColor )
  46552. _programLayers.enable( 21 );
  46553. array.push( _programLayers.mask );
  46554. _programLayers.disableAll();
  46555. if ( parameters.fog )
  46556. _programLayers.enable( 0 );
  46557. if ( parameters.useFog )
  46558. _programLayers.enable( 1 );
  46559. if ( parameters.flatShading )
  46560. _programLayers.enable( 2 );
  46561. if ( parameters.logarithmicDepthBuffer )
  46562. _programLayers.enable( 3 );
  46563. if ( parameters.reverseDepthBuffer )
  46564. _programLayers.enable( 4 );
  46565. if ( parameters.skinning )
  46566. _programLayers.enable( 5 );
  46567. if ( parameters.morphTargets )
  46568. _programLayers.enable( 6 );
  46569. if ( parameters.morphNormals )
  46570. _programLayers.enable( 7 );
  46571. if ( parameters.morphColors )
  46572. _programLayers.enable( 8 );
  46573. if ( parameters.premultipliedAlpha )
  46574. _programLayers.enable( 9 );
  46575. if ( parameters.shadowMapEnabled )
  46576. _programLayers.enable( 10 );
  46577. if ( parameters.doubleSided )
  46578. _programLayers.enable( 11 );
  46579. if ( parameters.flipSided )
  46580. _programLayers.enable( 12 );
  46581. if ( parameters.useDepthPacking )
  46582. _programLayers.enable( 13 );
  46583. if ( parameters.dithering )
  46584. _programLayers.enable( 14 );
  46585. if ( parameters.transmission )
  46586. _programLayers.enable( 15 );
  46587. if ( parameters.sheen )
  46588. _programLayers.enable( 16 );
  46589. if ( parameters.opaque )
  46590. _programLayers.enable( 17 );
  46591. if ( parameters.pointsUvs )
  46592. _programLayers.enable( 18 );
  46593. if ( parameters.decodeVideoTexture )
  46594. _programLayers.enable( 19 );
  46595. if ( parameters.decodeVideoTextureEmissive )
  46596. _programLayers.enable( 20 );
  46597. if ( parameters.alphaToCoverage )
  46598. _programLayers.enable( 21 );
  46599. array.push( _programLayers.mask );
  46600. }
  46601. function getUniforms( material ) {
  46602. const shaderID = shaderIDs[ material.type ];
  46603. let uniforms;
  46604. if ( shaderID ) {
  46605. const shader = ShaderLib[ shaderID ];
  46606. uniforms = UniformsUtils.clone( shader.uniforms );
  46607. } else {
  46608. uniforms = material.uniforms;
  46609. }
  46610. return uniforms;
  46611. }
  46612. function acquireProgram( parameters, cacheKey ) {
  46613. let program;
  46614. // Check if code has been already compiled
  46615. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  46616. const preexistingProgram = programs[ p ];
  46617. if ( preexistingProgram.cacheKey === cacheKey ) {
  46618. program = preexistingProgram;
  46619. ++ program.usedTimes;
  46620. break;
  46621. }
  46622. }
  46623. if ( program === undefined ) {
  46624. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  46625. programs.push( program );
  46626. }
  46627. return program;
  46628. }
  46629. function releaseProgram( program ) {
  46630. if ( -- program.usedTimes === 0 ) {
  46631. // Remove from unordered set
  46632. const i = programs.indexOf( program );
  46633. programs[ i ] = programs[ programs.length - 1 ];
  46634. programs.pop();
  46635. // Free WebGL resources
  46636. program.destroy();
  46637. }
  46638. }
  46639. function releaseShaderCache( material ) {
  46640. _customShaders.remove( material );
  46641. }
  46642. function dispose() {
  46643. _customShaders.dispose();
  46644. }
  46645. return {
  46646. getParameters: getParameters,
  46647. getProgramCacheKey: getProgramCacheKey,
  46648. getUniforms: getUniforms,
  46649. acquireProgram: acquireProgram,
  46650. releaseProgram: releaseProgram,
  46651. releaseShaderCache: releaseShaderCache,
  46652. // Exposed for resource monitoring & error feedback via renderer.info:
  46653. programs: programs,
  46654. dispose: dispose
  46655. };
  46656. }
  46657. function WebGLProperties() {
  46658. let properties = new WeakMap();
  46659. function has( object ) {
  46660. return properties.has( object );
  46661. }
  46662. function get( object ) {
  46663. let map = properties.get( object );
  46664. if ( map === undefined ) {
  46665. map = {};
  46666. properties.set( object, map );
  46667. }
  46668. return map;
  46669. }
  46670. function remove( object ) {
  46671. properties.delete( object );
  46672. }
  46673. function update( object, key, value ) {
  46674. properties.get( object )[ key ] = value;
  46675. }
  46676. function dispose() {
  46677. properties = new WeakMap();
  46678. }
  46679. return {
  46680. has: has,
  46681. get: get,
  46682. remove: remove,
  46683. update: update,
  46684. dispose: dispose
  46685. };
  46686. }
  46687. function painterSortStable( a, b ) {
  46688. if ( a.groupOrder !== b.groupOrder ) {
  46689. return a.groupOrder - b.groupOrder;
  46690. } else if ( a.renderOrder !== b.renderOrder ) {
  46691. return a.renderOrder - b.renderOrder;
  46692. } else if ( a.material.id !== b.material.id ) {
  46693. return a.material.id - b.material.id;
  46694. } else if ( a.z !== b.z ) {
  46695. return a.z - b.z;
  46696. } else {
  46697. return a.id - b.id;
  46698. }
  46699. }
  46700. function reversePainterSortStable( a, b ) {
  46701. if ( a.groupOrder !== b.groupOrder ) {
  46702. return a.groupOrder - b.groupOrder;
  46703. } else if ( a.renderOrder !== b.renderOrder ) {
  46704. return a.renderOrder - b.renderOrder;
  46705. } else if ( a.z !== b.z ) {
  46706. return b.z - a.z;
  46707. } else {
  46708. return a.id - b.id;
  46709. }
  46710. }
  46711. function WebGLRenderList() {
  46712. const renderItems = [];
  46713. let renderItemsIndex = 0;
  46714. const opaque = [];
  46715. const transmissive = [];
  46716. const transparent = [];
  46717. function init() {
  46718. renderItemsIndex = 0;
  46719. opaque.length = 0;
  46720. transmissive.length = 0;
  46721. transparent.length = 0;
  46722. }
  46723. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  46724. let renderItem = renderItems[ renderItemsIndex ];
  46725. if ( renderItem === undefined ) {
  46726. renderItem = {
  46727. id: object.id,
  46728. object: object,
  46729. geometry: geometry,
  46730. material: material,
  46731. groupOrder: groupOrder,
  46732. renderOrder: object.renderOrder,
  46733. z: z,
  46734. group: group
  46735. };
  46736. renderItems[ renderItemsIndex ] = renderItem;
  46737. } else {
  46738. renderItem.id = object.id;
  46739. renderItem.object = object;
  46740. renderItem.geometry = geometry;
  46741. renderItem.material = material;
  46742. renderItem.groupOrder = groupOrder;
  46743. renderItem.renderOrder = object.renderOrder;
  46744. renderItem.z = z;
  46745. renderItem.group = group;
  46746. }
  46747. renderItemsIndex ++;
  46748. return renderItem;
  46749. }
  46750. function push( object, geometry, material, groupOrder, z, group ) {
  46751. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  46752. if ( material.transmission > 0.0 ) {
  46753. transmissive.push( renderItem );
  46754. } else if ( material.transparent === true ) {
  46755. transparent.push( renderItem );
  46756. } else {
  46757. opaque.push( renderItem );
  46758. }
  46759. }
  46760. function unshift( object, geometry, material, groupOrder, z, group ) {
  46761. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  46762. if ( material.transmission > 0.0 ) {
  46763. transmissive.unshift( renderItem );
  46764. } else if ( material.transparent === true ) {
  46765. transparent.unshift( renderItem );
  46766. } else {
  46767. opaque.unshift( renderItem );
  46768. }
  46769. }
  46770. function sort( customOpaqueSort, customTransparentSort ) {
  46771. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  46772. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  46773. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  46774. }
  46775. function finish() {
  46776. // Clear references from inactive renderItems in the list
  46777. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  46778. const renderItem = renderItems[ i ];
  46779. if ( renderItem.id === null ) break;
  46780. renderItem.id = null;
  46781. renderItem.object = null;
  46782. renderItem.geometry = null;
  46783. renderItem.material = null;
  46784. renderItem.group = null;
  46785. }
  46786. }
  46787. return {
  46788. opaque: opaque,
  46789. transmissive: transmissive,
  46790. transparent: transparent,
  46791. init: init,
  46792. push: push,
  46793. unshift: unshift,
  46794. finish: finish,
  46795. sort: sort
  46796. };
  46797. }
  46798. function WebGLRenderLists() {
  46799. let lists = new WeakMap();
  46800. function get( scene, renderCallDepth ) {
  46801. const listArray = lists.get( scene );
  46802. let list;
  46803. if ( listArray === undefined ) {
  46804. list = new WebGLRenderList();
  46805. lists.set( scene, [ list ] );
  46806. } else {
  46807. if ( renderCallDepth >= listArray.length ) {
  46808. list = new WebGLRenderList();
  46809. listArray.push( list );
  46810. } else {
  46811. list = listArray[ renderCallDepth ];
  46812. }
  46813. }
  46814. return list;
  46815. }
  46816. function dispose() {
  46817. lists = new WeakMap();
  46818. }
  46819. return {
  46820. get: get,
  46821. dispose: dispose
  46822. };
  46823. }
  46824. function UniformsCache() {
  46825. const lights = {};
  46826. return {
  46827. get: function ( light ) {
  46828. if ( lights[ light.id ] !== undefined ) {
  46829. return lights[ light.id ];
  46830. }
  46831. let uniforms;
  46832. switch ( light.type ) {
  46833. case 'DirectionalLight':
  46834. uniforms = {
  46835. direction: new Vector3(),
  46836. color: new Color()
  46837. };
  46838. break;
  46839. case 'SpotLight':
  46840. uniforms = {
  46841. position: new Vector3(),
  46842. direction: new Vector3(),
  46843. color: new Color(),
  46844. distance: 0,
  46845. coneCos: 0,
  46846. penumbraCos: 0,
  46847. decay: 0
  46848. };
  46849. break;
  46850. case 'PointLight':
  46851. uniforms = {
  46852. position: new Vector3(),
  46853. color: new Color(),
  46854. distance: 0,
  46855. decay: 0
  46856. };
  46857. break;
  46858. case 'HemisphereLight':
  46859. uniforms = {
  46860. direction: new Vector3(),
  46861. skyColor: new Color(),
  46862. groundColor: new Color()
  46863. };
  46864. break;
  46865. case 'RectAreaLight':
  46866. uniforms = {
  46867. color: new Color(),
  46868. position: new Vector3(),
  46869. halfWidth: new Vector3(),
  46870. halfHeight: new Vector3()
  46871. };
  46872. break;
  46873. }
  46874. lights[ light.id ] = uniforms;
  46875. return uniforms;
  46876. }
  46877. };
  46878. }
  46879. function ShadowUniformsCache() {
  46880. const lights = {};
  46881. return {
  46882. get: function ( light ) {
  46883. if ( lights[ light.id ] !== undefined ) {
  46884. return lights[ light.id ];
  46885. }
  46886. let uniforms;
  46887. switch ( light.type ) {
  46888. case 'DirectionalLight':
  46889. uniforms = {
  46890. shadowIntensity: 1,
  46891. shadowBias: 0,
  46892. shadowNormalBias: 0,
  46893. shadowRadius: 1,
  46894. shadowMapSize: new Vector2()
  46895. };
  46896. break;
  46897. case 'SpotLight':
  46898. uniforms = {
  46899. shadowIntensity: 1,
  46900. shadowBias: 0,
  46901. shadowNormalBias: 0,
  46902. shadowRadius: 1,
  46903. shadowMapSize: new Vector2()
  46904. };
  46905. break;
  46906. case 'PointLight':
  46907. uniforms = {
  46908. shadowIntensity: 1,
  46909. shadowBias: 0,
  46910. shadowNormalBias: 0,
  46911. shadowRadius: 1,
  46912. shadowMapSize: new Vector2(),
  46913. shadowCameraNear: 1,
  46914. shadowCameraFar: 1000
  46915. };
  46916. break;
  46917. // TODO (abelnation): set RectAreaLight shadow uniforms
  46918. }
  46919. lights[ light.id ] = uniforms;
  46920. return uniforms;
  46921. }
  46922. };
  46923. }
  46924. let nextVersion = 0;
  46925. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  46926. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  46927. }
  46928. function WebGLLights( extensions ) {
  46929. const cache = new UniformsCache();
  46930. const shadowCache = ShadowUniformsCache();
  46931. const state = {
  46932. version: 0,
  46933. hash: {
  46934. directionalLength: -1,
  46935. pointLength: -1,
  46936. spotLength: -1,
  46937. rectAreaLength: -1,
  46938. hemiLength: -1,
  46939. numDirectionalShadows: -1,
  46940. numPointShadows: -1,
  46941. numSpotShadows: -1,
  46942. numSpotMaps: -1,
  46943. numLightProbes: -1
  46944. },
  46945. ambient: [ 0, 0, 0 ],
  46946. probe: [],
  46947. directional: [],
  46948. directionalShadow: [],
  46949. directionalShadowMap: [],
  46950. directionalShadowMatrix: [],
  46951. spot: [],
  46952. spotLightMap: [],
  46953. spotShadow: [],
  46954. spotShadowMap: [],
  46955. spotLightMatrix: [],
  46956. rectArea: [],
  46957. rectAreaLTC1: null,
  46958. rectAreaLTC2: null,
  46959. point: [],
  46960. pointShadow: [],
  46961. pointShadowMap: [],
  46962. pointShadowMatrix: [],
  46963. hemi: [],
  46964. numSpotLightShadowsWithMaps: 0,
  46965. numLightProbes: 0
  46966. };
  46967. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  46968. const vector3 = new Vector3();
  46969. const matrix4 = new Matrix4();
  46970. const matrix42 = new Matrix4();
  46971. function setup( lights ) {
  46972. let r = 0, g = 0, b = 0;
  46973. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  46974. let directionalLength = 0;
  46975. let pointLength = 0;
  46976. let spotLength = 0;
  46977. let rectAreaLength = 0;
  46978. let hemiLength = 0;
  46979. let numDirectionalShadows = 0;
  46980. let numPointShadows = 0;
  46981. let numSpotShadows = 0;
  46982. let numSpotMaps = 0;
  46983. let numSpotShadowsWithMaps = 0;
  46984. let numLightProbes = 0;
  46985. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  46986. lights.sort( shadowCastingAndTexturingLightsFirst );
  46987. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  46988. const light = lights[ i ];
  46989. const color = light.color;
  46990. const intensity = light.intensity;
  46991. const distance = light.distance;
  46992. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  46993. if ( light.isAmbientLight ) {
  46994. r += color.r * intensity;
  46995. g += color.g * intensity;
  46996. b += color.b * intensity;
  46997. } else if ( light.isLightProbe ) {
  46998. for ( let j = 0; j < 9; j ++ ) {
  46999. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  47000. }
  47001. numLightProbes ++;
  47002. } else if ( light.isDirectionalLight ) {
  47003. const uniforms = cache.get( light );
  47004. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  47005. if ( light.castShadow ) {
  47006. const shadow = light.shadow;
  47007. const shadowUniforms = shadowCache.get( light );
  47008. shadowUniforms.shadowIntensity = shadow.intensity;
  47009. shadowUniforms.shadowBias = shadow.bias;
  47010. shadowUniforms.shadowNormalBias = shadow.normalBias;
  47011. shadowUniforms.shadowRadius = shadow.radius;
  47012. shadowUniforms.shadowMapSize = shadow.mapSize;
  47013. state.directionalShadow[ directionalLength ] = shadowUniforms;
  47014. state.directionalShadowMap[ directionalLength ] = shadowMap;
  47015. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  47016. numDirectionalShadows ++;
  47017. }
  47018. state.directional[ directionalLength ] = uniforms;
  47019. directionalLength ++;
  47020. } else if ( light.isSpotLight ) {
  47021. const uniforms = cache.get( light );
  47022. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  47023. uniforms.color.copy( color ).multiplyScalar( intensity );
  47024. uniforms.distance = distance;
  47025. uniforms.coneCos = Math.cos( light.angle );
  47026. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  47027. uniforms.decay = light.decay;
  47028. state.spot[ spotLength ] = uniforms;
  47029. const shadow = light.shadow;
  47030. if ( light.map ) {
  47031. state.spotLightMap[ numSpotMaps ] = light.map;
  47032. numSpotMaps ++;
  47033. // make sure the lightMatrix is up to date
  47034. // TODO : do it if required only
  47035. shadow.updateMatrices( light );
  47036. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  47037. }
  47038. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  47039. if ( light.castShadow ) {
  47040. const shadowUniforms = shadowCache.get( light );
  47041. shadowUniforms.shadowIntensity = shadow.intensity;
  47042. shadowUniforms.shadowBias = shadow.bias;
  47043. shadowUniforms.shadowNormalBias = shadow.normalBias;
  47044. shadowUniforms.shadowRadius = shadow.radius;
  47045. shadowUniforms.shadowMapSize = shadow.mapSize;
  47046. state.spotShadow[ spotLength ] = shadowUniforms;
  47047. state.spotShadowMap[ spotLength ] = shadowMap;
  47048. numSpotShadows ++;
  47049. }
  47050. spotLength ++;
  47051. } else if ( light.isRectAreaLight ) {
  47052. const uniforms = cache.get( light );
  47053. uniforms.color.copy( color ).multiplyScalar( intensity );
  47054. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  47055. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  47056. state.rectArea[ rectAreaLength ] = uniforms;
  47057. rectAreaLength ++;
  47058. } else if ( light.isPointLight ) {
  47059. const uniforms = cache.get( light );
  47060. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  47061. uniforms.distance = light.distance;
  47062. uniforms.decay = light.decay;
  47063. if ( light.castShadow ) {
  47064. const shadow = light.shadow;
  47065. const shadowUniforms = shadowCache.get( light );
  47066. shadowUniforms.shadowIntensity = shadow.intensity;
  47067. shadowUniforms.shadowBias = shadow.bias;
  47068. shadowUniforms.shadowNormalBias = shadow.normalBias;
  47069. shadowUniforms.shadowRadius = shadow.radius;
  47070. shadowUniforms.shadowMapSize = shadow.mapSize;
  47071. shadowUniforms.shadowCameraNear = shadow.camera.near;
  47072. shadowUniforms.shadowCameraFar = shadow.camera.far;
  47073. state.pointShadow[ pointLength ] = shadowUniforms;
  47074. state.pointShadowMap[ pointLength ] = shadowMap;
  47075. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  47076. numPointShadows ++;
  47077. }
  47078. state.point[ pointLength ] = uniforms;
  47079. pointLength ++;
  47080. } else if ( light.isHemisphereLight ) {
  47081. const uniforms = cache.get( light );
  47082. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  47083. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  47084. state.hemi[ hemiLength ] = uniforms;
  47085. hemiLength ++;
  47086. }
  47087. }
  47088. if ( rectAreaLength > 0 ) {
  47089. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  47090. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  47091. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  47092. } else {
  47093. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  47094. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  47095. }
  47096. }
  47097. state.ambient[ 0 ] = r;
  47098. state.ambient[ 1 ] = g;
  47099. state.ambient[ 2 ] = b;
  47100. const hash = state.hash;
  47101. if ( hash.directionalLength !== directionalLength ||
  47102. hash.pointLength !== pointLength ||
  47103. hash.spotLength !== spotLength ||
  47104. hash.rectAreaLength !== rectAreaLength ||
  47105. hash.hemiLength !== hemiLength ||
  47106. hash.numDirectionalShadows !== numDirectionalShadows ||
  47107. hash.numPointShadows !== numPointShadows ||
  47108. hash.numSpotShadows !== numSpotShadows ||
  47109. hash.numSpotMaps !== numSpotMaps ||
  47110. hash.numLightProbes !== numLightProbes ) {
  47111. state.directional.length = directionalLength;
  47112. state.spot.length = spotLength;
  47113. state.rectArea.length = rectAreaLength;
  47114. state.point.length = pointLength;
  47115. state.hemi.length = hemiLength;
  47116. state.directionalShadow.length = numDirectionalShadows;
  47117. state.directionalShadowMap.length = numDirectionalShadows;
  47118. state.pointShadow.length = numPointShadows;
  47119. state.pointShadowMap.length = numPointShadows;
  47120. state.spotShadow.length = numSpotShadows;
  47121. state.spotShadowMap.length = numSpotShadows;
  47122. state.directionalShadowMatrix.length = numDirectionalShadows;
  47123. state.pointShadowMatrix.length = numPointShadows;
  47124. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  47125. state.spotLightMap.length = numSpotMaps;
  47126. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  47127. state.numLightProbes = numLightProbes;
  47128. hash.directionalLength = directionalLength;
  47129. hash.pointLength = pointLength;
  47130. hash.spotLength = spotLength;
  47131. hash.rectAreaLength = rectAreaLength;
  47132. hash.hemiLength = hemiLength;
  47133. hash.numDirectionalShadows = numDirectionalShadows;
  47134. hash.numPointShadows = numPointShadows;
  47135. hash.numSpotShadows = numSpotShadows;
  47136. hash.numSpotMaps = numSpotMaps;
  47137. hash.numLightProbes = numLightProbes;
  47138. state.version = nextVersion ++;
  47139. }
  47140. }
  47141. function setupView( lights, camera ) {
  47142. let directionalLength = 0;
  47143. let pointLength = 0;
  47144. let spotLength = 0;
  47145. let rectAreaLength = 0;
  47146. let hemiLength = 0;
  47147. const viewMatrix = camera.matrixWorldInverse;
  47148. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  47149. const light = lights[ i ];
  47150. if ( light.isDirectionalLight ) {
  47151. const uniforms = state.directional[ directionalLength ];
  47152. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  47153. vector3.setFromMatrixPosition( light.target.matrixWorld );
  47154. uniforms.direction.sub( vector3 );
  47155. uniforms.direction.transformDirection( viewMatrix );
  47156. directionalLength ++;
  47157. } else if ( light.isSpotLight ) {
  47158. const uniforms = state.spot[ spotLength ];
  47159. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  47160. uniforms.position.applyMatrix4( viewMatrix );
  47161. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  47162. vector3.setFromMatrixPosition( light.target.matrixWorld );
  47163. uniforms.direction.sub( vector3 );
  47164. uniforms.direction.transformDirection( viewMatrix );
  47165. spotLength ++;
  47166. } else if ( light.isRectAreaLight ) {
  47167. const uniforms = state.rectArea[ rectAreaLength ];
  47168. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  47169. uniforms.position.applyMatrix4( viewMatrix );
  47170. // extract local rotation of light to derive width/height half vectors
  47171. matrix42.identity();
  47172. matrix4.copy( light.matrixWorld );
  47173. matrix4.premultiply( viewMatrix );
  47174. matrix42.extractRotation( matrix4 );
  47175. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  47176. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  47177. uniforms.halfWidth.applyMatrix4( matrix42 );
  47178. uniforms.halfHeight.applyMatrix4( matrix42 );
  47179. rectAreaLength ++;
  47180. } else if ( light.isPointLight ) {
  47181. const uniforms = state.point[ pointLength ];
  47182. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  47183. uniforms.position.applyMatrix4( viewMatrix );
  47184. pointLength ++;
  47185. } else if ( light.isHemisphereLight ) {
  47186. const uniforms = state.hemi[ hemiLength ];
  47187. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  47188. uniforms.direction.transformDirection( viewMatrix );
  47189. hemiLength ++;
  47190. }
  47191. }
  47192. }
  47193. return {
  47194. setup: setup,
  47195. setupView: setupView,
  47196. state: state
  47197. };
  47198. }
  47199. function WebGLRenderState( extensions ) {
  47200. const lights = new WebGLLights( extensions );
  47201. const lightsArray = [];
  47202. const shadowsArray = [];
  47203. function init( camera ) {
  47204. state.camera = camera;
  47205. lightsArray.length = 0;
  47206. shadowsArray.length = 0;
  47207. }
  47208. function pushLight( light ) {
  47209. lightsArray.push( light );
  47210. }
  47211. function pushShadow( shadowLight ) {
  47212. shadowsArray.push( shadowLight );
  47213. }
  47214. function setupLights() {
  47215. lights.setup( lightsArray );
  47216. }
  47217. function setupLightsView( camera ) {
  47218. lights.setupView( lightsArray, camera );
  47219. }
  47220. const state = {
  47221. lightsArray: lightsArray,
  47222. shadowsArray: shadowsArray,
  47223. camera: null,
  47224. lights: lights,
  47225. transmissionRenderTarget: {}
  47226. };
  47227. return {
  47228. init: init,
  47229. state: state,
  47230. setupLights: setupLights,
  47231. setupLightsView: setupLightsView,
  47232. pushLight: pushLight,
  47233. pushShadow: pushShadow
  47234. };
  47235. }
  47236. function WebGLRenderStates( extensions ) {
  47237. let renderStates = new WeakMap();
  47238. function get( scene, renderCallDepth = 0 ) {
  47239. const renderStateArray = renderStates.get( scene );
  47240. let renderState;
  47241. if ( renderStateArray === undefined ) {
  47242. renderState = new WebGLRenderState( extensions );
  47243. renderStates.set( scene, [ renderState ] );
  47244. } else {
  47245. if ( renderCallDepth >= renderStateArray.length ) {
  47246. renderState = new WebGLRenderState( extensions );
  47247. renderStateArray.push( renderState );
  47248. } else {
  47249. renderState = renderStateArray[ renderCallDepth ];
  47250. }
  47251. }
  47252. return renderState;
  47253. }
  47254. function dispose() {
  47255. renderStates = new WeakMap();
  47256. }
  47257. return {
  47258. get: get,
  47259. dispose: dispose
  47260. };
  47261. }
  47262. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  47263. 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}";
  47264. function WebGLShadowMap( renderer, objects, capabilities ) {
  47265. let _frustum = new Frustum();
  47266. const _shadowMapSize = new Vector2(),
  47267. _viewportSize = new Vector2(),
  47268. _viewport = new Vector4(),
  47269. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  47270. _distanceMaterial = new MeshDistanceMaterial(),
  47271. _materialCache = {},
  47272. _maxTextureSize = capabilities.maxTextureSize;
  47273. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  47274. const shadowMaterialVertical = new ShaderMaterial( {
  47275. defines: {
  47276. VSM_SAMPLES: 8
  47277. },
  47278. uniforms: {
  47279. shadow_pass: { value: null },
  47280. resolution: { value: new Vector2() },
  47281. radius: { value: 4.0 }
  47282. },
  47283. vertexShader: vertex,
  47284. fragmentShader: fragment
  47285. } );
  47286. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  47287. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  47288. const fullScreenTri = new BufferGeometry();
  47289. fullScreenTri.setAttribute(
  47290. 'position',
  47291. new BufferAttribute(
  47292. new Float32Array( [ -1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5 ] ),
  47293. 3
  47294. )
  47295. );
  47296. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  47297. const scope = this;
  47298. this.enabled = false;
  47299. this.autoUpdate = true;
  47300. this.needsUpdate = false;
  47301. this.type = PCFShadowMap;
  47302. let _previousType = this.type;
  47303. this.render = function ( lights, scene, camera ) {
  47304. if ( scope.enabled === false ) return;
  47305. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  47306. if ( lights.length === 0 ) return;
  47307. const currentRenderTarget = renderer.getRenderTarget();
  47308. const activeCubeFace = renderer.getActiveCubeFace();
  47309. const activeMipmapLevel = renderer.getActiveMipmapLevel();
  47310. const _state = renderer.state;
  47311. // Set GL state for depth map.
  47312. _state.setBlending( NoBlending );
  47313. _state.buffers.color.setClear( 1, 1, 1, 1 );
  47314. _state.buffers.depth.setTest( true );
  47315. _state.setScissorTest( false );
  47316. // check for shadow map type changes
  47317. const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap );
  47318. const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap );
  47319. // render depth map
  47320. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  47321. const light = lights[ i ];
  47322. const shadow = light.shadow;
  47323. if ( shadow === undefined ) {
  47324. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  47325. continue;
  47326. }
  47327. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  47328. _shadowMapSize.copy( shadow.mapSize );
  47329. const shadowFrameExtents = shadow.getFrameExtents();
  47330. _shadowMapSize.multiply( shadowFrameExtents );
  47331. _viewportSize.copy( shadow.mapSize );
  47332. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  47333. if ( _shadowMapSize.x > _maxTextureSize ) {
  47334. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  47335. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  47336. shadow.mapSize.x = _viewportSize.x;
  47337. }
  47338. if ( _shadowMapSize.y > _maxTextureSize ) {
  47339. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  47340. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  47341. shadow.mapSize.y = _viewportSize.y;
  47342. }
  47343. }
  47344. if ( shadow.map === null || toVSM === true || fromVSM === true ) {
  47345. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  47346. if ( shadow.map !== null ) {
  47347. shadow.map.dispose();
  47348. }
  47349. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  47350. shadow.map.texture.name = light.name + '.shadowMap';
  47351. shadow.camera.updateProjectionMatrix();
  47352. }
  47353. renderer.setRenderTarget( shadow.map );
  47354. renderer.clear();
  47355. const viewportCount = shadow.getViewportCount();
  47356. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  47357. const viewport = shadow.getViewport( vp );
  47358. _viewport.set(
  47359. _viewportSize.x * viewport.x,
  47360. _viewportSize.y * viewport.y,
  47361. _viewportSize.x * viewport.z,
  47362. _viewportSize.y * viewport.w
  47363. );
  47364. _state.viewport( _viewport );
  47365. shadow.updateMatrices( light, vp );
  47366. _frustum = shadow.getFrustum();
  47367. renderObject( scene, camera, shadow.camera, light, this.type );
  47368. }
  47369. // do blur pass for VSM
  47370. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  47371. VSMPass( shadow, camera );
  47372. }
  47373. shadow.needsUpdate = false;
  47374. }
  47375. _previousType = this.type;
  47376. scope.needsUpdate = false;
  47377. renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  47378. };
  47379. function VSMPass( shadow, camera ) {
  47380. const geometry = objects.update( fullScreenMesh );
  47381. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  47382. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  47383. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  47384. shadowMaterialVertical.needsUpdate = true;
  47385. shadowMaterialHorizontal.needsUpdate = true;
  47386. }
  47387. if ( shadow.mapPass === null ) {
  47388. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  47389. }
  47390. // vertical pass
  47391. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  47392. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  47393. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  47394. renderer.setRenderTarget( shadow.mapPass );
  47395. renderer.clear();
  47396. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  47397. // horizontal pass
  47398. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  47399. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  47400. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  47401. renderer.setRenderTarget( shadow.map );
  47402. renderer.clear();
  47403. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  47404. }
  47405. function getDepthMaterial( object, material, light, type ) {
  47406. let result = null;
  47407. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  47408. if ( customMaterial !== undefined ) {
  47409. result = customMaterial;
  47410. } else {
  47411. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  47412. if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  47413. ( material.displacementMap && material.displacementScale !== 0 ) ||
  47414. ( material.alphaMap && material.alphaTest > 0 ) ||
  47415. ( material.map && material.alphaTest > 0 ) ||
  47416. ( material.alphaToCoverage === true ) ) {
  47417. // in this case we need a unique material instance reflecting the
  47418. // appropriate state
  47419. const keyA = result.uuid, keyB = material.uuid;
  47420. let materialsForVariant = _materialCache[ keyA ];
  47421. if ( materialsForVariant === undefined ) {
  47422. materialsForVariant = {};
  47423. _materialCache[ keyA ] = materialsForVariant;
  47424. }
  47425. let cachedMaterial = materialsForVariant[ keyB ];
  47426. if ( cachedMaterial === undefined ) {
  47427. cachedMaterial = result.clone();
  47428. materialsForVariant[ keyB ] = cachedMaterial;
  47429. material.addEventListener( 'dispose', onMaterialDispose );
  47430. }
  47431. result = cachedMaterial;
  47432. }
  47433. }
  47434. result.visible = material.visible;
  47435. result.wireframe = material.wireframe;
  47436. if ( type === VSMShadowMap ) {
  47437. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  47438. } else {
  47439. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  47440. }
  47441. result.alphaMap = material.alphaMap;
  47442. result.alphaTest = ( material.alphaToCoverage === true ) ? 0.5 : material.alphaTest; // approximate alphaToCoverage by using a fixed alphaTest value
  47443. result.map = material.map;
  47444. result.clipShadows = material.clipShadows;
  47445. result.clippingPlanes = material.clippingPlanes;
  47446. result.clipIntersection = material.clipIntersection;
  47447. result.displacementMap = material.displacementMap;
  47448. result.displacementScale = material.displacementScale;
  47449. result.displacementBias = material.displacementBias;
  47450. result.wireframeLinewidth = material.wireframeLinewidth;
  47451. result.linewidth = material.linewidth;
  47452. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  47453. const materialProperties = renderer.properties.get( result );
  47454. materialProperties.light = light;
  47455. }
  47456. return result;
  47457. }
  47458. function renderObject( object, camera, shadowCamera, light, type ) {
  47459. if ( object.visible === false ) return;
  47460. const visible = object.layers.test( camera.layers );
  47461. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  47462. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  47463. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  47464. const geometry = objects.update( object );
  47465. const material = object.material;
  47466. if ( Array.isArray( material ) ) {
  47467. const groups = geometry.groups;
  47468. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  47469. const group = groups[ k ];
  47470. const groupMaterial = material[ group.materialIndex ];
  47471. if ( groupMaterial && groupMaterial.visible ) {
  47472. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  47473. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  47474. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  47475. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  47476. }
  47477. }
  47478. } else if ( material.visible ) {
  47479. const depthMaterial = getDepthMaterial( object, material, light, type );
  47480. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  47481. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  47482. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  47483. }
  47484. }
  47485. }
  47486. const children = object.children;
  47487. for ( let i = 0, l = children.length; i < l; i ++ ) {
  47488. renderObject( children[ i ], camera, shadowCamera, light, type );
  47489. }
  47490. }
  47491. function onMaterialDispose( event ) {
  47492. const material = event.target;
  47493. material.removeEventListener( 'dispose', onMaterialDispose );
  47494. // make sure to remove the unique distance/depth materials used for shadow map rendering
  47495. for ( const id in _materialCache ) {
  47496. const cache = _materialCache[ id ];
  47497. const uuid = event.target.uuid;
  47498. if ( uuid in cache ) {
  47499. const shadowMaterial = cache[ uuid ];
  47500. shadowMaterial.dispose();
  47501. delete cache[ uuid ];
  47502. }
  47503. }
  47504. }
  47505. }
  47506. const reversedFuncs = {
  47507. [ NeverDepth ]: AlwaysDepth,
  47508. [ LessDepth ]: GreaterDepth,
  47509. [ EqualDepth ]: NotEqualDepth,
  47510. [ LessEqualDepth ]: GreaterEqualDepth,
  47511. [ AlwaysDepth ]: NeverDepth,
  47512. [ GreaterDepth ]: LessDepth,
  47513. [ NotEqualDepth ]: EqualDepth,
  47514. [ GreaterEqualDepth ]: LessEqualDepth,
  47515. };
  47516. function WebGLState( gl, extensions ) {
  47517. function ColorBuffer() {
  47518. let locked = false;
  47519. const color = new Vector4();
  47520. let currentColorMask = null;
  47521. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  47522. return {
  47523. setMask: function ( colorMask ) {
  47524. if ( currentColorMask !== colorMask && ! locked ) {
  47525. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  47526. currentColorMask = colorMask;
  47527. }
  47528. },
  47529. setLocked: function ( lock ) {
  47530. locked = lock;
  47531. },
  47532. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  47533. if ( premultipliedAlpha === true ) {
  47534. r *= a; g *= a; b *= a;
  47535. }
  47536. color.set( r, g, b, a );
  47537. if ( currentColorClear.equals( color ) === false ) {
  47538. gl.clearColor( r, g, b, a );
  47539. currentColorClear.copy( color );
  47540. }
  47541. },
  47542. reset: function () {
  47543. locked = false;
  47544. currentColorMask = null;
  47545. currentColorClear.set( -1, 0, 0, 0 ); // set to invalid state
  47546. }
  47547. };
  47548. }
  47549. function DepthBuffer() {
  47550. let locked = false;
  47551. let currentReversed = false;
  47552. let currentDepthMask = null;
  47553. let currentDepthFunc = null;
  47554. let currentDepthClear = null;
  47555. return {
  47556. setReversed: function ( reversed ) {
  47557. if ( currentReversed !== reversed ) {
  47558. const ext = extensions.get( 'EXT_clip_control' );
  47559. if ( reversed ) {
  47560. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT );
  47561. } else {
  47562. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT );
  47563. }
  47564. currentReversed = reversed;
  47565. const oldDepth = currentDepthClear;
  47566. currentDepthClear = null;
  47567. this.setClear( oldDepth );
  47568. }
  47569. },
  47570. getReversed: function () {
  47571. return currentReversed;
  47572. },
  47573. setTest: function ( depthTest ) {
  47574. if ( depthTest ) {
  47575. enable( gl.DEPTH_TEST );
  47576. } else {
  47577. disable( gl.DEPTH_TEST );
  47578. }
  47579. },
  47580. setMask: function ( depthMask ) {
  47581. if ( currentDepthMask !== depthMask && ! locked ) {
  47582. gl.depthMask( depthMask );
  47583. currentDepthMask = depthMask;
  47584. }
  47585. },
  47586. setFunc: function ( depthFunc ) {
  47587. if ( currentReversed ) depthFunc = reversedFuncs[ depthFunc ];
  47588. if ( currentDepthFunc !== depthFunc ) {
  47589. switch ( depthFunc ) {
  47590. case NeverDepth:
  47591. gl.depthFunc( gl.NEVER );
  47592. break;
  47593. case AlwaysDepth:
  47594. gl.depthFunc( gl.ALWAYS );
  47595. break;
  47596. case LessDepth:
  47597. gl.depthFunc( gl.LESS );
  47598. break;
  47599. case LessEqualDepth:
  47600. gl.depthFunc( gl.LEQUAL );
  47601. break;
  47602. case EqualDepth:
  47603. gl.depthFunc( gl.EQUAL );
  47604. break;
  47605. case GreaterEqualDepth:
  47606. gl.depthFunc( gl.GEQUAL );
  47607. break;
  47608. case GreaterDepth:
  47609. gl.depthFunc( gl.GREATER );
  47610. break;
  47611. case NotEqualDepth:
  47612. gl.depthFunc( gl.NOTEQUAL );
  47613. break;
  47614. default:
  47615. gl.depthFunc( gl.LEQUAL );
  47616. }
  47617. currentDepthFunc = depthFunc;
  47618. }
  47619. },
  47620. setLocked: function ( lock ) {
  47621. locked = lock;
  47622. },
  47623. setClear: function ( depth ) {
  47624. if ( currentDepthClear !== depth ) {
  47625. if ( currentReversed ) {
  47626. depth = 1 - depth;
  47627. }
  47628. gl.clearDepth( depth );
  47629. currentDepthClear = depth;
  47630. }
  47631. },
  47632. reset: function () {
  47633. locked = false;
  47634. currentDepthMask = null;
  47635. currentDepthFunc = null;
  47636. currentDepthClear = null;
  47637. currentReversed = false;
  47638. }
  47639. };
  47640. }
  47641. function StencilBuffer() {
  47642. let locked = false;
  47643. let currentStencilMask = null;
  47644. let currentStencilFunc = null;
  47645. let currentStencilRef = null;
  47646. let currentStencilFuncMask = null;
  47647. let currentStencilFail = null;
  47648. let currentStencilZFail = null;
  47649. let currentStencilZPass = null;
  47650. let currentStencilClear = null;
  47651. return {
  47652. setTest: function ( stencilTest ) {
  47653. if ( ! locked ) {
  47654. if ( stencilTest ) {
  47655. enable( gl.STENCIL_TEST );
  47656. } else {
  47657. disable( gl.STENCIL_TEST );
  47658. }
  47659. }
  47660. },
  47661. setMask: function ( stencilMask ) {
  47662. if ( currentStencilMask !== stencilMask && ! locked ) {
  47663. gl.stencilMask( stencilMask );
  47664. currentStencilMask = stencilMask;
  47665. }
  47666. },
  47667. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  47668. if ( currentStencilFunc !== stencilFunc ||
  47669. currentStencilRef !== stencilRef ||
  47670. currentStencilFuncMask !== stencilMask ) {
  47671. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  47672. currentStencilFunc = stencilFunc;
  47673. currentStencilRef = stencilRef;
  47674. currentStencilFuncMask = stencilMask;
  47675. }
  47676. },
  47677. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  47678. if ( currentStencilFail !== stencilFail ||
  47679. currentStencilZFail !== stencilZFail ||
  47680. currentStencilZPass !== stencilZPass ) {
  47681. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  47682. currentStencilFail = stencilFail;
  47683. currentStencilZFail = stencilZFail;
  47684. currentStencilZPass = stencilZPass;
  47685. }
  47686. },
  47687. setLocked: function ( lock ) {
  47688. locked = lock;
  47689. },
  47690. setClear: function ( stencil ) {
  47691. if ( currentStencilClear !== stencil ) {
  47692. gl.clearStencil( stencil );
  47693. currentStencilClear = stencil;
  47694. }
  47695. },
  47696. reset: function () {
  47697. locked = false;
  47698. currentStencilMask = null;
  47699. currentStencilFunc = null;
  47700. currentStencilRef = null;
  47701. currentStencilFuncMask = null;
  47702. currentStencilFail = null;
  47703. currentStencilZFail = null;
  47704. currentStencilZPass = null;
  47705. currentStencilClear = null;
  47706. }
  47707. };
  47708. }
  47709. //
  47710. const colorBuffer = new ColorBuffer();
  47711. const depthBuffer = new DepthBuffer();
  47712. const stencilBuffer = new StencilBuffer();
  47713. const uboBindings = new WeakMap();
  47714. const uboProgramMap = new WeakMap();
  47715. let enabledCapabilities = {};
  47716. let currentBoundFramebuffers = {};
  47717. let currentDrawbuffers = new WeakMap();
  47718. let defaultDrawbuffers = [];
  47719. let currentProgram = null;
  47720. let currentBlendingEnabled = false;
  47721. let currentBlending = null;
  47722. let currentBlendEquation = null;
  47723. let currentBlendSrc = null;
  47724. let currentBlendDst = null;
  47725. let currentBlendEquationAlpha = null;
  47726. let currentBlendSrcAlpha = null;
  47727. let currentBlendDstAlpha = null;
  47728. let currentBlendColor = new Color( 0, 0, 0 );
  47729. let currentBlendAlpha = 0;
  47730. let currentPremultipledAlpha = false;
  47731. let currentFlipSided = null;
  47732. let currentCullFace = null;
  47733. let currentLineWidth = null;
  47734. let currentPolygonOffsetFactor = null;
  47735. let currentPolygonOffsetUnits = null;
  47736. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  47737. let lineWidthAvailable = false;
  47738. let version = 0;
  47739. const glVersion = gl.getParameter( gl.VERSION );
  47740. if ( glVersion.indexOf( 'WebGL' ) !== -1 ) {
  47741. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  47742. lineWidthAvailable = ( version >= 1.0 );
  47743. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== -1 ) {
  47744. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  47745. lineWidthAvailable = ( version >= 2.0 );
  47746. }
  47747. let currentTextureSlot = null;
  47748. let currentBoundTextures = {};
  47749. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  47750. const viewportParam = gl.getParameter( gl.VIEWPORT );
  47751. const currentScissor = new Vector4().fromArray( scissorParam );
  47752. const currentViewport = new Vector4().fromArray( viewportParam );
  47753. function createTexture( type, target, count, dimensions ) {
  47754. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  47755. const texture = gl.createTexture();
  47756. gl.bindTexture( type, texture );
  47757. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  47758. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  47759. for ( let i = 0; i < count; i ++ ) {
  47760. if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) {
  47761. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  47762. } else {
  47763. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  47764. }
  47765. }
  47766. return texture;
  47767. }
  47768. const emptyTextures = {};
  47769. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  47770. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  47771. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  47772. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  47773. // init
  47774. colorBuffer.setClear( 0, 0, 0, 1 );
  47775. depthBuffer.setClear( 1 );
  47776. stencilBuffer.setClear( 0 );
  47777. enable( gl.DEPTH_TEST );
  47778. depthBuffer.setFunc( LessEqualDepth );
  47779. setFlipSided( false );
  47780. setCullFace( CullFaceBack );
  47781. enable( gl.CULL_FACE );
  47782. setBlending( NoBlending );
  47783. //
  47784. function enable( id ) {
  47785. if ( enabledCapabilities[ id ] !== true ) {
  47786. gl.enable( id );
  47787. enabledCapabilities[ id ] = true;
  47788. }
  47789. }
  47790. function disable( id ) {
  47791. if ( enabledCapabilities[ id ] !== false ) {
  47792. gl.disable( id );
  47793. enabledCapabilities[ id ] = false;
  47794. }
  47795. }
  47796. function bindFramebuffer( target, framebuffer ) {
  47797. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  47798. gl.bindFramebuffer( target, framebuffer );
  47799. currentBoundFramebuffers[ target ] = framebuffer;
  47800. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  47801. if ( target === gl.DRAW_FRAMEBUFFER ) {
  47802. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  47803. }
  47804. if ( target === gl.FRAMEBUFFER ) {
  47805. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  47806. }
  47807. return true;
  47808. }
  47809. return false;
  47810. }
  47811. function drawBuffers( renderTarget, framebuffer ) {
  47812. let drawBuffers = defaultDrawbuffers;
  47813. let needsUpdate = false;
  47814. if ( renderTarget ) {
  47815. drawBuffers = currentDrawbuffers.get( framebuffer );
  47816. if ( drawBuffers === undefined ) {
  47817. drawBuffers = [];
  47818. currentDrawbuffers.set( framebuffer, drawBuffers );
  47819. }
  47820. const textures = renderTarget.textures;
  47821. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  47822. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  47823. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  47824. }
  47825. drawBuffers.length = textures.length;
  47826. needsUpdate = true;
  47827. }
  47828. } else {
  47829. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  47830. drawBuffers[ 0 ] = gl.BACK;
  47831. needsUpdate = true;
  47832. }
  47833. }
  47834. if ( needsUpdate ) {
  47835. gl.drawBuffers( drawBuffers );
  47836. }
  47837. }
  47838. function useProgram( program ) {
  47839. if ( currentProgram !== program ) {
  47840. gl.useProgram( program );
  47841. currentProgram = program;
  47842. return true;
  47843. }
  47844. return false;
  47845. }
  47846. const equationToGL = {
  47847. [ AddEquation ]: gl.FUNC_ADD,
  47848. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  47849. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  47850. };
  47851. equationToGL[ MinEquation ] = gl.MIN;
  47852. equationToGL[ MaxEquation ] = gl.MAX;
  47853. const factorToGL = {
  47854. [ ZeroFactor ]: gl.ZERO,
  47855. [ OneFactor ]: gl.ONE,
  47856. [ SrcColorFactor ]: gl.SRC_COLOR,
  47857. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  47858. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  47859. [ DstColorFactor ]: gl.DST_COLOR,
  47860. [ DstAlphaFactor ]: gl.DST_ALPHA,
  47861. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  47862. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  47863. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  47864. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  47865. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  47866. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  47867. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  47868. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  47869. };
  47870. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  47871. if ( blending === NoBlending ) {
  47872. if ( currentBlendingEnabled === true ) {
  47873. disable( gl.BLEND );
  47874. currentBlendingEnabled = false;
  47875. }
  47876. return;
  47877. }
  47878. if ( currentBlendingEnabled === false ) {
  47879. enable( gl.BLEND );
  47880. currentBlendingEnabled = true;
  47881. }
  47882. if ( blending !== CustomBlending ) {
  47883. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  47884. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  47885. gl.blendEquation( gl.FUNC_ADD );
  47886. currentBlendEquation = AddEquation;
  47887. currentBlendEquationAlpha = AddEquation;
  47888. }
  47889. if ( premultipliedAlpha ) {
  47890. switch ( blending ) {
  47891. case NormalBlending:
  47892. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  47893. break;
  47894. case AdditiveBlending:
  47895. gl.blendFunc( gl.ONE, gl.ONE );
  47896. break;
  47897. case SubtractiveBlending:
  47898. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  47899. break;
  47900. case MultiplyBlending:
  47901. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  47902. break;
  47903. default:
  47904. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  47905. break;
  47906. }
  47907. } else {
  47908. switch ( blending ) {
  47909. case NormalBlending:
  47910. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  47911. break;
  47912. case AdditiveBlending:
  47913. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  47914. break;
  47915. case SubtractiveBlending:
  47916. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  47917. break;
  47918. case MultiplyBlending:
  47919. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  47920. break;
  47921. default:
  47922. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  47923. break;
  47924. }
  47925. }
  47926. currentBlendSrc = null;
  47927. currentBlendDst = null;
  47928. currentBlendSrcAlpha = null;
  47929. currentBlendDstAlpha = null;
  47930. currentBlendColor.set( 0, 0, 0 );
  47931. currentBlendAlpha = 0;
  47932. currentBlending = blending;
  47933. currentPremultipledAlpha = premultipliedAlpha;
  47934. }
  47935. return;
  47936. }
  47937. // custom blending
  47938. blendEquationAlpha = blendEquationAlpha || blendEquation;
  47939. blendSrcAlpha = blendSrcAlpha || blendSrc;
  47940. blendDstAlpha = blendDstAlpha || blendDst;
  47941. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  47942. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  47943. currentBlendEquation = blendEquation;
  47944. currentBlendEquationAlpha = blendEquationAlpha;
  47945. }
  47946. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  47947. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  47948. currentBlendSrc = blendSrc;
  47949. currentBlendDst = blendDst;
  47950. currentBlendSrcAlpha = blendSrcAlpha;
  47951. currentBlendDstAlpha = blendDstAlpha;
  47952. }
  47953. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  47954. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  47955. currentBlendColor.copy( blendColor );
  47956. currentBlendAlpha = blendAlpha;
  47957. }
  47958. currentBlending = blending;
  47959. currentPremultipledAlpha = false;
  47960. }
  47961. function setMaterial( material, frontFaceCW ) {
  47962. material.side === DoubleSide
  47963. ? disable( gl.CULL_FACE )
  47964. : enable( gl.CULL_FACE );
  47965. let flipSided = ( material.side === BackSide );
  47966. if ( frontFaceCW ) flipSided = ! flipSided;
  47967. setFlipSided( flipSided );
  47968. ( material.blending === NormalBlending && material.transparent === false )
  47969. ? setBlending( NoBlending )
  47970. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  47971. depthBuffer.setFunc( material.depthFunc );
  47972. depthBuffer.setTest( material.depthTest );
  47973. depthBuffer.setMask( material.depthWrite );
  47974. colorBuffer.setMask( material.colorWrite );
  47975. const stencilWrite = material.stencilWrite;
  47976. stencilBuffer.setTest( stencilWrite );
  47977. if ( stencilWrite ) {
  47978. stencilBuffer.setMask( material.stencilWriteMask );
  47979. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  47980. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  47981. }
  47982. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  47983. material.alphaToCoverage === true
  47984. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  47985. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  47986. }
  47987. //
  47988. function setFlipSided( flipSided ) {
  47989. if ( currentFlipSided !== flipSided ) {
  47990. if ( flipSided ) {
  47991. gl.frontFace( gl.CW );
  47992. } else {
  47993. gl.frontFace( gl.CCW );
  47994. }
  47995. currentFlipSided = flipSided;
  47996. }
  47997. }
  47998. function setCullFace( cullFace ) {
  47999. if ( cullFace !== CullFaceNone ) {
  48000. enable( gl.CULL_FACE );
  48001. if ( cullFace !== currentCullFace ) {
  48002. if ( cullFace === CullFaceBack ) {
  48003. gl.cullFace( gl.BACK );
  48004. } else if ( cullFace === CullFaceFront ) {
  48005. gl.cullFace( gl.FRONT );
  48006. } else {
  48007. gl.cullFace( gl.FRONT_AND_BACK );
  48008. }
  48009. }
  48010. } else {
  48011. disable( gl.CULL_FACE );
  48012. }
  48013. currentCullFace = cullFace;
  48014. }
  48015. function setLineWidth( width ) {
  48016. if ( width !== currentLineWidth ) {
  48017. if ( lineWidthAvailable ) gl.lineWidth( width );
  48018. currentLineWidth = width;
  48019. }
  48020. }
  48021. function setPolygonOffset( polygonOffset, factor, units ) {
  48022. if ( polygonOffset ) {
  48023. enable( gl.POLYGON_OFFSET_FILL );
  48024. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  48025. gl.polygonOffset( factor, units );
  48026. currentPolygonOffsetFactor = factor;
  48027. currentPolygonOffsetUnits = units;
  48028. }
  48029. } else {
  48030. disable( gl.POLYGON_OFFSET_FILL );
  48031. }
  48032. }
  48033. function setScissorTest( scissorTest ) {
  48034. if ( scissorTest ) {
  48035. enable( gl.SCISSOR_TEST );
  48036. } else {
  48037. disable( gl.SCISSOR_TEST );
  48038. }
  48039. }
  48040. // texture
  48041. function activeTexture( webglSlot ) {
  48042. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  48043. if ( currentTextureSlot !== webglSlot ) {
  48044. gl.activeTexture( webglSlot );
  48045. currentTextureSlot = webglSlot;
  48046. }
  48047. }
  48048. function bindTexture( webglType, webglTexture, webglSlot ) {
  48049. if ( webglSlot === undefined ) {
  48050. if ( currentTextureSlot === null ) {
  48051. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  48052. } else {
  48053. webglSlot = currentTextureSlot;
  48054. }
  48055. }
  48056. let boundTexture = currentBoundTextures[ webglSlot ];
  48057. if ( boundTexture === undefined ) {
  48058. boundTexture = { type: undefined, texture: undefined };
  48059. currentBoundTextures[ webglSlot ] = boundTexture;
  48060. }
  48061. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  48062. if ( currentTextureSlot !== webglSlot ) {
  48063. gl.activeTexture( webglSlot );
  48064. currentTextureSlot = webglSlot;
  48065. }
  48066. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  48067. boundTexture.type = webglType;
  48068. boundTexture.texture = webglTexture;
  48069. }
  48070. }
  48071. function unbindTexture() {
  48072. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  48073. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  48074. gl.bindTexture( boundTexture.type, null );
  48075. boundTexture.type = undefined;
  48076. boundTexture.texture = undefined;
  48077. }
  48078. }
  48079. function compressedTexImage2D() {
  48080. try {
  48081. gl.compressedTexImage2D( ...arguments );
  48082. } catch ( error ) {
  48083. console.error( 'THREE.WebGLState:', error );
  48084. }
  48085. }
  48086. function compressedTexImage3D() {
  48087. try {
  48088. gl.compressedTexImage3D( ...arguments );
  48089. } catch ( error ) {
  48090. console.error( 'THREE.WebGLState:', error );
  48091. }
  48092. }
  48093. function texSubImage2D() {
  48094. try {
  48095. gl.texSubImage2D( ...arguments );
  48096. } catch ( error ) {
  48097. console.error( 'THREE.WebGLState:', error );
  48098. }
  48099. }
  48100. function texSubImage3D() {
  48101. try {
  48102. gl.texSubImage3D( ...arguments );
  48103. } catch ( error ) {
  48104. console.error( 'THREE.WebGLState:', error );
  48105. }
  48106. }
  48107. function compressedTexSubImage2D() {
  48108. try {
  48109. gl.compressedTexSubImage2D( ...arguments );
  48110. } catch ( error ) {
  48111. console.error( 'THREE.WebGLState:', error );
  48112. }
  48113. }
  48114. function compressedTexSubImage3D() {
  48115. try {
  48116. gl.compressedTexSubImage3D( ...arguments );
  48117. } catch ( error ) {
  48118. console.error( 'THREE.WebGLState:', error );
  48119. }
  48120. }
  48121. function texStorage2D() {
  48122. try {
  48123. gl.texStorage2D( ...arguments );
  48124. } catch ( error ) {
  48125. console.error( 'THREE.WebGLState:', error );
  48126. }
  48127. }
  48128. function texStorage3D() {
  48129. try {
  48130. gl.texStorage3D( ...arguments );
  48131. } catch ( error ) {
  48132. console.error( 'THREE.WebGLState:', error );
  48133. }
  48134. }
  48135. function texImage2D() {
  48136. try {
  48137. gl.texImage2D( ...arguments );
  48138. } catch ( error ) {
  48139. console.error( 'THREE.WebGLState:', error );
  48140. }
  48141. }
  48142. function texImage3D() {
  48143. try {
  48144. gl.texImage3D( ...arguments );
  48145. } catch ( error ) {
  48146. console.error( 'THREE.WebGLState:', error );
  48147. }
  48148. }
  48149. //
  48150. function scissor( scissor ) {
  48151. if ( currentScissor.equals( scissor ) === false ) {
  48152. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  48153. currentScissor.copy( scissor );
  48154. }
  48155. }
  48156. function viewport( viewport ) {
  48157. if ( currentViewport.equals( viewport ) === false ) {
  48158. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  48159. currentViewport.copy( viewport );
  48160. }
  48161. }
  48162. function updateUBOMapping( uniformsGroup, program ) {
  48163. let mapping = uboProgramMap.get( program );
  48164. if ( mapping === undefined ) {
  48165. mapping = new WeakMap();
  48166. uboProgramMap.set( program, mapping );
  48167. }
  48168. let blockIndex = mapping.get( uniformsGroup );
  48169. if ( blockIndex === undefined ) {
  48170. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  48171. mapping.set( uniformsGroup, blockIndex );
  48172. }
  48173. }
  48174. function uniformBlockBinding( uniformsGroup, program ) {
  48175. const mapping = uboProgramMap.get( program );
  48176. const blockIndex = mapping.get( uniformsGroup );
  48177. if ( uboBindings.get( program ) !== blockIndex ) {
  48178. // bind shader specific block index to global block point
  48179. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  48180. uboBindings.set( program, blockIndex );
  48181. }
  48182. }
  48183. //
  48184. function reset() {
  48185. // reset state
  48186. gl.disable( gl.BLEND );
  48187. gl.disable( gl.CULL_FACE );
  48188. gl.disable( gl.DEPTH_TEST );
  48189. gl.disable( gl.POLYGON_OFFSET_FILL );
  48190. gl.disable( gl.SCISSOR_TEST );
  48191. gl.disable( gl.STENCIL_TEST );
  48192. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  48193. gl.blendEquation( gl.FUNC_ADD );
  48194. gl.blendFunc( gl.ONE, gl.ZERO );
  48195. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  48196. gl.blendColor( 0, 0, 0, 0 );
  48197. gl.colorMask( true, true, true, true );
  48198. gl.clearColor( 0, 0, 0, 0 );
  48199. gl.depthMask( true );
  48200. gl.depthFunc( gl.LESS );
  48201. depthBuffer.setReversed( false );
  48202. gl.clearDepth( 1 );
  48203. gl.stencilMask( 0xffffffff );
  48204. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  48205. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  48206. gl.clearStencil( 0 );
  48207. gl.cullFace( gl.BACK );
  48208. gl.frontFace( gl.CCW );
  48209. gl.polygonOffset( 0, 0 );
  48210. gl.activeTexture( gl.TEXTURE0 );
  48211. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  48212. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  48213. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  48214. gl.useProgram( null );
  48215. gl.lineWidth( 1 );
  48216. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  48217. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  48218. // reset internals
  48219. enabledCapabilities = {};
  48220. currentTextureSlot = null;
  48221. currentBoundTextures = {};
  48222. currentBoundFramebuffers = {};
  48223. currentDrawbuffers = new WeakMap();
  48224. defaultDrawbuffers = [];
  48225. currentProgram = null;
  48226. currentBlendingEnabled = false;
  48227. currentBlending = null;
  48228. currentBlendEquation = null;
  48229. currentBlendSrc = null;
  48230. currentBlendDst = null;
  48231. currentBlendEquationAlpha = null;
  48232. currentBlendSrcAlpha = null;
  48233. currentBlendDstAlpha = null;
  48234. currentBlendColor = new Color( 0, 0, 0 );
  48235. currentBlendAlpha = 0;
  48236. currentPremultipledAlpha = false;
  48237. currentFlipSided = null;
  48238. currentCullFace = null;
  48239. currentLineWidth = null;
  48240. currentPolygonOffsetFactor = null;
  48241. currentPolygonOffsetUnits = null;
  48242. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  48243. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  48244. colorBuffer.reset();
  48245. depthBuffer.reset();
  48246. stencilBuffer.reset();
  48247. }
  48248. return {
  48249. buffers: {
  48250. color: colorBuffer,
  48251. depth: depthBuffer,
  48252. stencil: stencilBuffer
  48253. },
  48254. enable: enable,
  48255. disable: disable,
  48256. bindFramebuffer: bindFramebuffer,
  48257. drawBuffers: drawBuffers,
  48258. useProgram: useProgram,
  48259. setBlending: setBlending,
  48260. setMaterial: setMaterial,
  48261. setFlipSided: setFlipSided,
  48262. setCullFace: setCullFace,
  48263. setLineWidth: setLineWidth,
  48264. setPolygonOffset: setPolygonOffset,
  48265. setScissorTest: setScissorTest,
  48266. activeTexture: activeTexture,
  48267. bindTexture: bindTexture,
  48268. unbindTexture: unbindTexture,
  48269. compressedTexImage2D: compressedTexImage2D,
  48270. compressedTexImage3D: compressedTexImage3D,
  48271. texImage2D: texImage2D,
  48272. texImage3D: texImage3D,
  48273. updateUBOMapping: updateUBOMapping,
  48274. uniformBlockBinding: uniformBlockBinding,
  48275. texStorage2D: texStorage2D,
  48276. texStorage3D: texStorage3D,
  48277. texSubImage2D: texSubImage2D,
  48278. texSubImage3D: texSubImage3D,
  48279. compressedTexSubImage2D: compressedTexSubImage2D,
  48280. compressedTexSubImage3D: compressedTexSubImage3D,
  48281. scissor: scissor,
  48282. viewport: viewport,
  48283. reset: reset
  48284. };
  48285. }
  48286. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  48287. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  48288. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  48289. const _imageDimensions = new Vector2();
  48290. const _videoTextures = new WeakMap();
  48291. let _canvas;
  48292. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  48293. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  48294. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  48295. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  48296. let useOffscreenCanvas = false;
  48297. try {
  48298. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  48299. // eslint-disable-next-line compat/compat
  48300. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  48301. } catch ( err ) {
  48302. // Ignore any errors
  48303. }
  48304. function createCanvas( width, height ) {
  48305. // Use OffscreenCanvas when available. Specially needed in web workers
  48306. return useOffscreenCanvas ?
  48307. // eslint-disable-next-line compat/compat
  48308. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  48309. }
  48310. function resizeImage( image, needsNewCanvas, maxSize ) {
  48311. let scale = 1;
  48312. const dimensions = getDimensions( image );
  48313. // handle case if texture exceeds max size
  48314. if ( dimensions.width > maxSize || dimensions.height > maxSize ) {
  48315. scale = maxSize / Math.max( dimensions.width, dimensions.height );
  48316. }
  48317. // only perform resize if necessary
  48318. if ( scale < 1 ) {
  48319. // only perform resize for certain image types
  48320. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  48321. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  48322. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  48323. ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) {
  48324. const width = Math.floor( scale * dimensions.width );
  48325. const height = Math.floor( scale * dimensions.height );
  48326. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  48327. // cube textures can't reuse the same canvas
  48328. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  48329. canvas.width = width;
  48330. canvas.height = height;
  48331. const context = canvas.getContext( '2d' );
  48332. context.drawImage( image, 0, 0, width, height );
  48333. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' );
  48334. return canvas;
  48335. } else {
  48336. if ( 'data' in image ) {
  48337. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' );
  48338. }
  48339. return image;
  48340. }
  48341. }
  48342. return image;
  48343. }
  48344. function textureNeedsGenerateMipmaps( texture ) {
  48345. return texture.generateMipmaps;
  48346. }
  48347. function generateMipmap( target ) {
  48348. _gl.generateMipmap( target );
  48349. }
  48350. function getTargetType( texture ) {
  48351. if ( texture.isWebGLCubeRenderTarget ) return _gl.TEXTURE_CUBE_MAP;
  48352. if ( texture.isWebGL3DRenderTarget ) return _gl.TEXTURE_3D;
  48353. if ( texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture ) return _gl.TEXTURE_2D_ARRAY;
  48354. return _gl.TEXTURE_2D;
  48355. }
  48356. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  48357. if ( internalFormatName !== null ) {
  48358. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  48359. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  48360. }
  48361. let internalFormat = glFormat;
  48362. if ( glFormat === _gl.RED ) {
  48363. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  48364. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  48365. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  48366. }
  48367. if ( glFormat === _gl.RED_INTEGER ) {
  48368. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  48369. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  48370. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  48371. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  48372. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  48373. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  48374. }
  48375. if ( glFormat === _gl.RG ) {
  48376. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  48377. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  48378. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  48379. }
  48380. if ( glFormat === _gl.RG_INTEGER ) {
  48381. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI;
  48382. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI;
  48383. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI;
  48384. if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I;
  48385. if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I;
  48386. if ( glType === _gl.INT ) internalFormat = _gl.RG32I;
  48387. }
  48388. if ( glFormat === _gl.RGB_INTEGER ) {
  48389. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGB8UI;
  48390. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGB16UI;
  48391. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGB32UI;
  48392. if ( glType === _gl.BYTE ) internalFormat = _gl.RGB8I;
  48393. if ( glType === _gl.SHORT ) internalFormat = _gl.RGB16I;
  48394. if ( glType === _gl.INT ) internalFormat = _gl.RGB32I;
  48395. }
  48396. if ( glFormat === _gl.RGBA_INTEGER ) {
  48397. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGBA8UI;
  48398. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGBA16UI;
  48399. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGBA32UI;
  48400. if ( glType === _gl.BYTE ) internalFormat = _gl.RGBA8I;
  48401. if ( glType === _gl.SHORT ) internalFormat = _gl.RGBA16I;
  48402. if ( glType === _gl.INT ) internalFormat = _gl.RGBA32I;
  48403. }
  48404. if ( glFormat === _gl.RGB ) {
  48405. if ( glType === _gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = _gl.RGB9_E5;
  48406. }
  48407. if ( glFormat === _gl.RGBA ) {
  48408. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  48409. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  48410. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  48411. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  48412. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  48413. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  48414. }
  48415. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  48416. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  48417. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  48418. extensions.get( 'EXT_color_buffer_float' );
  48419. }
  48420. return internalFormat;
  48421. }
  48422. function getInternalDepthFormat( useStencil, depthType ) {
  48423. let glInternalFormat;
  48424. if ( useStencil ) {
  48425. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  48426. glInternalFormat = _gl.DEPTH24_STENCIL8;
  48427. } else if ( depthType === FloatType ) {
  48428. glInternalFormat = _gl.DEPTH32F_STENCIL8;
  48429. } else if ( depthType === UnsignedShortType ) {
  48430. glInternalFormat = _gl.DEPTH24_STENCIL8;
  48431. console.warn( 'DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.' );
  48432. }
  48433. } else {
  48434. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  48435. glInternalFormat = _gl.DEPTH_COMPONENT24;
  48436. } else if ( depthType === FloatType ) {
  48437. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  48438. } else if ( depthType === UnsignedShortType ) {
  48439. glInternalFormat = _gl.DEPTH_COMPONENT16;
  48440. }
  48441. }
  48442. return glInternalFormat;
  48443. }
  48444. function getMipLevels( texture, image ) {
  48445. if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  48446. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  48447. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  48448. // user-defined mipmaps
  48449. return texture.mipmaps.length;
  48450. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  48451. return image.mipmaps.length;
  48452. } else {
  48453. // texture without mipmaps (only base level)
  48454. return 1;
  48455. }
  48456. }
  48457. //
  48458. function onTextureDispose( event ) {
  48459. const texture = event.target;
  48460. texture.removeEventListener( 'dispose', onTextureDispose );
  48461. deallocateTexture( texture );
  48462. if ( texture.isVideoTexture ) {
  48463. _videoTextures.delete( texture );
  48464. }
  48465. }
  48466. function onRenderTargetDispose( event ) {
  48467. const renderTarget = event.target;
  48468. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  48469. deallocateRenderTarget( renderTarget );
  48470. }
  48471. //
  48472. function deallocateTexture( texture ) {
  48473. const textureProperties = properties.get( texture );
  48474. if ( textureProperties.__webglInit === undefined ) return;
  48475. // check if it's necessary to remove the WebGLTexture object
  48476. const source = texture.source;
  48477. const webglTextures = _sources.get( source );
  48478. if ( webglTextures ) {
  48479. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  48480. webglTexture.usedTimes --;
  48481. // the WebGLTexture object is not used anymore, remove it
  48482. if ( webglTexture.usedTimes === 0 ) {
  48483. deleteTexture( texture );
  48484. }
  48485. // remove the weak map entry if no WebGLTexture uses the source anymore
  48486. if ( Object.keys( webglTextures ).length === 0 ) {
  48487. _sources.delete( source );
  48488. }
  48489. }
  48490. properties.remove( texture );
  48491. }
  48492. function deleteTexture( texture ) {
  48493. const textureProperties = properties.get( texture );
  48494. _gl.deleteTexture( textureProperties.__webglTexture );
  48495. const source = texture.source;
  48496. const webglTextures = _sources.get( source );
  48497. delete webglTextures[ textureProperties.__cacheKey ];
  48498. info.memory.textures --;
  48499. }
  48500. function deallocateRenderTarget( renderTarget ) {
  48501. const renderTargetProperties = properties.get( renderTarget );
  48502. if ( renderTarget.depthTexture ) {
  48503. renderTarget.depthTexture.dispose();
  48504. properties.remove( renderTarget.depthTexture );
  48505. }
  48506. if ( renderTarget.isWebGLCubeRenderTarget ) {
  48507. for ( let i = 0; i < 6; i ++ ) {
  48508. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  48509. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  48510. } else {
  48511. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  48512. }
  48513. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  48514. }
  48515. } else {
  48516. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  48517. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  48518. } else {
  48519. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  48520. }
  48521. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  48522. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  48523. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  48524. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  48525. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  48526. }
  48527. }
  48528. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  48529. }
  48530. const textures = renderTarget.textures;
  48531. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  48532. const attachmentProperties = properties.get( textures[ i ] );
  48533. if ( attachmentProperties.__webglTexture ) {
  48534. _gl.deleteTexture( attachmentProperties.__webglTexture );
  48535. info.memory.textures --;
  48536. }
  48537. properties.remove( textures[ i ] );
  48538. }
  48539. properties.remove( renderTarget );
  48540. }
  48541. //
  48542. let textureUnits = 0;
  48543. function resetTextureUnits() {
  48544. textureUnits = 0;
  48545. }
  48546. function allocateTextureUnit() {
  48547. const textureUnit = textureUnits;
  48548. if ( textureUnit >= capabilities.maxTextures ) {
  48549. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  48550. }
  48551. textureUnits += 1;
  48552. return textureUnit;
  48553. }
  48554. function getTextureCacheKey( texture ) {
  48555. const array = [];
  48556. array.push( texture.wrapS );
  48557. array.push( texture.wrapT );
  48558. array.push( texture.wrapR || 0 );
  48559. array.push( texture.magFilter );
  48560. array.push( texture.minFilter );
  48561. array.push( texture.anisotropy );
  48562. array.push( texture.internalFormat );
  48563. array.push( texture.format );
  48564. array.push( texture.type );
  48565. array.push( texture.generateMipmaps );
  48566. array.push( texture.premultiplyAlpha );
  48567. array.push( texture.flipY );
  48568. array.push( texture.unpackAlignment );
  48569. array.push( texture.colorSpace );
  48570. return array.join();
  48571. }
  48572. //
  48573. function setTexture2D( texture, slot ) {
  48574. const textureProperties = properties.get( texture );
  48575. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  48576. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  48577. const image = texture.image;
  48578. if ( image === null ) {
  48579. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  48580. } else if ( image.complete === false ) {
  48581. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  48582. } else {
  48583. uploadTexture( textureProperties, texture, slot );
  48584. return;
  48585. }
  48586. }
  48587. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  48588. }
  48589. function setTexture2DArray( texture, slot ) {
  48590. const textureProperties = properties.get( texture );
  48591. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  48592. uploadTexture( textureProperties, texture, slot );
  48593. return;
  48594. }
  48595. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  48596. }
  48597. function setTexture3D( texture, slot ) {
  48598. const textureProperties = properties.get( texture );
  48599. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  48600. uploadTexture( textureProperties, texture, slot );
  48601. return;
  48602. }
  48603. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  48604. }
  48605. function setTextureCube( texture, slot ) {
  48606. const textureProperties = properties.get( texture );
  48607. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  48608. uploadCubeTexture( textureProperties, texture, slot );
  48609. return;
  48610. }
  48611. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  48612. }
  48613. const wrappingToGL = {
  48614. [ RepeatWrapping ]: _gl.REPEAT,
  48615. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  48616. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  48617. };
  48618. const filterToGL = {
  48619. [ NearestFilter ]: _gl.NEAREST,
  48620. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  48621. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  48622. [ LinearFilter ]: _gl.LINEAR,
  48623. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  48624. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  48625. };
  48626. const compareToGL = {
  48627. [ NeverCompare ]: _gl.NEVER,
  48628. [ AlwaysCompare ]: _gl.ALWAYS,
  48629. [ LessCompare ]: _gl.LESS,
  48630. [ LessEqualCompare ]: _gl.LEQUAL,
  48631. [ EqualCompare ]: _gl.EQUAL,
  48632. [ GreaterEqualCompare ]: _gl.GEQUAL,
  48633. [ GreaterCompare ]: _gl.GREATER,
  48634. [ NotEqualCompare ]: _gl.NOTEQUAL
  48635. };
  48636. function setTextureParameters( textureType, texture ) {
  48637. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false &&
  48638. ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  48639. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) {
  48640. console.warn( 'THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' );
  48641. }
  48642. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  48643. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  48644. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  48645. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  48646. }
  48647. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  48648. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  48649. if ( texture.compareFunction ) {
  48650. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  48651. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  48652. }
  48653. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  48654. if ( texture.magFilter === NearestFilter ) return;
  48655. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  48656. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension
  48657. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  48658. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  48659. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  48660. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  48661. }
  48662. }
  48663. }
  48664. function initTexture( textureProperties, texture ) {
  48665. let forceUpload = false;
  48666. if ( textureProperties.__webglInit === undefined ) {
  48667. textureProperties.__webglInit = true;
  48668. texture.addEventListener( 'dispose', onTextureDispose );
  48669. }
  48670. // create Source <-> WebGLTextures mapping if necessary
  48671. const source = texture.source;
  48672. let webglTextures = _sources.get( source );
  48673. if ( webglTextures === undefined ) {
  48674. webglTextures = {};
  48675. _sources.set( source, webglTextures );
  48676. }
  48677. // check if there is already a WebGLTexture object for the given texture parameters
  48678. const textureCacheKey = getTextureCacheKey( texture );
  48679. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  48680. // if not, create a new instance of WebGLTexture
  48681. if ( webglTextures[ textureCacheKey ] === undefined ) {
  48682. // create new entry
  48683. webglTextures[ textureCacheKey ] = {
  48684. texture: _gl.createTexture(),
  48685. usedTimes: 0
  48686. };
  48687. info.memory.textures ++;
  48688. // when a new instance of WebGLTexture was created, a texture upload is required
  48689. // even if the image contents are identical
  48690. forceUpload = true;
  48691. }
  48692. webglTextures[ textureCacheKey ].usedTimes ++;
  48693. // every time the texture cache key changes, it's necessary to check if an instance of
  48694. // WebGLTexture can be deleted in order to avoid a memory leak.
  48695. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  48696. if ( webglTexture !== undefined ) {
  48697. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  48698. if ( webglTexture.usedTimes === 0 ) {
  48699. deleteTexture( texture );
  48700. }
  48701. }
  48702. // store references to cache key and WebGLTexture object
  48703. textureProperties.__cacheKey = textureCacheKey;
  48704. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  48705. }
  48706. return forceUpload;
  48707. }
  48708. function uploadTexture( textureProperties, texture, slot ) {
  48709. let textureType = _gl.TEXTURE_2D;
  48710. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  48711. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  48712. const forceUpload = initTexture( textureProperties, texture );
  48713. const source = texture.source;
  48714. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  48715. const sourceProperties = properties.get( source );
  48716. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  48717. state.activeTexture( _gl.TEXTURE0 + slot );
  48718. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  48719. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  48720. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  48721. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  48722. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  48723. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  48724. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  48725. let image = resizeImage( texture.image, false, capabilities.maxTextureSize );
  48726. image = verifyColorSpace( texture, image );
  48727. const glFormat = utils.convert( texture.format, texture.colorSpace );
  48728. const glType = utils.convert( texture.type );
  48729. let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  48730. setTextureParameters( textureType, texture );
  48731. let mipmap;
  48732. const mipmaps = texture.mipmaps;
  48733. const useTexStorage = ( texture.isVideoTexture !== true );
  48734. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  48735. const dataReady = source.dataReady;
  48736. const levels = getMipLevels( texture, image );
  48737. if ( texture.isDepthTexture ) {
  48738. glInternalFormat = getInternalDepthFormat( texture.format === DepthStencilFormat, texture.type );
  48739. //
  48740. if ( allocateMemory ) {
  48741. if ( useTexStorage ) {
  48742. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  48743. } else {
  48744. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  48745. }
  48746. }
  48747. } else if ( texture.isDataTexture ) {
  48748. // use manually created mipmaps if available
  48749. // if there are no manual mipmaps
  48750. // set 0 level mipmap and then use GL to generate other mipmap levels
  48751. if ( mipmaps.length > 0 ) {
  48752. if ( useTexStorage && allocateMemory ) {
  48753. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  48754. }
  48755. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  48756. mipmap = mipmaps[ i ];
  48757. if ( useTexStorage ) {
  48758. if ( dataReady ) {
  48759. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  48760. }
  48761. } else {
  48762. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  48763. }
  48764. }
  48765. texture.generateMipmaps = false;
  48766. } else {
  48767. if ( useTexStorage ) {
  48768. if ( allocateMemory ) {
  48769. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  48770. }
  48771. if ( dataReady ) {
  48772. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  48773. }
  48774. } else {
  48775. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  48776. }
  48777. }
  48778. } else if ( texture.isCompressedTexture ) {
  48779. if ( texture.isCompressedArrayTexture ) {
  48780. if ( useTexStorage && allocateMemory ) {
  48781. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  48782. }
  48783. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  48784. mipmap = mipmaps[ i ];
  48785. if ( texture.format !== RGBAFormat ) {
  48786. if ( glFormat !== null ) {
  48787. if ( useTexStorage ) {
  48788. if ( dataReady ) {
  48789. if ( texture.layerUpdates.size > 0 ) {
  48790. const layerByteLength = getByteLength( mipmap.width, mipmap.height, texture.format, texture.type );
  48791. for ( const layerIndex of texture.layerUpdates ) {
  48792. const layerData = mipmap.data.subarray(
  48793. layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT,
  48794. ( layerIndex + 1 ) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT
  48795. );
  48796. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData );
  48797. }
  48798. texture.clearLayerUpdates();
  48799. } else {
  48800. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  48801. }
  48802. }
  48803. } else {
  48804. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  48805. }
  48806. } else {
  48807. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  48808. }
  48809. } else {
  48810. if ( useTexStorage ) {
  48811. if ( dataReady ) {
  48812. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  48813. }
  48814. } else {
  48815. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  48816. }
  48817. }
  48818. }
  48819. } else {
  48820. if ( useTexStorage && allocateMemory ) {
  48821. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  48822. }
  48823. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  48824. mipmap = mipmaps[ i ];
  48825. if ( texture.format !== RGBAFormat ) {
  48826. if ( glFormat !== null ) {
  48827. if ( useTexStorage ) {
  48828. if ( dataReady ) {
  48829. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  48830. }
  48831. } else {
  48832. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  48833. }
  48834. } else {
  48835. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  48836. }
  48837. } else {
  48838. if ( useTexStorage ) {
  48839. if ( dataReady ) {
  48840. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  48841. }
  48842. } else {
  48843. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  48844. }
  48845. }
  48846. }
  48847. }
  48848. } else if ( texture.isDataArrayTexture ) {
  48849. if ( useTexStorage ) {
  48850. if ( allocateMemory ) {
  48851. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  48852. }
  48853. if ( dataReady ) {
  48854. if ( texture.layerUpdates.size > 0 ) {
  48855. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  48856. for ( const layerIndex of texture.layerUpdates ) {
  48857. const layerData = image.data.subarray(
  48858. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  48859. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  48860. );
  48861. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  48862. }
  48863. texture.clearLayerUpdates();
  48864. } else {
  48865. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  48866. }
  48867. }
  48868. } else {
  48869. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  48870. }
  48871. } else if ( texture.isData3DTexture ) {
  48872. if ( useTexStorage ) {
  48873. if ( allocateMemory ) {
  48874. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  48875. }
  48876. if ( dataReady ) {
  48877. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  48878. }
  48879. } else {
  48880. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  48881. }
  48882. } else if ( texture.isFramebufferTexture ) {
  48883. if ( allocateMemory ) {
  48884. if ( useTexStorage ) {
  48885. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  48886. } else {
  48887. let width = image.width, height = image.height;
  48888. for ( let i = 0; i < levels; i ++ ) {
  48889. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  48890. width >>= 1;
  48891. height >>= 1;
  48892. }
  48893. }
  48894. }
  48895. } else {
  48896. // regular Texture (image, video, canvas)
  48897. // use manually created mipmaps if available
  48898. // if there are no manual mipmaps
  48899. // set 0 level mipmap and then use GL to generate other mipmap levels
  48900. if ( mipmaps.length > 0 ) {
  48901. if ( useTexStorage && allocateMemory ) {
  48902. const dimensions = getDimensions( mipmaps[ 0 ] );
  48903. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  48904. }
  48905. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  48906. mipmap = mipmaps[ i ];
  48907. if ( useTexStorage ) {
  48908. if ( dataReady ) {
  48909. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  48910. }
  48911. } else {
  48912. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  48913. }
  48914. }
  48915. texture.generateMipmaps = false;
  48916. } else {
  48917. if ( useTexStorage ) {
  48918. if ( allocateMemory ) {
  48919. const dimensions = getDimensions( image );
  48920. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  48921. }
  48922. if ( dataReady ) {
  48923. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  48924. }
  48925. } else {
  48926. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  48927. }
  48928. }
  48929. }
  48930. if ( textureNeedsGenerateMipmaps( texture ) ) {
  48931. generateMipmap( textureType );
  48932. }
  48933. sourceProperties.__version = source.version;
  48934. if ( texture.onUpdate ) texture.onUpdate( texture );
  48935. }
  48936. textureProperties.__version = texture.version;
  48937. }
  48938. function uploadCubeTexture( textureProperties, texture, slot ) {
  48939. if ( texture.image.length !== 6 ) return;
  48940. const forceUpload = initTexture( textureProperties, texture );
  48941. const source = texture.source;
  48942. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  48943. const sourceProperties = properties.get( source );
  48944. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  48945. state.activeTexture( _gl.TEXTURE0 + slot );
  48946. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  48947. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  48948. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  48949. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  48950. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  48951. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  48952. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  48953. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  48954. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  48955. const cubeImage = [];
  48956. for ( let i = 0; i < 6; i ++ ) {
  48957. if ( ! isCompressed && ! isDataTexture ) {
  48958. cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize );
  48959. } else {
  48960. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  48961. }
  48962. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  48963. }
  48964. const image = cubeImage[ 0 ],
  48965. glFormat = utils.convert( texture.format, texture.colorSpace ),
  48966. glType = utils.convert( texture.type ),
  48967. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  48968. const useTexStorage = ( texture.isVideoTexture !== true );
  48969. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  48970. const dataReady = source.dataReady;
  48971. let levels = getMipLevels( texture, image );
  48972. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  48973. let mipmaps;
  48974. if ( isCompressed ) {
  48975. if ( useTexStorage && allocateMemory ) {
  48976. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  48977. }
  48978. for ( let i = 0; i < 6; i ++ ) {
  48979. mipmaps = cubeImage[ i ].mipmaps;
  48980. for ( let j = 0; j < mipmaps.length; j ++ ) {
  48981. const mipmap = mipmaps[ j ];
  48982. if ( texture.format !== RGBAFormat ) {
  48983. if ( glFormat !== null ) {
  48984. if ( useTexStorage ) {
  48985. if ( dataReady ) {
  48986. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  48987. }
  48988. } else {
  48989. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  48990. }
  48991. } else {
  48992. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  48993. }
  48994. } else {
  48995. if ( useTexStorage ) {
  48996. if ( dataReady ) {
  48997. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  48998. }
  48999. } else {
  49000. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  49001. }
  49002. }
  49003. }
  49004. }
  49005. } else {
  49006. mipmaps = texture.mipmaps;
  49007. if ( useTexStorage && allocateMemory ) {
  49008. // TODO: Uniformly handle mipmap definitions
  49009. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  49010. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  49011. if ( mipmaps.length > 0 ) levels ++;
  49012. const dimensions = getDimensions( cubeImage[ 0 ] );
  49013. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height );
  49014. }
  49015. for ( let i = 0; i < 6; i ++ ) {
  49016. if ( isDataTexture ) {
  49017. if ( useTexStorage ) {
  49018. if ( dataReady ) {
  49019. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  49020. }
  49021. } else {
  49022. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  49023. }
  49024. for ( let j = 0; j < mipmaps.length; j ++ ) {
  49025. const mipmap = mipmaps[ j ];
  49026. const mipmapImage = mipmap.image[ i ].image;
  49027. if ( useTexStorage ) {
  49028. if ( dataReady ) {
  49029. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  49030. }
  49031. } else {
  49032. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  49033. }
  49034. }
  49035. } else {
  49036. if ( useTexStorage ) {
  49037. if ( dataReady ) {
  49038. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  49039. }
  49040. } else {
  49041. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  49042. }
  49043. for ( let j = 0; j < mipmaps.length; j ++ ) {
  49044. const mipmap = mipmaps[ j ];
  49045. if ( useTexStorage ) {
  49046. if ( dataReady ) {
  49047. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  49048. }
  49049. } else {
  49050. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  49051. }
  49052. }
  49053. }
  49054. }
  49055. }
  49056. if ( textureNeedsGenerateMipmaps( texture ) ) {
  49057. // We assume images for cube map have the same size.
  49058. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  49059. }
  49060. sourceProperties.__version = source.version;
  49061. if ( texture.onUpdate ) texture.onUpdate( texture );
  49062. }
  49063. textureProperties.__version = texture.version;
  49064. }
  49065. // Render targets
  49066. // Setup storage for target texture and bind it to correct framebuffer
  49067. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  49068. const glFormat = utils.convert( texture.format, texture.colorSpace );
  49069. const glType = utils.convert( texture.type );
  49070. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  49071. const renderTargetProperties = properties.get( renderTarget );
  49072. const textureProperties = properties.get( texture );
  49073. textureProperties.__renderTarget = renderTarget;
  49074. if ( ! renderTargetProperties.__hasExternalTextures ) {
  49075. const width = Math.max( 1, renderTarget.width >> level );
  49076. const height = Math.max( 1, renderTarget.height >> level );
  49077. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  49078. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  49079. } else {
  49080. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  49081. }
  49082. }
  49083. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  49084. if ( useMultisampledRTT( renderTarget ) ) {
  49085. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  49086. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  49087. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level );
  49088. }
  49089. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  49090. }
  49091. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  49092. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  49093. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  49094. if ( renderTarget.depthBuffer ) {
  49095. // retrieve the depth attachment types
  49096. const depthTexture = renderTarget.depthTexture;
  49097. const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null;
  49098. const glInternalFormat = getInternalDepthFormat( renderTarget.stencilBuffer, depthType );
  49099. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  49100. // set up the attachment
  49101. const samples = getRenderTargetSamples( renderTarget );
  49102. const isUseMultisampledRTT = useMultisampledRTT( renderTarget );
  49103. if ( isUseMultisampledRTT ) {
  49104. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49105. } else if ( isMultisample ) {
  49106. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49107. } else {
  49108. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  49109. }
  49110. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  49111. } else {
  49112. const textures = renderTarget.textures;
  49113. for ( let i = 0; i < textures.length; i ++ ) {
  49114. const texture = textures[ i ];
  49115. const glFormat = utils.convert( texture.format, texture.colorSpace );
  49116. const glType = utils.convert( texture.type );
  49117. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  49118. const samples = getRenderTargetSamples( renderTarget );
  49119. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  49120. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49121. } else if ( useMultisampledRTT( renderTarget ) ) {
  49122. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49123. } else {
  49124. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  49125. }
  49126. }
  49127. }
  49128. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  49129. }
  49130. // Setup resources for a Depth Texture for a FBO (needs an extension)
  49131. function setupDepthTexture( framebuffer, renderTarget ) {
  49132. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  49133. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  49134. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  49135. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  49136. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  49137. }
  49138. const textureProperties = properties.get( renderTarget.depthTexture );
  49139. textureProperties.__renderTarget = renderTarget;
  49140. // upload an empty depth texture with framebuffer size
  49141. if ( ! textureProperties.__webglTexture ||
  49142. renderTarget.depthTexture.image.width !== renderTarget.width ||
  49143. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  49144. renderTarget.depthTexture.image.width = renderTarget.width;
  49145. renderTarget.depthTexture.image.height = renderTarget.height;
  49146. renderTarget.depthTexture.needsUpdate = true;
  49147. }
  49148. setTexture2D( renderTarget.depthTexture, 0 );
  49149. const webglDepthTexture = textureProperties.__webglTexture;
  49150. const samples = getRenderTargetSamples( renderTarget );
  49151. if ( renderTarget.depthTexture.format === DepthFormat ) {
  49152. if ( useMultisampledRTT( renderTarget ) ) {
  49153. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  49154. } else {
  49155. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  49156. }
  49157. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  49158. if ( useMultisampledRTT( renderTarget ) ) {
  49159. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  49160. } else {
  49161. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  49162. }
  49163. } else {
  49164. throw new Error( 'Unknown depthTexture format' );
  49165. }
  49166. }
  49167. // Setup GL resources for a non-texture depth buffer
  49168. function setupDepthRenderbuffer( renderTarget ) {
  49169. const renderTargetProperties = properties.get( renderTarget );
  49170. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  49171. // if the bound depth texture has changed
  49172. if ( renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture ) {
  49173. // fire the dispose event to get rid of stored state associated with the previously bound depth buffer
  49174. const depthTexture = renderTarget.depthTexture;
  49175. if ( renderTargetProperties.__depthDisposeCallback ) {
  49176. renderTargetProperties.__depthDisposeCallback();
  49177. }
  49178. // set up dispose listeners to track when the currently attached buffer is implicitly unbound
  49179. if ( depthTexture ) {
  49180. const disposeEvent = () => {
  49181. delete renderTargetProperties.__boundDepthTexture;
  49182. delete renderTargetProperties.__depthDisposeCallback;
  49183. depthTexture.removeEventListener( 'dispose', disposeEvent );
  49184. };
  49185. depthTexture.addEventListener( 'dispose', disposeEvent );
  49186. renderTargetProperties.__depthDisposeCallback = disposeEvent;
  49187. }
  49188. renderTargetProperties.__boundDepthTexture = depthTexture;
  49189. }
  49190. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  49191. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  49192. const mipmaps = renderTarget.texture.mipmaps;
  49193. if ( mipmaps && mipmaps.length > 0 ) {
  49194. setupDepthTexture( renderTargetProperties.__webglFramebuffer[ 0 ], renderTarget );
  49195. } else {
  49196. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  49197. }
  49198. } else {
  49199. if ( isCube ) {
  49200. renderTargetProperties.__webglDepthbuffer = [];
  49201. for ( let i = 0; i < 6; i ++ ) {
  49202. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  49203. if ( renderTargetProperties.__webglDepthbuffer[ i ] === undefined ) {
  49204. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  49205. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  49206. } else {
  49207. // attach buffer if it's been created already
  49208. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  49209. const renderbuffer = renderTargetProperties.__webglDepthbuffer[ i ];
  49210. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  49211. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  49212. }
  49213. }
  49214. } else {
  49215. const mipmaps = renderTarget.texture.mipmaps;
  49216. if ( mipmaps && mipmaps.length > 0 ) {
  49217. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  49218. } else {
  49219. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  49220. }
  49221. if ( renderTargetProperties.__webglDepthbuffer === undefined ) {
  49222. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  49223. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  49224. } else {
  49225. // attach buffer if it's been created already
  49226. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  49227. const renderbuffer = renderTargetProperties.__webglDepthbuffer;
  49228. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  49229. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  49230. }
  49231. }
  49232. }
  49233. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  49234. }
  49235. // rebind framebuffer with external textures
  49236. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  49237. const renderTargetProperties = properties.get( renderTarget );
  49238. if ( colorTexture !== undefined ) {
  49239. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  49240. }
  49241. if ( depthTexture !== undefined ) {
  49242. setupDepthRenderbuffer( renderTarget );
  49243. }
  49244. }
  49245. // Set up GL resources for the render target
  49246. function setupRenderTarget( renderTarget ) {
  49247. const texture = renderTarget.texture;
  49248. const renderTargetProperties = properties.get( renderTarget );
  49249. const textureProperties = properties.get( texture );
  49250. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  49251. const textures = renderTarget.textures;
  49252. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  49253. const isMultipleRenderTargets = ( textures.length > 1 );
  49254. if ( ! isMultipleRenderTargets ) {
  49255. if ( textureProperties.__webglTexture === undefined ) {
  49256. textureProperties.__webglTexture = _gl.createTexture();
  49257. }
  49258. textureProperties.__version = texture.version;
  49259. info.memory.textures ++;
  49260. }
  49261. // Setup framebuffer
  49262. if ( isCube ) {
  49263. renderTargetProperties.__webglFramebuffer = [];
  49264. for ( let i = 0; i < 6; i ++ ) {
  49265. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  49266. renderTargetProperties.__webglFramebuffer[ i ] = [];
  49267. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  49268. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  49269. }
  49270. } else {
  49271. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  49272. }
  49273. }
  49274. } else {
  49275. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  49276. renderTargetProperties.__webglFramebuffer = [];
  49277. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  49278. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  49279. }
  49280. } else {
  49281. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  49282. }
  49283. if ( isMultipleRenderTargets ) {
  49284. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49285. const attachmentProperties = properties.get( textures[ i ] );
  49286. if ( attachmentProperties.__webglTexture === undefined ) {
  49287. attachmentProperties.__webglTexture = _gl.createTexture();
  49288. info.memory.textures ++;
  49289. }
  49290. }
  49291. }
  49292. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  49293. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  49294. renderTargetProperties.__webglColorRenderbuffer = [];
  49295. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  49296. for ( let i = 0; i < textures.length; i ++ ) {
  49297. const texture = textures[ i ];
  49298. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  49299. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  49300. const glFormat = utils.convert( texture.format, texture.colorSpace );
  49301. const glType = utils.convert( texture.type );
  49302. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  49303. const samples = getRenderTargetSamples( renderTarget );
  49304. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49305. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  49306. }
  49307. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  49308. if ( renderTarget.depthBuffer ) {
  49309. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  49310. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  49311. }
  49312. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  49313. }
  49314. }
  49315. // Setup color buffer
  49316. if ( isCube ) {
  49317. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  49318. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  49319. for ( let i = 0; i < 6; i ++ ) {
  49320. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  49321. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  49322. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  49323. }
  49324. } else {
  49325. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  49326. }
  49327. }
  49328. if ( textureNeedsGenerateMipmaps( texture ) ) {
  49329. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  49330. }
  49331. state.unbindTexture();
  49332. } else if ( isMultipleRenderTargets ) {
  49333. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49334. const attachment = textures[ i ];
  49335. const attachmentProperties = properties.get( attachment );
  49336. state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture );
  49337. setTextureParameters( _gl.TEXTURE_2D, attachment );
  49338. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, 0 );
  49339. if ( textureNeedsGenerateMipmaps( attachment ) ) {
  49340. generateMipmap( _gl.TEXTURE_2D );
  49341. }
  49342. }
  49343. state.unbindTexture();
  49344. } else {
  49345. let glTextureType = _gl.TEXTURE_2D;
  49346. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  49347. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  49348. }
  49349. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  49350. setTextureParameters( glTextureType, texture );
  49351. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  49352. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  49353. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  49354. }
  49355. } else {
  49356. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  49357. }
  49358. if ( textureNeedsGenerateMipmaps( texture ) ) {
  49359. generateMipmap( glTextureType );
  49360. }
  49361. state.unbindTexture();
  49362. }
  49363. // Setup depth and stencil buffers
  49364. if ( renderTarget.depthBuffer ) {
  49365. setupDepthRenderbuffer( renderTarget );
  49366. }
  49367. }
  49368. function updateRenderTargetMipmap( renderTarget ) {
  49369. const textures = renderTarget.textures;
  49370. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49371. const texture = textures[ i ];
  49372. if ( textureNeedsGenerateMipmaps( texture ) ) {
  49373. const targetType = getTargetType( renderTarget );
  49374. const webglTexture = properties.get( texture ).__webglTexture;
  49375. state.bindTexture( targetType, webglTexture );
  49376. generateMipmap( targetType );
  49377. state.unbindTexture();
  49378. }
  49379. }
  49380. }
  49381. const invalidationArrayRead = [];
  49382. const invalidationArrayDraw = [];
  49383. function updateMultisampleRenderTarget( renderTarget ) {
  49384. if ( renderTarget.samples > 0 ) {
  49385. if ( useMultisampledRTT( renderTarget ) === false ) {
  49386. const textures = renderTarget.textures;
  49387. const width = renderTarget.width;
  49388. const height = renderTarget.height;
  49389. let mask = _gl.COLOR_BUFFER_BIT;
  49390. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  49391. const renderTargetProperties = properties.get( renderTarget );
  49392. const isMultipleRenderTargets = ( textures.length > 1 );
  49393. // If MRT we need to remove FBO attachments
  49394. if ( isMultipleRenderTargets ) {
  49395. for ( let i = 0; i < textures.length; i ++ ) {
  49396. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  49397. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  49398. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  49399. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  49400. }
  49401. }
  49402. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  49403. const mipmaps = renderTarget.texture.mipmaps;
  49404. if ( mipmaps && mipmaps.length > 0 ) {
  49405. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  49406. } else {
  49407. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  49408. }
  49409. for ( let i = 0; i < textures.length; i ++ ) {
  49410. if ( renderTarget.resolveDepthBuffer ) {
  49411. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  49412. // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799)
  49413. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  49414. }
  49415. if ( isMultipleRenderTargets ) {
  49416. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  49417. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  49418. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  49419. }
  49420. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  49421. if ( supportsInvalidateFramebuffer === true ) {
  49422. invalidationArrayRead.length = 0;
  49423. invalidationArrayDraw.length = 0;
  49424. invalidationArrayRead.push( _gl.COLOR_ATTACHMENT0 + i );
  49425. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false ) {
  49426. invalidationArrayRead.push( depthStyle );
  49427. invalidationArrayDraw.push( depthStyle );
  49428. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, invalidationArrayDraw );
  49429. }
  49430. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArrayRead );
  49431. }
  49432. }
  49433. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  49434. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  49435. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  49436. if ( isMultipleRenderTargets ) {
  49437. for ( let i = 0; i < textures.length; i ++ ) {
  49438. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  49439. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  49440. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  49441. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  49442. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  49443. }
  49444. }
  49445. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  49446. } else {
  49447. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer ) {
  49448. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  49449. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  49450. }
  49451. }
  49452. }
  49453. }
  49454. function getRenderTargetSamples( renderTarget ) {
  49455. return Math.min( capabilities.maxSamples, renderTarget.samples );
  49456. }
  49457. function useMultisampledRTT( renderTarget ) {
  49458. const renderTargetProperties = properties.get( renderTarget );
  49459. return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  49460. }
  49461. function updateVideoTexture( texture ) {
  49462. const frame = info.render.frame;
  49463. // Check the last frame we updated the VideoTexture
  49464. if ( _videoTextures.get( texture ) !== frame ) {
  49465. _videoTextures.set( texture, frame );
  49466. texture.update();
  49467. }
  49468. }
  49469. function verifyColorSpace( texture, image ) {
  49470. const colorSpace = texture.colorSpace;
  49471. const format = texture.format;
  49472. const type = texture.type;
  49473. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image;
  49474. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  49475. // sRGB
  49476. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  49477. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  49478. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  49479. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  49480. }
  49481. } else {
  49482. console.error( 'THREE.WebGLTextures: Unsupported texture color space:', colorSpace );
  49483. }
  49484. }
  49485. return image;
  49486. }
  49487. function getDimensions( image ) {
  49488. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) {
  49489. // if intrinsic data are not available, fallback to width/height
  49490. _imageDimensions.width = image.naturalWidth || image.width;
  49491. _imageDimensions.height = image.naturalHeight || image.height;
  49492. } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) {
  49493. _imageDimensions.width = image.displayWidth;
  49494. _imageDimensions.height = image.displayHeight;
  49495. } else {
  49496. _imageDimensions.width = image.width;
  49497. _imageDimensions.height = image.height;
  49498. }
  49499. return _imageDimensions;
  49500. }
  49501. //
  49502. this.allocateTextureUnit = allocateTextureUnit;
  49503. this.resetTextureUnits = resetTextureUnits;
  49504. this.setTexture2D = setTexture2D;
  49505. this.setTexture2DArray = setTexture2DArray;
  49506. this.setTexture3D = setTexture3D;
  49507. this.setTextureCube = setTextureCube;
  49508. this.rebindTextures = rebindTextures;
  49509. this.setupRenderTarget = setupRenderTarget;
  49510. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  49511. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  49512. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  49513. this.setupFrameBufferTexture = setupFrameBufferTexture;
  49514. this.useMultisampledRTT = useMultisampledRTT;
  49515. }
  49516. function WebGLUtils( gl, extensions ) {
  49517. function convert( p, colorSpace = NoColorSpace ) {
  49518. let extension;
  49519. const transfer = ColorManagement.getTransfer( colorSpace );
  49520. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  49521. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  49522. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  49523. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  49524. if ( p === ByteType ) return gl.BYTE;
  49525. if ( p === ShortType ) return gl.SHORT;
  49526. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  49527. if ( p === IntType ) return gl.INT;
  49528. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  49529. if ( p === FloatType ) return gl.FLOAT;
  49530. if ( p === HalfFloatType ) return gl.HALF_FLOAT;
  49531. if ( p === AlphaFormat ) return gl.ALPHA;
  49532. if ( p === RGBFormat ) return gl.RGB;
  49533. if ( p === RGBAFormat ) return gl.RGBA;
  49534. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  49535. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  49536. // WebGL2 formats.
  49537. if ( p === RedFormat ) return gl.RED;
  49538. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  49539. if ( p === RGFormat ) return gl.RG;
  49540. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  49541. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  49542. // S3TC
  49543. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  49544. if ( transfer === SRGBTransfer ) {
  49545. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  49546. if ( extension !== null ) {
  49547. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  49548. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  49549. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  49550. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  49551. } else {
  49552. return null;
  49553. }
  49554. } else {
  49555. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  49556. if ( extension !== null ) {
  49557. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  49558. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  49559. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  49560. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  49561. } else {
  49562. return null;
  49563. }
  49564. }
  49565. }
  49566. // PVRTC
  49567. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  49568. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  49569. if ( extension !== null ) {
  49570. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  49571. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  49572. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  49573. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  49574. } else {
  49575. return null;
  49576. }
  49577. }
  49578. // ETC
  49579. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  49580. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  49581. if ( extension !== null ) {
  49582. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  49583. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  49584. } else {
  49585. return null;
  49586. }
  49587. }
  49588. // ASTC
  49589. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  49590. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  49591. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  49592. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  49593. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  49594. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  49595. if ( extension !== null ) {
  49596. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  49597. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  49598. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  49599. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  49600. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  49601. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  49602. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  49603. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  49604. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  49605. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  49606. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  49607. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  49608. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  49609. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  49610. } else {
  49611. return null;
  49612. }
  49613. }
  49614. // BPTC
  49615. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  49616. extension = extensions.get( 'EXT_texture_compression_bptc' );
  49617. if ( extension !== null ) {
  49618. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  49619. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  49620. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  49621. } else {
  49622. return null;
  49623. }
  49624. }
  49625. // RGTC
  49626. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  49627. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  49628. if ( extension !== null ) {
  49629. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  49630. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  49631. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  49632. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  49633. } else {
  49634. return null;
  49635. }
  49636. }
  49637. //
  49638. if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8;
  49639. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  49640. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  49641. }
  49642. return { convert: convert };
  49643. }
  49644. const _occlusion_vertex = `
  49645. void main() {
  49646. gl_Position = vec4( position, 1.0 );
  49647. }`;
  49648. const _occlusion_fragment = `
  49649. uniform sampler2DArray depthColor;
  49650. uniform float depthWidth;
  49651. uniform float depthHeight;
  49652. void main() {
  49653. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  49654. if ( coord.x >= 1.0 ) {
  49655. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  49656. } else {
  49657. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  49658. }
  49659. }`;
  49660. /**
  49661. * A XR module that manages the access to the Depth Sensing API.
  49662. */
  49663. class WebXRDepthSensing {
  49664. /**
  49665. * Constructs a new depth sensing module.
  49666. */
  49667. constructor() {
  49668. /**
  49669. * A texture representing the depth of the user's environment.
  49670. *
  49671. * @type {?Texture}
  49672. */
  49673. this.texture = null;
  49674. /**
  49675. * A plane mesh for visualizing the depth texture.
  49676. *
  49677. * @type {?Mesh}
  49678. */
  49679. this.mesh = null;
  49680. /**
  49681. * The depth near value.
  49682. *
  49683. * @type {number}
  49684. */
  49685. this.depthNear = 0;
  49686. /**
  49687. * The depth near far.
  49688. *
  49689. * @type {number}
  49690. */
  49691. this.depthFar = 0;
  49692. }
  49693. /**
  49694. * Inits the depth sensing module
  49695. *
  49696. * @param {WebGLRenderer} renderer - The renderer.
  49697. * @param {XRWebGLDepthInformation} depthData - The XR depth data.
  49698. * @param {XRRenderState} renderState - The XR render state.
  49699. */
  49700. init( renderer, depthData, renderState ) {
  49701. if ( this.texture === null ) {
  49702. const texture = new Texture();
  49703. const texProps = renderer.properties.get( texture );
  49704. texProps.__webglTexture = depthData.texture;
  49705. if ( ( depthData.depthNear !== renderState.depthNear ) || ( depthData.depthFar !== renderState.depthFar ) ) {
  49706. this.depthNear = depthData.depthNear;
  49707. this.depthFar = depthData.depthFar;
  49708. }
  49709. this.texture = texture;
  49710. }
  49711. }
  49712. /**
  49713. * Returns a plane mesh that visualizes the depth texture.
  49714. *
  49715. * @param {ArrayCamera} cameraXR - The XR camera.
  49716. * @return {?Mesh} The plane mesh.
  49717. */
  49718. getMesh( cameraXR ) {
  49719. if ( this.texture !== null ) {
  49720. if ( this.mesh === null ) {
  49721. const viewport = cameraXR.cameras[ 0 ].viewport;
  49722. const material = new ShaderMaterial( {
  49723. vertexShader: _occlusion_vertex,
  49724. fragmentShader: _occlusion_fragment,
  49725. uniforms: {
  49726. depthColor: { value: this.texture },
  49727. depthWidth: { value: viewport.z },
  49728. depthHeight: { value: viewport.w }
  49729. }
  49730. } );
  49731. this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material );
  49732. }
  49733. }
  49734. return this.mesh;
  49735. }
  49736. /**
  49737. * Resets the module
  49738. */
  49739. reset() {
  49740. this.texture = null;
  49741. this.mesh = null;
  49742. }
  49743. /**
  49744. * Returns a texture representing the depth of the user's environment.
  49745. *
  49746. * @return {?Texture} The depth texture.
  49747. */
  49748. getDepthTexture() {
  49749. return this.texture;
  49750. }
  49751. }
  49752. /**
  49753. * This class represents an abstraction of the WebXR Device API and is
  49754. * internally used by {@link WebGLRenderer}. `WebXRManager` also provides a public
  49755. * interface that allows users to enable/disable XR and perform XR related
  49756. * tasks like for instance retrieving controllers.
  49757. *
  49758. * @augments EventDispatcher
  49759. * @hideconstructor
  49760. */
  49761. class WebXRManager extends EventDispatcher {
  49762. /**
  49763. * Constructs a new WebGL renderer.
  49764. *
  49765. * @param {WebGLRenderer} renderer - The renderer.
  49766. * @param {WebGL2RenderingContext} gl - The rendering context.
  49767. */
  49768. constructor( renderer, gl ) {
  49769. super();
  49770. const scope = this;
  49771. let session = null;
  49772. let framebufferScaleFactor = 1.0;
  49773. let referenceSpace = null;
  49774. let referenceSpaceType = 'local-floor';
  49775. // Set default foveation to maximum.
  49776. let foveation = 1.0;
  49777. let customReferenceSpace = null;
  49778. let pose = null;
  49779. let glBinding = null;
  49780. let glProjLayer = null;
  49781. let glBaseLayer = null;
  49782. let xrFrame = null;
  49783. const depthSensing = new WebXRDepthSensing();
  49784. const attributes = gl.getContextAttributes();
  49785. let initialRenderTarget = null;
  49786. let newRenderTarget = null;
  49787. const controllers = [];
  49788. const controllerInputSources = [];
  49789. const currentSize = new Vector2();
  49790. let currentPixelRatio = null;
  49791. //
  49792. const cameraL = new PerspectiveCamera();
  49793. cameraL.viewport = new Vector4();
  49794. const cameraR = new PerspectiveCamera();
  49795. cameraR.viewport = new Vector4();
  49796. const cameras = [ cameraL, cameraR ];
  49797. const cameraXR = new ArrayCamera();
  49798. let _currentDepthNear = null;
  49799. let _currentDepthFar = null;
  49800. //
  49801. /**
  49802. * Whether the manager's XR camera should be automatically updated or not.
  49803. *
  49804. * @type {boolean}
  49805. * @default true
  49806. */
  49807. this.cameraAutoUpdate = true;
  49808. /**
  49809. * This flag notifies the renderer to be ready for XR rendering. Set it to `true`
  49810. * if you are going to use XR in your app.
  49811. *
  49812. * @type {boolean}
  49813. * @default false
  49814. */
  49815. this.enabled = false;
  49816. /**
  49817. * Whether XR presentation is active or not.
  49818. *
  49819. * @type {boolean}
  49820. * @readonly
  49821. * @default false
  49822. */
  49823. this.isPresenting = false;
  49824. /**
  49825. * Returns a group representing the `target ray` space of the XR controller.
  49826. * Use this space for visualizing 3D objects that support the user in pointing
  49827. * tasks like UI interaction.
  49828. *
  49829. * @param {number} index - The index of the controller.
  49830. * @return {Group} A group representing the `target ray` space.
  49831. */
  49832. this.getController = function ( index ) {
  49833. let controller = controllers[ index ];
  49834. if ( controller === undefined ) {
  49835. controller = new WebXRController();
  49836. controllers[ index ] = controller;
  49837. }
  49838. return controller.getTargetRaySpace();
  49839. };
  49840. /**
  49841. * Returns a group representing the `grip` space of the XR controller.
  49842. * Use this space for visualizing 3D objects that support the user in pointing
  49843. * tasks like UI interaction.
  49844. *
  49845. * Note: If you want to show something in the user's hand AND offer a
  49846. * pointing ray at the same time, you'll want to attached the handheld object
  49847. * to the group returned by `getControllerGrip()` and the ray to the
  49848. * group returned by `getController()`. The idea is to have two
  49849. * different groups in two different coordinate spaces for the same WebXR
  49850. * controller.
  49851. *
  49852. * @param {number} index - The index of the controller.
  49853. * @return {Group} A group representing the `grip` space.
  49854. */
  49855. this.getControllerGrip = function ( index ) {
  49856. let controller = controllers[ index ];
  49857. if ( controller === undefined ) {
  49858. controller = new WebXRController();
  49859. controllers[ index ] = controller;
  49860. }
  49861. return controller.getGripSpace();
  49862. };
  49863. /**
  49864. * Returns a group representing the `hand` space of the XR controller.
  49865. * Use this space for visualizing 3D objects that support the user in pointing
  49866. * tasks like UI interaction.
  49867. *
  49868. * @param {number} index - The index of the controller.
  49869. * @return {Group} A group representing the `hand` space.
  49870. */
  49871. this.getHand = function ( index ) {
  49872. let controller = controllers[ index ];
  49873. if ( controller === undefined ) {
  49874. controller = new WebXRController();
  49875. controllers[ index ] = controller;
  49876. }
  49877. return controller.getHandSpace();
  49878. };
  49879. //
  49880. function onSessionEvent( event ) {
  49881. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  49882. if ( controllerIndex === -1 ) {
  49883. return;
  49884. }
  49885. const controller = controllers[ controllerIndex ];
  49886. if ( controller !== undefined ) {
  49887. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  49888. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  49889. }
  49890. }
  49891. function onSessionEnd() {
  49892. session.removeEventListener( 'select', onSessionEvent );
  49893. session.removeEventListener( 'selectstart', onSessionEvent );
  49894. session.removeEventListener( 'selectend', onSessionEvent );
  49895. session.removeEventListener( 'squeeze', onSessionEvent );
  49896. session.removeEventListener( 'squeezestart', onSessionEvent );
  49897. session.removeEventListener( 'squeezeend', onSessionEvent );
  49898. session.removeEventListener( 'end', onSessionEnd );
  49899. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  49900. for ( let i = 0; i < controllers.length; i ++ ) {
  49901. const inputSource = controllerInputSources[ i ];
  49902. if ( inputSource === null ) continue;
  49903. controllerInputSources[ i ] = null;
  49904. controllers[ i ].disconnect( inputSource );
  49905. }
  49906. _currentDepthNear = null;
  49907. _currentDepthFar = null;
  49908. depthSensing.reset();
  49909. // restore framebuffer/rendering state
  49910. renderer.setRenderTarget( initialRenderTarget );
  49911. glBaseLayer = null;
  49912. glProjLayer = null;
  49913. glBinding = null;
  49914. session = null;
  49915. newRenderTarget = null;
  49916. //
  49917. animation.stop();
  49918. scope.isPresenting = false;
  49919. renderer.setPixelRatio( currentPixelRatio );
  49920. renderer.setSize( currentSize.width, currentSize.height, false );
  49921. scope.dispatchEvent( { type: 'sessionend' } );
  49922. }
  49923. /**
  49924. * Sets the framebuffer scale factor.
  49925. *
  49926. * This method can not be used during a XR session.
  49927. *
  49928. * @param {number} value - The framebuffer scale factor.
  49929. */
  49930. this.setFramebufferScaleFactor = function ( value ) {
  49931. framebufferScaleFactor = value;
  49932. if ( scope.isPresenting === true ) {
  49933. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  49934. }
  49935. };
  49936. /**
  49937. * Sets the reference space type. Can be used to configure a spatial relationship with the user's physical
  49938. * environment. Depending on how the user moves in 3D space, setting an appropriate reference space can
  49939. * improve tracking. Default is `local-floor`. Valid values can be found here
  49940. * https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpace#reference_space_types.
  49941. *
  49942. * This method can not be used during a XR session.
  49943. *
  49944. * @param {string} value - The reference space type.
  49945. */
  49946. this.setReferenceSpaceType = function ( value ) {
  49947. referenceSpaceType = value;
  49948. if ( scope.isPresenting === true ) {
  49949. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  49950. }
  49951. };
  49952. /**
  49953. * Returns the XR reference space.
  49954. *
  49955. * @return {XRReferenceSpace} The XR reference space.
  49956. */
  49957. this.getReferenceSpace = function () {
  49958. return customReferenceSpace || referenceSpace;
  49959. };
  49960. /**
  49961. * Sets a custom XR reference space.
  49962. *
  49963. * @param {XRReferenceSpace} space - The XR reference space.
  49964. */
  49965. this.setReferenceSpace = function ( space ) {
  49966. customReferenceSpace = space;
  49967. };
  49968. /**
  49969. * Returns the current base layer.
  49970. *
  49971. * @return {?(XRWebGLLayer|XRProjectionLayer)} The XR base layer.
  49972. */
  49973. this.getBaseLayer = function () {
  49974. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  49975. };
  49976. /**
  49977. * Returns the current XR binding.
  49978. *
  49979. * @return {?XRWebGLBinding} The XR binding.
  49980. */
  49981. this.getBinding = function () {
  49982. return glBinding;
  49983. };
  49984. /**
  49985. * Returns the current XR frame.
  49986. *
  49987. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  49988. */
  49989. this.getFrame = function () {
  49990. return xrFrame;
  49991. };
  49992. /**
  49993. * Returns the current XR session.
  49994. *
  49995. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  49996. */
  49997. this.getSession = function () {
  49998. return session;
  49999. };
  50000. /**
  50001. * After a XR session has been requested usually with one of the `*Button` modules, it
  50002. * is injected into the renderer with this method. This method triggers the start of
  50003. * the actual XR rendering.
  50004. *
  50005. * @async
  50006. * @param {XRSession} value - The XR session to set.
  50007. * @return {Promise} A Promise that resolves when the session has been set.
  50008. */
  50009. this.setSession = async function ( value ) {
  50010. session = value;
  50011. if ( session !== null ) {
  50012. initialRenderTarget = renderer.getRenderTarget();
  50013. session.addEventListener( 'select', onSessionEvent );
  50014. session.addEventListener( 'selectstart', onSessionEvent );
  50015. session.addEventListener( 'selectend', onSessionEvent );
  50016. session.addEventListener( 'squeeze', onSessionEvent );
  50017. session.addEventListener( 'squeezestart', onSessionEvent );
  50018. session.addEventListener( 'squeezeend', onSessionEvent );
  50019. session.addEventListener( 'end', onSessionEnd );
  50020. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  50021. if ( attributes.xrCompatible !== true ) {
  50022. await gl.makeXRCompatible();
  50023. }
  50024. currentPixelRatio = renderer.getPixelRatio();
  50025. renderer.getSize( currentSize );
  50026. // Check that the browser implements the necessary APIs to use an
  50027. // XRProjectionLayer rather than an XRWebGLLayer
  50028. const useLayers = typeof XRWebGLBinding !== 'undefined' && 'createProjectionLayer' in XRWebGLBinding.prototype;
  50029. if ( ! useLayers ) {
  50030. const layerInit = {
  50031. antialias: attributes.antialias,
  50032. alpha: true,
  50033. depth: attributes.depth,
  50034. stencil: attributes.stencil,
  50035. framebufferScaleFactor: framebufferScaleFactor
  50036. };
  50037. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  50038. session.updateRenderState( { baseLayer: glBaseLayer } );
  50039. renderer.setPixelRatio( 1 );
  50040. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  50041. newRenderTarget = new WebGLRenderTarget(
  50042. glBaseLayer.framebufferWidth,
  50043. glBaseLayer.framebufferHeight,
  50044. {
  50045. format: RGBAFormat,
  50046. type: UnsignedByteType,
  50047. colorSpace: renderer.outputColorSpace,
  50048. stencilBuffer: attributes.stencil,
  50049. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  50050. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false )
  50051. }
  50052. );
  50053. } else {
  50054. let depthFormat = null;
  50055. let depthType = null;
  50056. let glDepthFormat = null;
  50057. if ( attributes.depth ) {
  50058. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  50059. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  50060. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  50061. }
  50062. const projectionlayerInit = {
  50063. colorFormat: gl.RGBA8,
  50064. depthFormat: glDepthFormat,
  50065. scaleFactor: framebufferScaleFactor
  50066. };
  50067. glBinding = new XRWebGLBinding( session, gl );
  50068. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  50069. session.updateRenderState( { layers: [ glProjLayer ] } );
  50070. renderer.setPixelRatio( 1 );
  50071. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  50072. newRenderTarget = new WebGLRenderTarget(
  50073. glProjLayer.textureWidth,
  50074. glProjLayer.textureHeight,
  50075. {
  50076. format: RGBAFormat,
  50077. type: UnsignedByteType,
  50078. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  50079. stencilBuffer: attributes.stencil,
  50080. colorSpace: renderer.outputColorSpace,
  50081. samples: attributes.antialias ? 4 : 0,
  50082. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  50083. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false )
  50084. } );
  50085. }
  50086. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  50087. this.setFoveation( foveation );
  50088. customReferenceSpace = null;
  50089. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  50090. animation.setContext( session );
  50091. animation.start();
  50092. scope.isPresenting = true;
  50093. scope.dispatchEvent( { type: 'sessionstart' } );
  50094. }
  50095. };
  50096. /**
  50097. * Returns the environment blend mode from the current XR session.
  50098. *
  50099. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  50100. */
  50101. this.getEnvironmentBlendMode = function () {
  50102. if ( session !== null ) {
  50103. return session.environmentBlendMode;
  50104. }
  50105. };
  50106. /**
  50107. * Returns the current depth texture computed via depth sensing.
  50108. *
  50109. * @return {?Texture} The depth texture.
  50110. */
  50111. this.getDepthTexture = function () {
  50112. return depthSensing.getDepthTexture();
  50113. };
  50114. function onInputSourcesChange( event ) {
  50115. // Notify disconnected
  50116. for ( let i = 0; i < event.removed.length; i ++ ) {
  50117. const inputSource = event.removed[ i ];
  50118. const index = controllerInputSources.indexOf( inputSource );
  50119. if ( index >= 0 ) {
  50120. controllerInputSources[ index ] = null;
  50121. controllers[ index ].disconnect( inputSource );
  50122. }
  50123. }
  50124. // Notify connected
  50125. for ( let i = 0; i < event.added.length; i ++ ) {
  50126. const inputSource = event.added[ i ];
  50127. let controllerIndex = controllerInputSources.indexOf( inputSource );
  50128. if ( controllerIndex === -1 ) {
  50129. // Assign input source a controller that currently has no input source
  50130. for ( let i = 0; i < controllers.length; i ++ ) {
  50131. if ( i >= controllerInputSources.length ) {
  50132. controllerInputSources.push( inputSource );
  50133. controllerIndex = i;
  50134. break;
  50135. } else if ( controllerInputSources[ i ] === null ) {
  50136. controllerInputSources[ i ] = inputSource;
  50137. controllerIndex = i;
  50138. break;
  50139. }
  50140. }
  50141. // If all controllers do currently receive input we ignore new ones
  50142. if ( controllerIndex === -1 ) break;
  50143. }
  50144. const controller = controllers[ controllerIndex ];
  50145. if ( controller ) {
  50146. controller.connect( inputSource );
  50147. }
  50148. }
  50149. }
  50150. //
  50151. const cameraLPos = new Vector3();
  50152. const cameraRPos = new Vector3();
  50153. /**
  50154. * Assumes 2 cameras that are parallel and share an X-axis, and that
  50155. * the cameras' projection and world matrices have already been set.
  50156. * And that near and far planes are identical for both cameras.
  50157. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  50158. *
  50159. * @param {ArrayCamera} camera - The camera to update.
  50160. * @param {PerspectiveCamera} cameraL - The left camera.
  50161. * @param {PerspectiveCamera} cameraR - The right camera.
  50162. */
  50163. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  50164. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  50165. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  50166. const ipd = cameraLPos.distanceTo( cameraRPos );
  50167. const projL = cameraL.projectionMatrix.elements;
  50168. const projR = cameraR.projectionMatrix.elements;
  50169. // VR systems will have identical far and near planes, and
  50170. // most likely identical top and bottom frustum extents.
  50171. // Use the left camera for these values.
  50172. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  50173. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  50174. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  50175. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  50176. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  50177. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  50178. const left = near * leftFov;
  50179. const right = near * rightFov;
  50180. // Calculate the new camera's position offset from the
  50181. // left camera. xOffset should be roughly half `ipd`.
  50182. const zOffset = ipd / ( - leftFov + rightFov );
  50183. const xOffset = zOffset * - leftFov;
  50184. // TODO: Better way to apply this offset?
  50185. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  50186. camera.translateX( xOffset );
  50187. camera.translateZ( zOffset );
  50188. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  50189. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  50190. // Check if the projection uses an infinite far plane.
  50191. if ( projL[ 10 ] === -1 ) {
  50192. // Use the projection matrix from the left eye.
  50193. // The camera offset is sufficient to include the view volumes
  50194. // of both eyes (assuming symmetric projections).
  50195. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  50196. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  50197. } else {
  50198. // Find the union of the frustum values of the cameras and scale
  50199. // the values so that the near plane's position does not change in world space,
  50200. // although must now be relative to the new union camera.
  50201. const near2 = near + zOffset;
  50202. const far2 = far + zOffset;
  50203. const left2 = left - xOffset;
  50204. const right2 = right + ( ipd - xOffset );
  50205. const top2 = topFov * far / far2 * near2;
  50206. const bottom2 = bottomFov * far / far2 * near2;
  50207. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  50208. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  50209. }
  50210. }
  50211. function updateCamera( camera, parent ) {
  50212. if ( parent === null ) {
  50213. camera.matrixWorld.copy( camera.matrix );
  50214. } else {
  50215. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  50216. }
  50217. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  50218. }
  50219. /**
  50220. * Updates the state of the XR camera. Use this method on app level if you
  50221. * set cameraAutoUpdate` to `false`. The method requires the non-XR
  50222. * camera of the scene as a parameter. The passed in camera's transformation
  50223. * is automatically adjusted to the position of the XR camera when calling
  50224. * this method.
  50225. *
  50226. * @param {Camera} camera - The camera.
  50227. */
  50228. this.updateCamera = function ( camera ) {
  50229. if ( session === null ) return;
  50230. let depthNear = camera.near;
  50231. let depthFar = camera.far;
  50232. if ( depthSensing.texture !== null ) {
  50233. if ( depthSensing.depthNear > 0 ) depthNear = depthSensing.depthNear;
  50234. if ( depthSensing.depthFar > 0 ) depthFar = depthSensing.depthFar;
  50235. }
  50236. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  50237. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  50238. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  50239. // Note that the new renderState won't apply until the next frame. See #18320
  50240. session.updateRenderState( {
  50241. depthNear: cameraXR.near,
  50242. depthFar: cameraXR.far
  50243. } );
  50244. _currentDepthNear = cameraXR.near;
  50245. _currentDepthFar = cameraXR.far;
  50246. }
  50247. cameraL.layers.mask = camera.layers.mask | 0b010;
  50248. cameraR.layers.mask = camera.layers.mask | 0b100;
  50249. cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask;
  50250. const parent = camera.parent;
  50251. const cameras = cameraXR.cameras;
  50252. updateCamera( cameraXR, parent );
  50253. for ( let i = 0; i < cameras.length; i ++ ) {
  50254. updateCamera( cameras[ i ], parent );
  50255. }
  50256. // update projection matrix for proper view frustum culling
  50257. if ( cameras.length === 2 ) {
  50258. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  50259. } else {
  50260. // assume single camera setup (AR)
  50261. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  50262. }
  50263. // update user camera and its children
  50264. updateUserCamera( camera, cameraXR, parent );
  50265. };
  50266. function updateUserCamera( camera, cameraXR, parent ) {
  50267. if ( parent === null ) {
  50268. camera.matrix.copy( cameraXR.matrixWorld );
  50269. } else {
  50270. camera.matrix.copy( parent.matrixWorld );
  50271. camera.matrix.invert();
  50272. camera.matrix.multiply( cameraXR.matrixWorld );
  50273. }
  50274. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  50275. camera.updateMatrixWorld( true );
  50276. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  50277. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  50278. if ( camera.isPerspectiveCamera ) {
  50279. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  50280. camera.zoom = 1;
  50281. }
  50282. }
  50283. /**
  50284. * Returns an instance of {@link ArrayCamera} which represents the XR camera
  50285. * of the active XR session. For each view it holds a separate camera object.
  50286. *
  50287. * The camera's `fov` is currently not used and does not reflect the fov of
  50288. * the XR camera. If you need the fov on app level, you have to compute in
  50289. * manually from the XR camera's projection matrices.
  50290. *
  50291. * @return {ArrayCamera} The XR camera.
  50292. */
  50293. this.getCamera = function () {
  50294. return cameraXR;
  50295. };
  50296. /**
  50297. * Returns the amount of foveation used by the XR compositor for the projection layer.
  50298. *
  50299. * @return {number} The amount of foveation.
  50300. */
  50301. this.getFoveation = function () {
  50302. if ( glProjLayer === null && glBaseLayer === null ) {
  50303. return undefined;
  50304. }
  50305. return foveation;
  50306. };
  50307. /**
  50308. * Sets the foveation value.
  50309. *
  50310. * @param {number} value - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  50311. * and `1` means maximum foveation (the edges render at lower resolution).
  50312. */
  50313. this.setFoveation = function ( value ) {
  50314. // 0 = no foveation = full resolution
  50315. // 1 = maximum foveation = the edges render at lower resolution
  50316. foveation = value;
  50317. if ( glProjLayer !== null ) {
  50318. glProjLayer.fixedFoveation = value;
  50319. }
  50320. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  50321. glBaseLayer.fixedFoveation = value;
  50322. }
  50323. };
  50324. /**
  50325. * Returns `true` if depth sensing is supported.
  50326. *
  50327. * @return {boolean} Whether depth sensing is supported or not.
  50328. */
  50329. this.hasDepthSensing = function () {
  50330. return depthSensing.texture !== null;
  50331. };
  50332. /**
  50333. * Returns the depth sensing mesh.
  50334. *
  50335. * @return {Mesh} The depth sensing mesh.
  50336. */
  50337. this.getDepthSensingMesh = function () {
  50338. return depthSensing.getMesh( cameraXR );
  50339. };
  50340. // Animation Loop
  50341. let onAnimationFrameCallback = null;
  50342. function onAnimationFrame( time, frame ) {
  50343. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  50344. xrFrame = frame;
  50345. if ( pose !== null ) {
  50346. const views = pose.views;
  50347. if ( glBaseLayer !== null ) {
  50348. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  50349. renderer.setRenderTarget( newRenderTarget );
  50350. }
  50351. let cameraXRNeedsUpdate = false;
  50352. // check if it's necessary to rebuild cameraXR's camera list
  50353. if ( views.length !== cameraXR.cameras.length ) {
  50354. cameraXR.cameras.length = 0;
  50355. cameraXRNeedsUpdate = true;
  50356. }
  50357. for ( let i = 0; i < views.length; i ++ ) {
  50358. const view = views[ i ];
  50359. let viewport = null;
  50360. if ( glBaseLayer !== null ) {
  50361. viewport = glBaseLayer.getViewport( view );
  50362. } else {
  50363. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  50364. viewport = glSubImage.viewport;
  50365. // For side-by-side projection, we only produce a single texture for both eyes.
  50366. if ( i === 0 ) {
  50367. renderer.setRenderTargetTextures(
  50368. newRenderTarget,
  50369. glSubImage.colorTexture,
  50370. glSubImage.depthStencilTexture );
  50371. renderer.setRenderTarget( newRenderTarget );
  50372. }
  50373. }
  50374. let camera = cameras[ i ];
  50375. if ( camera === undefined ) {
  50376. camera = new PerspectiveCamera();
  50377. camera.layers.enable( i );
  50378. camera.viewport = new Vector4();
  50379. cameras[ i ] = camera;
  50380. }
  50381. camera.matrix.fromArray( view.transform.matrix );
  50382. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  50383. camera.projectionMatrix.fromArray( view.projectionMatrix );
  50384. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  50385. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  50386. if ( i === 0 ) {
  50387. cameraXR.matrix.copy( camera.matrix );
  50388. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  50389. }
  50390. if ( cameraXRNeedsUpdate === true ) {
  50391. cameraXR.cameras.push( camera );
  50392. }
  50393. }
  50394. //
  50395. const enabledFeatures = session.enabledFeatures;
  50396. const gpuDepthSensingEnabled = enabledFeatures &&
  50397. enabledFeatures.includes( 'depth-sensing' ) &&
  50398. session.depthUsage == 'gpu-optimized';
  50399. if ( gpuDepthSensingEnabled && glBinding ) {
  50400. const depthData = glBinding.getDepthInformation( views[ 0 ] );
  50401. if ( depthData && depthData.isValid && depthData.texture ) {
  50402. depthSensing.init( renderer, depthData, session.renderState );
  50403. }
  50404. }
  50405. }
  50406. //
  50407. for ( let i = 0; i < controllers.length; i ++ ) {
  50408. const inputSource = controllerInputSources[ i ];
  50409. const controller = controllers[ i ];
  50410. if ( inputSource !== null && controller !== undefined ) {
  50411. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  50412. }
  50413. }
  50414. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  50415. if ( frame.detectedPlanes ) {
  50416. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  50417. }
  50418. xrFrame = null;
  50419. }
  50420. const animation = new WebGLAnimation();
  50421. animation.setAnimationLoop( onAnimationFrame );
  50422. this.setAnimationLoop = function ( callback ) {
  50423. onAnimationFrameCallback = callback;
  50424. };
  50425. this.dispose = function () {};
  50426. }
  50427. }
  50428. const _e1 = /*@__PURE__*/ new Euler();
  50429. const _m1 = /*@__PURE__*/ new Matrix4();
  50430. function WebGLMaterials( renderer, properties ) {
  50431. function refreshTransformUniform( map, uniform ) {
  50432. if ( map.matrixAutoUpdate === true ) {
  50433. map.updateMatrix();
  50434. }
  50435. uniform.value.copy( map.matrix );
  50436. }
  50437. function refreshFogUniforms( uniforms, fog ) {
  50438. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  50439. if ( fog.isFog ) {
  50440. uniforms.fogNear.value = fog.near;
  50441. uniforms.fogFar.value = fog.far;
  50442. } else if ( fog.isFogExp2 ) {
  50443. uniforms.fogDensity.value = fog.density;
  50444. }
  50445. }
  50446. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  50447. if ( material.isMeshBasicMaterial ) {
  50448. refreshUniformsCommon( uniforms, material );
  50449. } else if ( material.isMeshLambertMaterial ) {
  50450. refreshUniformsCommon( uniforms, material );
  50451. } else if ( material.isMeshToonMaterial ) {
  50452. refreshUniformsCommon( uniforms, material );
  50453. refreshUniformsToon( uniforms, material );
  50454. } else if ( material.isMeshPhongMaterial ) {
  50455. refreshUniformsCommon( uniforms, material );
  50456. refreshUniformsPhong( uniforms, material );
  50457. } else if ( material.isMeshStandardMaterial ) {
  50458. refreshUniformsCommon( uniforms, material );
  50459. refreshUniformsStandard( uniforms, material );
  50460. if ( material.isMeshPhysicalMaterial ) {
  50461. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  50462. }
  50463. } else if ( material.isMeshMatcapMaterial ) {
  50464. refreshUniformsCommon( uniforms, material );
  50465. refreshUniformsMatcap( uniforms, material );
  50466. } else if ( material.isMeshDepthMaterial ) {
  50467. refreshUniformsCommon( uniforms, material );
  50468. } else if ( material.isMeshDistanceMaterial ) {
  50469. refreshUniformsCommon( uniforms, material );
  50470. refreshUniformsDistance( uniforms, material );
  50471. } else if ( material.isMeshNormalMaterial ) {
  50472. refreshUniformsCommon( uniforms, material );
  50473. } else if ( material.isLineBasicMaterial ) {
  50474. refreshUniformsLine( uniforms, material );
  50475. if ( material.isLineDashedMaterial ) {
  50476. refreshUniformsDash( uniforms, material );
  50477. }
  50478. } else if ( material.isPointsMaterial ) {
  50479. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  50480. } else if ( material.isSpriteMaterial ) {
  50481. refreshUniformsSprites( uniforms, material );
  50482. } else if ( material.isShadowMaterial ) {
  50483. uniforms.color.value.copy( material.color );
  50484. uniforms.opacity.value = material.opacity;
  50485. } else if ( material.isShaderMaterial ) {
  50486. material.uniformsNeedUpdate = false; // #15581
  50487. }
  50488. }
  50489. function refreshUniformsCommon( uniforms, material ) {
  50490. uniforms.opacity.value = material.opacity;
  50491. if ( material.color ) {
  50492. uniforms.diffuse.value.copy( material.color );
  50493. }
  50494. if ( material.emissive ) {
  50495. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  50496. }
  50497. if ( material.map ) {
  50498. uniforms.map.value = material.map;
  50499. refreshTransformUniform( material.map, uniforms.mapTransform );
  50500. }
  50501. if ( material.alphaMap ) {
  50502. uniforms.alphaMap.value = material.alphaMap;
  50503. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  50504. }
  50505. if ( material.bumpMap ) {
  50506. uniforms.bumpMap.value = material.bumpMap;
  50507. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  50508. uniforms.bumpScale.value = material.bumpScale;
  50509. if ( material.side === BackSide ) {
  50510. uniforms.bumpScale.value *= -1;
  50511. }
  50512. }
  50513. if ( material.normalMap ) {
  50514. uniforms.normalMap.value = material.normalMap;
  50515. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  50516. uniforms.normalScale.value.copy( material.normalScale );
  50517. if ( material.side === BackSide ) {
  50518. uniforms.normalScale.value.negate();
  50519. }
  50520. }
  50521. if ( material.displacementMap ) {
  50522. uniforms.displacementMap.value = material.displacementMap;
  50523. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  50524. uniforms.displacementScale.value = material.displacementScale;
  50525. uniforms.displacementBias.value = material.displacementBias;
  50526. }
  50527. if ( material.emissiveMap ) {
  50528. uniforms.emissiveMap.value = material.emissiveMap;
  50529. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  50530. }
  50531. if ( material.specularMap ) {
  50532. uniforms.specularMap.value = material.specularMap;
  50533. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  50534. }
  50535. if ( material.alphaTest > 0 ) {
  50536. uniforms.alphaTest.value = material.alphaTest;
  50537. }
  50538. const materialProperties = properties.get( material );
  50539. const envMap = materialProperties.envMap;
  50540. const envMapRotation = materialProperties.envMapRotation;
  50541. if ( envMap ) {
  50542. uniforms.envMap.value = envMap;
  50543. _e1.copy( envMapRotation );
  50544. // accommodate left-handed frame
  50545. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  50546. if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) {
  50547. // environment maps which are not cube render targets or PMREMs follow a different convention
  50548. _e1.y *= -1;
  50549. _e1.z *= -1;
  50550. }
  50551. uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) );
  50552. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  50553. uniforms.reflectivity.value = material.reflectivity;
  50554. uniforms.ior.value = material.ior;
  50555. uniforms.refractionRatio.value = material.refractionRatio;
  50556. }
  50557. if ( material.lightMap ) {
  50558. uniforms.lightMap.value = material.lightMap;
  50559. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  50560. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  50561. }
  50562. if ( material.aoMap ) {
  50563. uniforms.aoMap.value = material.aoMap;
  50564. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  50565. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  50566. }
  50567. }
  50568. function refreshUniformsLine( uniforms, material ) {
  50569. uniforms.diffuse.value.copy( material.color );
  50570. uniforms.opacity.value = material.opacity;
  50571. if ( material.map ) {
  50572. uniforms.map.value = material.map;
  50573. refreshTransformUniform( material.map, uniforms.mapTransform );
  50574. }
  50575. }
  50576. function refreshUniformsDash( uniforms, material ) {
  50577. uniforms.dashSize.value = material.dashSize;
  50578. uniforms.totalSize.value = material.dashSize + material.gapSize;
  50579. uniforms.scale.value = material.scale;
  50580. }
  50581. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  50582. uniforms.diffuse.value.copy( material.color );
  50583. uniforms.opacity.value = material.opacity;
  50584. uniforms.size.value = material.size * pixelRatio;
  50585. uniforms.scale.value = height * 0.5;
  50586. if ( material.map ) {
  50587. uniforms.map.value = material.map;
  50588. refreshTransformUniform( material.map, uniforms.uvTransform );
  50589. }
  50590. if ( material.alphaMap ) {
  50591. uniforms.alphaMap.value = material.alphaMap;
  50592. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  50593. }
  50594. if ( material.alphaTest > 0 ) {
  50595. uniforms.alphaTest.value = material.alphaTest;
  50596. }
  50597. }
  50598. function refreshUniformsSprites( uniforms, material ) {
  50599. uniforms.diffuse.value.copy( material.color );
  50600. uniforms.opacity.value = material.opacity;
  50601. uniforms.rotation.value = material.rotation;
  50602. if ( material.map ) {
  50603. uniforms.map.value = material.map;
  50604. refreshTransformUniform( material.map, uniforms.mapTransform );
  50605. }
  50606. if ( material.alphaMap ) {
  50607. uniforms.alphaMap.value = material.alphaMap;
  50608. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  50609. }
  50610. if ( material.alphaTest > 0 ) {
  50611. uniforms.alphaTest.value = material.alphaTest;
  50612. }
  50613. }
  50614. function refreshUniformsPhong( uniforms, material ) {
  50615. uniforms.specular.value.copy( material.specular );
  50616. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  50617. }
  50618. function refreshUniformsToon( uniforms, material ) {
  50619. if ( material.gradientMap ) {
  50620. uniforms.gradientMap.value = material.gradientMap;
  50621. }
  50622. }
  50623. function refreshUniformsStandard( uniforms, material ) {
  50624. uniforms.metalness.value = material.metalness;
  50625. if ( material.metalnessMap ) {
  50626. uniforms.metalnessMap.value = material.metalnessMap;
  50627. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  50628. }
  50629. uniforms.roughness.value = material.roughness;
  50630. if ( material.roughnessMap ) {
  50631. uniforms.roughnessMap.value = material.roughnessMap;
  50632. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  50633. }
  50634. if ( material.envMap ) {
  50635. //uniforms.envMap.value = material.envMap; // part of uniforms common
  50636. uniforms.envMapIntensity.value = material.envMapIntensity;
  50637. }
  50638. }
  50639. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  50640. uniforms.ior.value = material.ior; // also part of uniforms common
  50641. if ( material.sheen > 0 ) {
  50642. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  50643. uniforms.sheenRoughness.value = material.sheenRoughness;
  50644. if ( material.sheenColorMap ) {
  50645. uniforms.sheenColorMap.value = material.sheenColorMap;
  50646. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  50647. }
  50648. if ( material.sheenRoughnessMap ) {
  50649. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  50650. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  50651. }
  50652. }
  50653. if ( material.clearcoat > 0 ) {
  50654. uniforms.clearcoat.value = material.clearcoat;
  50655. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  50656. if ( material.clearcoatMap ) {
  50657. uniforms.clearcoatMap.value = material.clearcoatMap;
  50658. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  50659. }
  50660. if ( material.clearcoatRoughnessMap ) {
  50661. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  50662. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  50663. }
  50664. if ( material.clearcoatNormalMap ) {
  50665. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  50666. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  50667. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  50668. if ( material.side === BackSide ) {
  50669. uniforms.clearcoatNormalScale.value.negate();
  50670. }
  50671. }
  50672. }
  50673. if ( material.dispersion > 0 ) {
  50674. uniforms.dispersion.value = material.dispersion;
  50675. }
  50676. if ( material.iridescence > 0 ) {
  50677. uniforms.iridescence.value = material.iridescence;
  50678. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  50679. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  50680. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  50681. if ( material.iridescenceMap ) {
  50682. uniforms.iridescenceMap.value = material.iridescenceMap;
  50683. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  50684. }
  50685. if ( material.iridescenceThicknessMap ) {
  50686. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  50687. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  50688. }
  50689. }
  50690. if ( material.transmission > 0 ) {
  50691. uniforms.transmission.value = material.transmission;
  50692. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  50693. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  50694. if ( material.transmissionMap ) {
  50695. uniforms.transmissionMap.value = material.transmissionMap;
  50696. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  50697. }
  50698. uniforms.thickness.value = material.thickness;
  50699. if ( material.thicknessMap ) {
  50700. uniforms.thicknessMap.value = material.thicknessMap;
  50701. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  50702. }
  50703. uniforms.attenuationDistance.value = material.attenuationDistance;
  50704. uniforms.attenuationColor.value.copy( material.attenuationColor );
  50705. }
  50706. if ( material.anisotropy > 0 ) {
  50707. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  50708. if ( material.anisotropyMap ) {
  50709. uniforms.anisotropyMap.value = material.anisotropyMap;
  50710. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  50711. }
  50712. }
  50713. uniforms.specularIntensity.value = material.specularIntensity;
  50714. uniforms.specularColor.value.copy( material.specularColor );
  50715. if ( material.specularColorMap ) {
  50716. uniforms.specularColorMap.value = material.specularColorMap;
  50717. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  50718. }
  50719. if ( material.specularIntensityMap ) {
  50720. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  50721. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  50722. }
  50723. }
  50724. function refreshUniformsMatcap( uniforms, material ) {
  50725. if ( material.matcap ) {
  50726. uniforms.matcap.value = material.matcap;
  50727. }
  50728. }
  50729. function refreshUniformsDistance( uniforms, material ) {
  50730. const light = properties.get( material ).light;
  50731. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  50732. uniforms.nearDistance.value = light.shadow.camera.near;
  50733. uniforms.farDistance.value = light.shadow.camera.far;
  50734. }
  50735. return {
  50736. refreshFogUniforms: refreshFogUniforms,
  50737. refreshMaterialUniforms: refreshMaterialUniforms
  50738. };
  50739. }
  50740. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  50741. let buffers = {};
  50742. let updateList = {};
  50743. let allocatedBindingPoints = [];
  50744. const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program
  50745. function bind( uniformsGroup, program ) {
  50746. const webglProgram = program.program;
  50747. state.uniformBlockBinding( uniformsGroup, webglProgram );
  50748. }
  50749. function update( uniformsGroup, program ) {
  50750. let buffer = buffers[ uniformsGroup.id ];
  50751. if ( buffer === undefined ) {
  50752. prepareUniformsGroup( uniformsGroup );
  50753. buffer = createBuffer( uniformsGroup );
  50754. buffers[ uniformsGroup.id ] = buffer;
  50755. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  50756. }
  50757. // ensure to update the binding points/block indices mapping for this program
  50758. const webglProgram = program.program;
  50759. state.updateUBOMapping( uniformsGroup, webglProgram );
  50760. // update UBO once per frame
  50761. const frame = info.render.frame;
  50762. if ( updateList[ uniformsGroup.id ] !== frame ) {
  50763. updateBufferData( uniformsGroup );
  50764. updateList[ uniformsGroup.id ] = frame;
  50765. }
  50766. }
  50767. function createBuffer( uniformsGroup ) {
  50768. // the setup of an UBO is independent of a particular shader program but global
  50769. const bindingPointIndex = allocateBindingPointIndex();
  50770. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  50771. const buffer = gl.createBuffer();
  50772. const size = uniformsGroup.__size;
  50773. const usage = uniformsGroup.usage;
  50774. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  50775. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  50776. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  50777. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  50778. return buffer;
  50779. }
  50780. function allocateBindingPointIndex() {
  50781. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  50782. if ( allocatedBindingPoints.indexOf( i ) === -1 ) {
  50783. allocatedBindingPoints.push( i );
  50784. return i;
  50785. }
  50786. }
  50787. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  50788. return 0;
  50789. }
  50790. function updateBufferData( uniformsGroup ) {
  50791. const buffer = buffers[ uniformsGroup.id ];
  50792. const uniforms = uniformsGroup.uniforms;
  50793. const cache = uniformsGroup.__cache;
  50794. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  50795. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  50796. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  50797. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  50798. const uniform = uniformArray[ j ];
  50799. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  50800. const offset = uniform.__offset;
  50801. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  50802. let arrayOffset = 0;
  50803. for ( let k = 0; k < values.length; k ++ ) {
  50804. const value = values[ k ];
  50805. const info = getUniformSize( value );
  50806. // TODO add integer and struct support
  50807. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  50808. uniform.__data[ 0 ] = value;
  50809. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  50810. } else if ( value.isMatrix3 ) {
  50811. // manually converting 3x3 to 3x4
  50812. uniform.__data[ 0 ] = value.elements[ 0 ];
  50813. uniform.__data[ 1 ] = value.elements[ 1 ];
  50814. uniform.__data[ 2 ] = value.elements[ 2 ];
  50815. uniform.__data[ 3 ] = 0;
  50816. uniform.__data[ 4 ] = value.elements[ 3 ];
  50817. uniform.__data[ 5 ] = value.elements[ 4 ];
  50818. uniform.__data[ 6 ] = value.elements[ 5 ];
  50819. uniform.__data[ 7 ] = 0;
  50820. uniform.__data[ 8 ] = value.elements[ 6 ];
  50821. uniform.__data[ 9 ] = value.elements[ 7 ];
  50822. uniform.__data[ 10 ] = value.elements[ 8 ];
  50823. uniform.__data[ 11 ] = 0;
  50824. } else {
  50825. value.toArray( uniform.__data, arrayOffset );
  50826. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  50827. }
  50828. }
  50829. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  50830. }
  50831. }
  50832. }
  50833. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  50834. }
  50835. function hasUniformChanged( uniform, index, indexArray, cache ) {
  50836. const value = uniform.value;
  50837. const indexString = index + '_' + indexArray;
  50838. if ( cache[ indexString ] === undefined ) {
  50839. // cache entry does not exist so far
  50840. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  50841. cache[ indexString ] = value;
  50842. } else {
  50843. cache[ indexString ] = value.clone();
  50844. }
  50845. return true;
  50846. } else {
  50847. const cachedObject = cache[ indexString ];
  50848. // compare current value with cached entry
  50849. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  50850. if ( cachedObject !== value ) {
  50851. cache[ indexString ] = value;
  50852. return true;
  50853. }
  50854. } else {
  50855. if ( cachedObject.equals( value ) === false ) {
  50856. cachedObject.copy( value );
  50857. return true;
  50858. }
  50859. }
  50860. }
  50861. return false;
  50862. }
  50863. function prepareUniformsGroup( uniformsGroup ) {
  50864. // determine total buffer size according to the STD140 layout
  50865. // Hint: STD140 is the only supported layout in WebGL 2
  50866. const uniforms = uniformsGroup.uniforms;
  50867. let offset = 0; // global buffer offset in bytes
  50868. const chunkSize = 16; // size of a chunk in bytes
  50869. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  50870. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  50871. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  50872. const uniform = uniformArray[ j ];
  50873. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  50874. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  50875. const value = values[ k ];
  50876. const info = getUniformSize( value );
  50877. const chunkOffset = offset % chunkSize; // offset in the current chunk
  50878. const chunkPadding = chunkOffset % info.boundary; // required padding to match boundary
  50879. const chunkStart = chunkOffset + chunkPadding; // the start position in the current chunk for the data
  50880. offset += chunkPadding;
  50881. // Check for chunk overflow
  50882. if ( chunkStart !== 0 && ( chunkSize - chunkStart ) < info.storage ) {
  50883. // Add padding and adjust offset
  50884. offset += ( chunkSize - chunkStart );
  50885. }
  50886. // the following two properties will be used for partial buffer updates
  50887. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  50888. uniform.__offset = offset;
  50889. // Update the global offset
  50890. offset += info.storage;
  50891. }
  50892. }
  50893. }
  50894. // ensure correct final padding
  50895. const chunkOffset = offset % chunkSize;
  50896. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  50897. //
  50898. uniformsGroup.__size = offset;
  50899. uniformsGroup.__cache = {};
  50900. return this;
  50901. }
  50902. function getUniformSize( value ) {
  50903. const info = {
  50904. boundary: 0, // bytes
  50905. storage: 0 // bytes
  50906. };
  50907. // determine sizes according to STD140
  50908. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  50909. // float/int/bool
  50910. info.boundary = 4;
  50911. info.storage = 4;
  50912. } else if ( value.isVector2 ) {
  50913. // vec2
  50914. info.boundary = 8;
  50915. info.storage = 8;
  50916. } else if ( value.isVector3 || value.isColor ) {
  50917. // vec3
  50918. info.boundary = 16;
  50919. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  50920. } else if ( value.isVector4 ) {
  50921. // vec4
  50922. info.boundary = 16;
  50923. info.storage = 16;
  50924. } else if ( value.isMatrix3 ) {
  50925. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  50926. info.boundary = 48;
  50927. info.storage = 48;
  50928. } else if ( value.isMatrix4 ) {
  50929. // mat4
  50930. info.boundary = 64;
  50931. info.storage = 64;
  50932. } else if ( value.isTexture ) {
  50933. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  50934. } else {
  50935. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  50936. }
  50937. return info;
  50938. }
  50939. function onUniformsGroupsDispose( event ) {
  50940. const uniformsGroup = event.target;
  50941. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  50942. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  50943. allocatedBindingPoints.splice( index, 1 );
  50944. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  50945. delete buffers[ uniformsGroup.id ];
  50946. delete updateList[ uniformsGroup.id ];
  50947. }
  50948. function dispose() {
  50949. for ( const id in buffers ) {
  50950. gl.deleteBuffer( buffers[ id ] );
  50951. }
  50952. allocatedBindingPoints = [];
  50953. buffers = {};
  50954. updateList = {};
  50955. }
  50956. return {
  50957. bind: bind,
  50958. update: update,
  50959. dispose: dispose
  50960. };
  50961. }
  50962. /**
  50963. * This renderer uses WebGL 2 to display scenes.
  50964. *
  50965. * WebGL 1 is not supported since `r163`.
  50966. */
  50967. class WebGLRenderer {
  50968. /**
  50969. * Constructs a new WebGL renderer.
  50970. *
  50971. * @param {WebGLRenderer~Options} [parameters] - The configuration parameter.
  50972. */
  50973. constructor( parameters = {} ) {
  50974. const {
  50975. canvas = createCanvasElement(),
  50976. context = null,
  50977. depth = true,
  50978. stencil = false,
  50979. alpha = false,
  50980. antialias = false,
  50981. premultipliedAlpha = true,
  50982. preserveDrawingBuffer = false,
  50983. powerPreference = 'default',
  50984. failIfMajorPerformanceCaveat = false,
  50985. reverseDepthBuffer = false,
  50986. } = parameters;
  50987. /**
  50988. * This flag can be used for type testing.
  50989. *
  50990. * @type {boolean}
  50991. * @readonly
  50992. * @default true
  50993. */
  50994. this.isWebGLRenderer = true;
  50995. let _alpha;
  50996. if ( context !== null ) {
  50997. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  50998. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  50999. }
  51000. _alpha = context.getContextAttributes().alpha;
  51001. } else {
  51002. _alpha = alpha;
  51003. }
  51004. const uintClearColor = new Uint32Array( 4 );
  51005. const intClearColor = new Int32Array( 4 );
  51006. let currentRenderList = null;
  51007. let currentRenderState = null;
  51008. // render() can be called from within a callback triggered by another render.
  51009. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  51010. const renderListStack = [];
  51011. const renderStateStack = [];
  51012. // public properties
  51013. /**
  51014. * A canvas where the renderer draws its output.This is automatically created by the renderer
  51015. * in the constructor (if not provided already); you just need to add it to your page like so:
  51016. * ```js
  51017. * document.body.appendChild( renderer.domElement );
  51018. * ```
  51019. *
  51020. * @type {DOMElement}
  51021. */
  51022. this.domElement = canvas;
  51023. /**
  51024. * A object with debug configuration settings.
  51025. *
  51026. * - `checkShaderErrors`: If it is `true`, defines whether material shader programs are
  51027. * checked for errors during compilation and linkage process. It may be useful to disable
  51028. * this check in production for performance gain. It is strongly recommended to keep these
  51029. * checks enabled during development. If the shader does not compile and link - it will not
  51030. * work and associated material will not render.
  51031. * - `onShaderError(gl, program, glVertexShader,glFragmentShader)`: A callback function that
  51032. * can be used for custom error reporting. The callback receives the WebGL context, an instance
  51033. * of WebGLProgram as well two instances of WebGLShader representing the vertex and fragment shader.
  51034. * Assigning a custom function disables the default error reporting.
  51035. *
  51036. * @type {Object}
  51037. */
  51038. this.debug = {
  51039. /**
  51040. * Enables error checking and reporting when shader programs are being compiled.
  51041. * @type {boolean}
  51042. */
  51043. checkShaderErrors: true,
  51044. /**
  51045. * Callback for custom error reporting.
  51046. * @type {?Function}
  51047. */
  51048. onShaderError: null
  51049. };
  51050. // clearing
  51051. /**
  51052. * Whether the renderer should automatically clear its output before rendering a frame or not.
  51053. *
  51054. * @type {boolean}
  51055. * @default true
  51056. */
  51057. this.autoClear = true;
  51058. /**
  51059. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  51060. * the color buffer or not.
  51061. *
  51062. * @type {boolean}
  51063. * @default true
  51064. */
  51065. this.autoClearColor = true;
  51066. /**
  51067. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  51068. * the depth buffer or not.
  51069. *
  51070. * @type {boolean}
  51071. * @default true
  51072. */
  51073. this.autoClearDepth = true;
  51074. /**
  51075. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  51076. * the stencil buffer or not.
  51077. *
  51078. * @type {boolean}
  51079. * @default true
  51080. */
  51081. this.autoClearStencil = true;
  51082. // scene graph
  51083. /**
  51084. * Whether the renderer should sort objects or not.
  51085. *
  51086. * Note: Sorting is used to attempt to properly render objects that have some
  51087. * degree of transparency. By definition, sorting objects may not work in all
  51088. * cases. Depending on the needs of application, it may be necessary to turn
  51089. * off sorting and use other methods to deal with transparency rendering e.g.
  51090. * manually determining each object's rendering order.
  51091. *
  51092. * @type {boolean}
  51093. * @default true
  51094. */
  51095. this.sortObjects = true;
  51096. // user-defined clipping
  51097. /**
  51098. * User-defined clipping planes specified in world space. These planes apply globally.
  51099. * Points in space whose dot product with the plane is negative are cut away.
  51100. *
  51101. * @type {Array<Plane>}
  51102. */
  51103. this.clippingPlanes = [];
  51104. /**
  51105. * Whether the renderer respects object-level clipping planes or not.
  51106. *
  51107. * @type {boolean}
  51108. * @default false
  51109. */
  51110. this.localClippingEnabled = false;
  51111. // tone mapping
  51112. /**
  51113. * The tone mapping technique of the renderer.
  51114. *
  51115. * @type {(NoToneMapping|LinearToneMapping|ReinhardToneMapping|CineonToneMapping|ACESFilmicToneMapping|CustomToneMapping|AgXToneMapping|NeutralToneMapping)}
  51116. * @default NoToneMapping
  51117. */
  51118. this.toneMapping = NoToneMapping;
  51119. /**
  51120. * Exposure level of tone mapping.
  51121. *
  51122. * @type {number}
  51123. * @default 1
  51124. */
  51125. this.toneMappingExposure = 1.0;
  51126. // transmission
  51127. /**
  51128. * The normalized resolution scale for the transmission render target, measured in percentage
  51129. * of viewport dimensions. Lowering this value can result in significant performance improvements
  51130. * when using {@link MeshPhysicalMaterial#transmission}.
  51131. *
  51132. * @type {number}
  51133. * @default 1
  51134. */
  51135. this.transmissionResolutionScale = 1.0;
  51136. // internal properties
  51137. const _this = this;
  51138. let _isContextLost = false;
  51139. // internal state cache
  51140. this._outputColorSpace = SRGBColorSpace;
  51141. let _currentActiveCubeFace = 0;
  51142. let _currentActiveMipmapLevel = 0;
  51143. let _currentRenderTarget = null;
  51144. let _currentMaterialId = -1;
  51145. let _currentCamera = null;
  51146. const _currentViewport = new Vector4();
  51147. const _currentScissor = new Vector4();
  51148. let _currentScissorTest = null;
  51149. const _currentClearColor = new Color( 0x000000 );
  51150. let _currentClearAlpha = 0;
  51151. //
  51152. let _width = canvas.width;
  51153. let _height = canvas.height;
  51154. let _pixelRatio = 1;
  51155. let _opaqueSort = null;
  51156. let _transparentSort = null;
  51157. const _viewport = new Vector4( 0, 0, _width, _height );
  51158. const _scissor = new Vector4( 0, 0, _width, _height );
  51159. let _scissorTest = false;
  51160. // frustum
  51161. const _frustum = new Frustum();
  51162. // clipping
  51163. let _clippingEnabled = false;
  51164. let _localClippingEnabled = false;
  51165. // camera matrices cache
  51166. const _currentProjectionMatrix = new Matrix4();
  51167. const _projScreenMatrix = new Matrix4();
  51168. const _vector3 = new Vector3();
  51169. const _vector4 = new Vector4();
  51170. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  51171. let _renderBackground = false;
  51172. function getTargetPixelRatio() {
  51173. return _currentRenderTarget === null ? _pixelRatio : 1;
  51174. }
  51175. // initialize
  51176. let _gl = context;
  51177. function getContext( contextName, contextAttributes ) {
  51178. return canvas.getContext( contextName, contextAttributes );
  51179. }
  51180. try {
  51181. const contextAttributes = {
  51182. alpha: true,
  51183. depth,
  51184. stencil,
  51185. antialias,
  51186. premultipliedAlpha,
  51187. preserveDrawingBuffer,
  51188. powerPreference,
  51189. failIfMajorPerformanceCaveat,
  51190. };
  51191. // OffscreenCanvas does not have setAttribute, see #22811
  51192. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  51193. // event listeners must be registered before WebGL context is created, see #12753
  51194. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  51195. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  51196. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  51197. if ( _gl === null ) {
  51198. const contextName = 'webgl2';
  51199. _gl = getContext( contextName, contextAttributes );
  51200. if ( _gl === null ) {
  51201. if ( getContext( contextName ) ) {
  51202. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  51203. } else {
  51204. throw new Error( 'Error creating WebGL context.' );
  51205. }
  51206. }
  51207. }
  51208. } catch ( error ) {
  51209. console.error( 'THREE.WebGLRenderer: ' + error.message );
  51210. throw error;
  51211. }
  51212. let extensions, capabilities, state, info;
  51213. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  51214. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  51215. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  51216. let utils, bindingStates, uniformsGroups;
  51217. function initGLContext() {
  51218. extensions = new WebGLExtensions( _gl );
  51219. extensions.init();
  51220. utils = new WebGLUtils( _gl, extensions );
  51221. capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils );
  51222. state = new WebGLState( _gl, extensions );
  51223. if ( capabilities.reverseDepthBuffer && reverseDepthBuffer ) {
  51224. state.buffers.depth.setReversed( true );
  51225. }
  51226. info = new WebGLInfo( _gl );
  51227. properties = new WebGLProperties();
  51228. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  51229. cubemaps = new WebGLCubeMaps( _this );
  51230. cubeuvmaps = new WebGLCubeUVMaps( _this );
  51231. attributes = new WebGLAttributes( _gl );
  51232. bindingStates = new WebGLBindingStates( _gl, attributes );
  51233. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  51234. objects = new WebGLObjects( _gl, geometries, attributes, info );
  51235. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  51236. clipping = new WebGLClipping( properties );
  51237. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  51238. materials = new WebGLMaterials( _this, properties );
  51239. renderLists = new WebGLRenderLists();
  51240. renderStates = new WebGLRenderStates( extensions );
  51241. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  51242. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  51243. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  51244. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  51245. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  51246. info.programs = programCache.programs;
  51247. /**
  51248. * Holds details about the capabilities of the current rendering context.
  51249. *
  51250. * @name WebGLRenderer#capabilities
  51251. * @type {WebGLRenderer~Capabilities}
  51252. */
  51253. _this.capabilities = capabilities;
  51254. /**
  51255. * Provides methods for retrieving and testing WebGL extensions.
  51256. *
  51257. * - `get(extensionName:string)`: Used to check whether a WebGL extension is supported
  51258. * and return the extension object if available.
  51259. * - `has(extensionName:string)`: returns `true` if the extension is supported.
  51260. *
  51261. * @name WebGLRenderer#extensions
  51262. * @type {Object}
  51263. */
  51264. _this.extensions = extensions;
  51265. /**
  51266. * Used to track properties of other objects like native WebGL objects.
  51267. *
  51268. * @name WebGLRenderer#properties
  51269. * @type {Object}
  51270. */
  51271. _this.properties = properties;
  51272. /**
  51273. * Manages the render lists of the renderer.
  51274. *
  51275. * @name WebGLRenderer#renderLists
  51276. * @type {Object}
  51277. */
  51278. _this.renderLists = renderLists;
  51279. /**
  51280. * Interface for managing shadows.
  51281. *
  51282. * @name WebGLRenderer#shadowMap
  51283. * @type {WebGLRenderer~ShadowMap}
  51284. */
  51285. _this.shadowMap = shadowMap;
  51286. /**
  51287. * Interface for managing the WebGL state.
  51288. *
  51289. * @name WebGLRenderer#state
  51290. * @type {Object}
  51291. */
  51292. _this.state = state;
  51293. /**
  51294. * Holds a series of statistical information about the GPU memory
  51295. * and the rendering process. Useful for debugging and monitoring.
  51296. *
  51297. * By default these data are reset at each render call but when having
  51298. * multiple render passes per frame (e.g. when using post processing) it can
  51299. * be preferred to reset with a custom pattern. First, set `autoReset` to
  51300. * `false`.
  51301. * ```js
  51302. * renderer.info.autoReset = false;
  51303. * ```
  51304. * Call `reset()` whenever you have finished to render a single frame.
  51305. * ```js
  51306. * renderer.info.reset();
  51307. * ```
  51308. *
  51309. * @name WebGLRenderer#info
  51310. * @type {WebGLRenderer~Info}
  51311. */
  51312. _this.info = info;
  51313. }
  51314. initGLContext();
  51315. // xr
  51316. const xr = new WebXRManager( _this, _gl );
  51317. /**
  51318. * A reference to the XR manager.
  51319. *
  51320. * @type {WebXRManager}
  51321. */
  51322. this.xr = xr;
  51323. /**
  51324. * Returns the rendering context.
  51325. *
  51326. * @return {WebGL2RenderingContext} The rendering context.
  51327. */
  51328. this.getContext = function () {
  51329. return _gl;
  51330. };
  51331. /**
  51332. * Returns the rendering context attributes.
  51333. *
  51334. * @return {WebGLContextAttributes} The rendering context attributes.
  51335. */
  51336. this.getContextAttributes = function () {
  51337. return _gl.getContextAttributes();
  51338. };
  51339. /**
  51340. * Simulates a loss of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  51341. */
  51342. this.forceContextLoss = function () {
  51343. const extension = extensions.get( 'WEBGL_lose_context' );
  51344. if ( extension ) extension.loseContext();
  51345. };
  51346. /**
  51347. * Simulates a restore of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  51348. */
  51349. this.forceContextRestore = function () {
  51350. const extension = extensions.get( 'WEBGL_lose_context' );
  51351. if ( extension ) extension.restoreContext();
  51352. };
  51353. /**
  51354. * Returns the pixel ratio.
  51355. *
  51356. * @return {number} The pixel ratio.
  51357. */
  51358. this.getPixelRatio = function () {
  51359. return _pixelRatio;
  51360. };
  51361. /**
  51362. * Sets the given pixel ratio and resizes the canvas if necessary.
  51363. *
  51364. * @param {number} value - The pixel ratio.
  51365. */
  51366. this.setPixelRatio = function ( value ) {
  51367. if ( value === undefined ) return;
  51368. _pixelRatio = value;
  51369. this.setSize( _width, _height, false );
  51370. };
  51371. /**
  51372. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  51373. *
  51374. * @param {Vector2} target - The method writes the result in this target object.
  51375. * @return {Vector2} The renderer's size in logical pixels.
  51376. */
  51377. this.getSize = function ( target ) {
  51378. return target.set( _width, _height );
  51379. };
  51380. /**
  51381. * Resizes the output canvas to (width, height) with device pixel ratio taken
  51382. * into account, and also sets the viewport to fit that size, starting in (0,
  51383. * 0). Setting `updateStyle` to false prevents any style changes to the output canvas.
  51384. *
  51385. * @param {number} width - The width in logical pixels.
  51386. * @param {number} height - The height in logical pixels.
  51387. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  51388. */
  51389. this.setSize = function ( width, height, updateStyle = true ) {
  51390. if ( xr.isPresenting ) {
  51391. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  51392. return;
  51393. }
  51394. _width = width;
  51395. _height = height;
  51396. canvas.width = Math.floor( width * _pixelRatio );
  51397. canvas.height = Math.floor( height * _pixelRatio );
  51398. if ( updateStyle === true ) {
  51399. canvas.style.width = width + 'px';
  51400. canvas.style.height = height + 'px';
  51401. }
  51402. this.setViewport( 0, 0, width, height );
  51403. };
  51404. /**
  51405. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  51406. *
  51407. * @param {Vector2} target - The method writes the result in this target object.
  51408. * @return {Vector2} The drawing buffer size.
  51409. */
  51410. this.getDrawingBufferSize = function ( target ) {
  51411. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  51412. };
  51413. /**
  51414. * This method allows to define the drawing buffer size by specifying
  51415. * width, height and pixel ratio all at once. The size of the drawing
  51416. * buffer is computed with this formula:
  51417. * ```js
  51418. * size.x = width * pixelRatio;
  51419. * size.y = height * pixelRatio;
  51420. * ```
  51421. *
  51422. * @param {number} width - The width in logical pixels.
  51423. * @param {number} height - The height in logical pixels.
  51424. * @param {number} pixelRatio - The pixel ratio.
  51425. */
  51426. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  51427. _width = width;
  51428. _height = height;
  51429. _pixelRatio = pixelRatio;
  51430. canvas.width = Math.floor( width * pixelRatio );
  51431. canvas.height = Math.floor( height * pixelRatio );
  51432. this.setViewport( 0, 0, width, height );
  51433. };
  51434. /**
  51435. * Returns the current viewport definition.
  51436. *
  51437. * @param {Vector2} target - The method writes the result in this target object.
  51438. * @return {Vector2} The current viewport definition.
  51439. */
  51440. this.getCurrentViewport = function ( target ) {
  51441. return target.copy( _currentViewport );
  51442. };
  51443. /**
  51444. * Returns the viewport definition.
  51445. *
  51446. * @param {Vector4} target - The method writes the result in this target object.
  51447. * @return {Vector4} The viewport definition.
  51448. */
  51449. this.getViewport = function ( target ) {
  51450. return target.copy( _viewport );
  51451. };
  51452. /**
  51453. * Sets the viewport to render from `(x, y)` to `(x + width, y + height)`.
  51454. *
  51455. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  51456. * Or alternatively a four-component vector specifying all the parameters of the viewport.
  51457. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  51458. * @param {number} width - The width of the viewport in logical pixel unit.
  51459. * @param {number} height - The height of the viewport in logical pixel unit.
  51460. */
  51461. this.setViewport = function ( x, y, width, height ) {
  51462. if ( x.isVector4 ) {
  51463. _viewport.set( x.x, x.y, x.z, x.w );
  51464. } else {
  51465. _viewport.set( x, y, width, height );
  51466. }
  51467. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  51468. };
  51469. /**
  51470. * Returns the scissor region.
  51471. *
  51472. * @param {Vector4} target - The method writes the result in this target object.
  51473. * @return {Vector4} The scissor region.
  51474. */
  51475. this.getScissor = function ( target ) {
  51476. return target.copy( _scissor );
  51477. };
  51478. /**
  51479. * Sets the scissor region to render from `(x, y)` to `(x + width, y + height)`.
  51480. *
  51481. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  51482. * Or alternatively a four-component vector specifying all the parameters of the scissor region.
  51483. * @param {number} y - The vertical coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  51484. * @param {number} width - The width of the scissor region in logical pixel unit.
  51485. * @param {number} height - The height of the scissor region in logical pixel unit.
  51486. */
  51487. this.setScissor = function ( x, y, width, height ) {
  51488. if ( x.isVector4 ) {
  51489. _scissor.set( x.x, x.y, x.z, x.w );
  51490. } else {
  51491. _scissor.set( x, y, width, height );
  51492. }
  51493. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  51494. };
  51495. /**
  51496. * Returns `true` if the scissor test is enabled.
  51497. *
  51498. * @return {boolean} Whether the scissor test is enabled or not.
  51499. */
  51500. this.getScissorTest = function () {
  51501. return _scissorTest;
  51502. };
  51503. /**
  51504. * Enable or disable the scissor test. When this is enabled, only the pixels
  51505. * within the defined scissor area will be affected by further renderer
  51506. * actions.
  51507. *
  51508. * @param {boolean} boolean - Whether the scissor test is enabled or not.
  51509. */
  51510. this.setScissorTest = function ( boolean ) {
  51511. state.setScissorTest( _scissorTest = boolean );
  51512. };
  51513. /**
  51514. * Sets a custom opaque sort function for the render lists. Pass `null`
  51515. * to use the default `painterSortStable` function.
  51516. *
  51517. * @param {?Function} method - The opaque sort function.
  51518. */
  51519. this.setOpaqueSort = function ( method ) {
  51520. _opaqueSort = method;
  51521. };
  51522. /**
  51523. * Sets a custom transparent sort function for the render lists. Pass `null`
  51524. * to use the default `reversePainterSortStable` function.
  51525. *
  51526. * @param {?Function} method - The opaque sort function.
  51527. */
  51528. this.setTransparentSort = function ( method ) {
  51529. _transparentSort = method;
  51530. };
  51531. // Clearing
  51532. /**
  51533. * Returns the clear color.
  51534. *
  51535. * @param {Color} target - The method writes the result in this target object.
  51536. * @return {Color} The clear color.
  51537. */
  51538. this.getClearColor = function ( target ) {
  51539. return target.copy( background.getClearColor() );
  51540. };
  51541. /**
  51542. * Sets the clear color and alpha.
  51543. *
  51544. * @param {Color} color - The clear color.
  51545. * @param {number} [alpha=1] - The clear alpha.
  51546. */
  51547. this.setClearColor = function () {
  51548. background.setClearColor( ...arguments );
  51549. };
  51550. /**
  51551. * Returns the clear alpha. Ranges within `[0,1]`.
  51552. *
  51553. * @return {number} The clear alpha.
  51554. */
  51555. this.getClearAlpha = function () {
  51556. return background.getClearAlpha();
  51557. };
  51558. /**
  51559. * Sets the clear alpha.
  51560. *
  51561. * @param {number} alpha - The clear alpha.
  51562. */
  51563. this.setClearAlpha = function () {
  51564. background.setClearAlpha( ...arguments );
  51565. };
  51566. /**
  51567. * Tells the renderer to clear its color, depth or stencil drawing buffer(s).
  51568. * This method initializes the buffers to the current clear color values.
  51569. *
  51570. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  51571. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  51572. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  51573. */
  51574. this.clear = function ( color = true, depth = true, stencil = true ) {
  51575. let bits = 0;
  51576. if ( color ) {
  51577. // check if we're trying to clear an integer target
  51578. let isIntegerFormat = false;
  51579. if ( _currentRenderTarget !== null ) {
  51580. const targetFormat = _currentRenderTarget.texture.format;
  51581. isIntegerFormat = targetFormat === RGBAIntegerFormat ||
  51582. targetFormat === RGIntegerFormat ||
  51583. targetFormat === RedIntegerFormat;
  51584. }
  51585. // use the appropriate clear functions to clear the target if it's a signed
  51586. // or unsigned integer target
  51587. if ( isIntegerFormat ) {
  51588. const targetType = _currentRenderTarget.texture.type;
  51589. const isUnsignedType = targetType === UnsignedByteType ||
  51590. targetType === UnsignedIntType ||
  51591. targetType === UnsignedShortType ||
  51592. targetType === UnsignedInt248Type ||
  51593. targetType === UnsignedShort4444Type ||
  51594. targetType === UnsignedShort5551Type;
  51595. const clearColor = background.getClearColor();
  51596. const a = background.getClearAlpha();
  51597. const r = clearColor.r;
  51598. const g = clearColor.g;
  51599. const b = clearColor.b;
  51600. if ( isUnsignedType ) {
  51601. uintClearColor[ 0 ] = r;
  51602. uintClearColor[ 1 ] = g;
  51603. uintClearColor[ 2 ] = b;
  51604. uintClearColor[ 3 ] = a;
  51605. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  51606. } else {
  51607. intClearColor[ 0 ] = r;
  51608. intClearColor[ 1 ] = g;
  51609. intClearColor[ 2 ] = b;
  51610. intClearColor[ 3 ] = a;
  51611. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  51612. }
  51613. } else {
  51614. bits |= _gl.COLOR_BUFFER_BIT;
  51615. }
  51616. }
  51617. if ( depth ) {
  51618. bits |= _gl.DEPTH_BUFFER_BIT;
  51619. }
  51620. if ( stencil ) {
  51621. bits |= _gl.STENCIL_BUFFER_BIT;
  51622. this.state.buffers.stencil.setMask( 0xffffffff );
  51623. }
  51624. _gl.clear( bits );
  51625. };
  51626. /**
  51627. * Clears the color buffer. Equivalent to calling `renderer.clear( true, false, false )`.
  51628. */
  51629. this.clearColor = function () {
  51630. this.clear( true, false, false );
  51631. };
  51632. /**
  51633. * Clears the depth buffer. Equivalent to calling `renderer.clear( false, true, false )`.
  51634. */
  51635. this.clearDepth = function () {
  51636. this.clear( false, true, false );
  51637. };
  51638. /**
  51639. * Clears the stencil buffer. Equivalent to calling `renderer.clear( false, false, true )`.
  51640. */
  51641. this.clearStencil = function () {
  51642. this.clear( false, false, true );
  51643. };
  51644. /**
  51645. * Frees the GPU-related resources allocated by this instance. Call this
  51646. * method whenever this instance is no longer used in your app.
  51647. */
  51648. this.dispose = function () {
  51649. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  51650. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  51651. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  51652. background.dispose();
  51653. renderLists.dispose();
  51654. renderStates.dispose();
  51655. properties.dispose();
  51656. cubemaps.dispose();
  51657. cubeuvmaps.dispose();
  51658. objects.dispose();
  51659. bindingStates.dispose();
  51660. uniformsGroups.dispose();
  51661. programCache.dispose();
  51662. xr.dispose();
  51663. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  51664. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  51665. animation.stop();
  51666. };
  51667. // Events
  51668. function onContextLost( event ) {
  51669. event.preventDefault();
  51670. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  51671. _isContextLost = true;
  51672. }
  51673. function onContextRestore( /* event */ ) {
  51674. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  51675. _isContextLost = false;
  51676. const infoAutoReset = info.autoReset;
  51677. const shadowMapEnabled = shadowMap.enabled;
  51678. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  51679. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  51680. const shadowMapType = shadowMap.type;
  51681. initGLContext();
  51682. info.autoReset = infoAutoReset;
  51683. shadowMap.enabled = shadowMapEnabled;
  51684. shadowMap.autoUpdate = shadowMapAutoUpdate;
  51685. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  51686. shadowMap.type = shadowMapType;
  51687. }
  51688. function onContextCreationError( event ) {
  51689. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  51690. }
  51691. function onMaterialDispose( event ) {
  51692. const material = event.target;
  51693. material.removeEventListener( 'dispose', onMaterialDispose );
  51694. deallocateMaterial( material );
  51695. }
  51696. // Buffer deallocation
  51697. function deallocateMaterial( material ) {
  51698. releaseMaterialProgramReferences( material );
  51699. properties.remove( material );
  51700. }
  51701. function releaseMaterialProgramReferences( material ) {
  51702. const programs = properties.get( material ).programs;
  51703. if ( programs !== undefined ) {
  51704. programs.forEach( function ( program ) {
  51705. programCache.releaseProgram( program );
  51706. } );
  51707. if ( material.isShaderMaterial ) {
  51708. programCache.releaseShaderCache( material );
  51709. }
  51710. }
  51711. }
  51712. // Buffer rendering
  51713. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  51714. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  51715. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  51716. const program = setProgram( camera, scene, geometry, material, object );
  51717. state.setMaterial( material, frontFaceCW );
  51718. //
  51719. let index = geometry.index;
  51720. let rangeFactor = 1;
  51721. if ( material.wireframe === true ) {
  51722. index = geometries.getWireframeAttribute( geometry );
  51723. if ( index === undefined ) return;
  51724. rangeFactor = 2;
  51725. }
  51726. //
  51727. const drawRange = geometry.drawRange;
  51728. const position = geometry.attributes.position;
  51729. let drawStart = drawRange.start * rangeFactor;
  51730. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  51731. if ( group !== null ) {
  51732. drawStart = Math.max( drawStart, group.start * rangeFactor );
  51733. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  51734. }
  51735. if ( index !== null ) {
  51736. drawStart = Math.max( drawStart, 0 );
  51737. drawEnd = Math.min( drawEnd, index.count );
  51738. } else if ( position !== undefined && position !== null ) {
  51739. drawStart = Math.max( drawStart, 0 );
  51740. drawEnd = Math.min( drawEnd, position.count );
  51741. }
  51742. const drawCount = drawEnd - drawStart;
  51743. if ( drawCount < 0 || drawCount === Infinity ) return;
  51744. //
  51745. bindingStates.setup( object, material, program, geometry, index );
  51746. let attribute;
  51747. let renderer = bufferRenderer;
  51748. if ( index !== null ) {
  51749. attribute = attributes.get( index );
  51750. renderer = indexedBufferRenderer;
  51751. renderer.setIndex( attribute );
  51752. }
  51753. //
  51754. if ( object.isMesh ) {
  51755. if ( material.wireframe === true ) {
  51756. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  51757. renderer.setMode( _gl.LINES );
  51758. } else {
  51759. renderer.setMode( _gl.TRIANGLES );
  51760. }
  51761. } else if ( object.isLine ) {
  51762. let lineWidth = material.linewidth;
  51763. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  51764. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  51765. if ( object.isLineSegments ) {
  51766. renderer.setMode( _gl.LINES );
  51767. } else if ( object.isLineLoop ) {
  51768. renderer.setMode( _gl.LINE_LOOP );
  51769. } else {
  51770. renderer.setMode( _gl.LINE_STRIP );
  51771. }
  51772. } else if ( object.isPoints ) {
  51773. renderer.setMode( _gl.POINTS );
  51774. } else if ( object.isSprite ) {
  51775. renderer.setMode( _gl.TRIANGLES );
  51776. }
  51777. if ( object.isBatchedMesh ) {
  51778. if ( object._multiDrawInstances !== null ) {
  51779. // @deprecated, r174
  51780. warnOnce( 'THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  51781. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  51782. } else {
  51783. if ( ! extensions.get( 'WEBGL_multi_draw' ) ) {
  51784. const starts = object._multiDrawStarts;
  51785. const counts = object._multiDrawCounts;
  51786. const drawCount = object._multiDrawCount;
  51787. const bytesPerElement = index ? attributes.get( index ).bytesPerElement : 1;
  51788. const uniforms = properties.get( material ).currentProgram.getUniforms();
  51789. for ( let i = 0; i < drawCount; i ++ ) {
  51790. uniforms.setValue( _gl, '_gl_DrawID', i );
  51791. renderer.render( starts[ i ] / bytesPerElement, counts[ i ] );
  51792. }
  51793. } else {
  51794. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  51795. }
  51796. }
  51797. } else if ( object.isInstancedMesh ) {
  51798. renderer.renderInstances( drawStart, drawCount, object.count );
  51799. } else if ( geometry.isInstancedBufferGeometry ) {
  51800. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  51801. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  51802. renderer.renderInstances( drawStart, drawCount, instanceCount );
  51803. } else {
  51804. renderer.render( drawStart, drawCount );
  51805. }
  51806. };
  51807. // Compile
  51808. function prepareMaterial( material, scene, object ) {
  51809. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  51810. material.side = BackSide;
  51811. material.needsUpdate = true;
  51812. getProgram( material, scene, object );
  51813. material.side = FrontSide;
  51814. material.needsUpdate = true;
  51815. getProgram( material, scene, object );
  51816. material.side = DoubleSide;
  51817. } else {
  51818. getProgram( material, scene, object );
  51819. }
  51820. }
  51821. /**
  51822. * Compiles all materials in the scene with the camera. This is useful to precompile shaders
  51823. * before the first rendering. If you want to add a 3D object to an existing scene, use the third
  51824. * optional parameter for applying the target scene.
  51825. *
  51826. * Note that the (target) scene's lighting and environment must be configured before calling this method.
  51827. *
  51828. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  51829. * @param {Camera} camera - The camera.
  51830. * @param {?Scene} [targetScene=null] - The target scene.
  51831. * @return {Set<Material>} The precompiled materials.
  51832. */
  51833. this.compile = function ( scene, camera, targetScene = null ) {
  51834. if ( targetScene === null ) targetScene = scene;
  51835. currentRenderState = renderStates.get( targetScene );
  51836. currentRenderState.init( camera );
  51837. renderStateStack.push( currentRenderState );
  51838. // gather lights from both the target scene and the new object that will be added to the scene.
  51839. targetScene.traverseVisible( function ( object ) {
  51840. if ( object.isLight && object.layers.test( camera.layers ) ) {
  51841. currentRenderState.pushLight( object );
  51842. if ( object.castShadow ) {
  51843. currentRenderState.pushShadow( object );
  51844. }
  51845. }
  51846. } );
  51847. if ( scene !== targetScene ) {
  51848. scene.traverseVisible( function ( object ) {
  51849. if ( object.isLight && object.layers.test( camera.layers ) ) {
  51850. currentRenderState.pushLight( object );
  51851. if ( object.castShadow ) {
  51852. currentRenderState.pushShadow( object );
  51853. }
  51854. }
  51855. } );
  51856. }
  51857. currentRenderState.setupLights();
  51858. // Only initialize materials in the new scene, not the targetScene.
  51859. const materials = new Set();
  51860. scene.traverse( function ( object ) {
  51861. if ( ! ( object.isMesh || object.isPoints || object.isLine || object.isSprite ) ) {
  51862. return;
  51863. }
  51864. const material = object.material;
  51865. if ( material ) {
  51866. if ( Array.isArray( material ) ) {
  51867. for ( let i = 0; i < material.length; i ++ ) {
  51868. const material2 = material[ i ];
  51869. prepareMaterial( material2, targetScene, object );
  51870. materials.add( material2 );
  51871. }
  51872. } else {
  51873. prepareMaterial( material, targetScene, object );
  51874. materials.add( material );
  51875. }
  51876. }
  51877. } );
  51878. currentRenderState = renderStateStack.pop();
  51879. return materials;
  51880. };
  51881. // compileAsync
  51882. /**
  51883. * Asynchronous version of {@link WebGLRenderer#compile}.
  51884. *
  51885. * This method makes use of the `KHR_parallel_shader_compile` WebGL extension. Hence,
  51886. * it is recommended to use this version of `compile()` whenever possible.
  51887. *
  51888. * @async
  51889. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  51890. * @param {Camera} camera - The camera.
  51891. * @param {?Scene} [targetScene=null] - The target scene.
  51892. * @return {Promise} A Promise that resolves when the given scene can be rendered without unnecessary stalling due to shader compilation.
  51893. */
  51894. this.compileAsync = function ( scene, camera, targetScene = null ) {
  51895. const materials = this.compile( scene, camera, targetScene );
  51896. // Wait for all the materials in the new object to indicate that they're
  51897. // ready to be used before resolving the promise.
  51898. return new Promise( ( resolve ) => {
  51899. function checkMaterialsReady() {
  51900. materials.forEach( function ( material ) {
  51901. const materialProperties = properties.get( material );
  51902. const program = materialProperties.currentProgram;
  51903. if ( program.isReady() ) {
  51904. // remove any programs that report they're ready to use from the list
  51905. materials.delete( material );
  51906. }
  51907. } );
  51908. // once the list of compiling materials is empty, call the callback
  51909. if ( materials.size === 0 ) {
  51910. resolve( scene );
  51911. return;
  51912. }
  51913. // if some materials are still not ready, wait a bit and check again
  51914. setTimeout( checkMaterialsReady, 10 );
  51915. }
  51916. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  51917. // If we can check the compilation status of the materials without
  51918. // blocking then do so right away.
  51919. checkMaterialsReady();
  51920. } else {
  51921. // Otherwise start by waiting a bit to give the materials we just
  51922. // initialized a chance to finish.
  51923. setTimeout( checkMaterialsReady, 10 );
  51924. }
  51925. } );
  51926. };
  51927. // Animation Loop
  51928. let onAnimationFrameCallback = null;
  51929. function onAnimationFrame( time ) {
  51930. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  51931. }
  51932. function onXRSessionStart() {
  51933. animation.stop();
  51934. }
  51935. function onXRSessionEnd() {
  51936. animation.start();
  51937. }
  51938. const animation = new WebGLAnimation();
  51939. animation.setAnimationLoop( onAnimationFrame );
  51940. if ( typeof self !== 'undefined' ) animation.setContext( self );
  51941. this.setAnimationLoop = function ( callback ) {
  51942. onAnimationFrameCallback = callback;
  51943. xr.setAnimationLoop( callback );
  51944. ( callback === null ) ? animation.stop() : animation.start();
  51945. };
  51946. xr.addEventListener( 'sessionstart', onXRSessionStart );
  51947. xr.addEventListener( 'sessionend', onXRSessionEnd );
  51948. // Rendering
  51949. /**
  51950. * Renders the given scene (or other type of 3D object) using the given camera.
  51951. *
  51952. * The render is done to a previously specified render target set by calling {@link WebGLRenderer#setRenderTarget}
  51953. * or to the canvas as usual.
  51954. *
  51955. * By default render buffers are cleared before rendering but you can prevent
  51956. * this by setting the property `autoClear` to `false`. If you want to prevent
  51957. * only certain buffers being cleared you can `autoClearColor`, `autoClearDepth`
  51958. * or `autoClearStencil` to `false`. To force a clear, use {@link WebGLRenderer#clear}.
  51959. *
  51960. * @param {Object3D} scene - The scene to render.
  51961. * @param {Camera} camera - The camera.
  51962. */
  51963. this.render = function ( scene, camera ) {
  51964. if ( camera !== undefined && camera.isCamera !== true ) {
  51965. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  51966. return;
  51967. }
  51968. if ( _isContextLost === true ) return;
  51969. // update scene graph
  51970. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  51971. // update camera matrices and frustum
  51972. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  51973. if ( xr.enabled === true && xr.isPresenting === true ) {
  51974. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  51975. camera = xr.getCamera(); // use XR camera for rendering
  51976. }
  51977. //
  51978. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  51979. currentRenderState = renderStates.get( scene, renderStateStack.length );
  51980. currentRenderState.init( camera );
  51981. renderStateStack.push( currentRenderState );
  51982. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  51983. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  51984. _localClippingEnabled = this.localClippingEnabled;
  51985. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  51986. currentRenderList = renderLists.get( scene, renderListStack.length );
  51987. currentRenderList.init();
  51988. renderListStack.push( currentRenderList );
  51989. if ( xr.enabled === true && xr.isPresenting === true ) {
  51990. const depthSensingMesh = _this.xr.getDepthSensingMesh();
  51991. if ( depthSensingMesh !== null ) {
  51992. projectObject( depthSensingMesh, camera, - Infinity, _this.sortObjects );
  51993. }
  51994. }
  51995. projectObject( scene, camera, 0, _this.sortObjects );
  51996. currentRenderList.finish();
  51997. if ( _this.sortObjects === true ) {
  51998. currentRenderList.sort( _opaqueSort, _transparentSort );
  51999. }
  52000. _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  52001. if ( _renderBackground ) {
  52002. background.addToRenderList( currentRenderList, scene );
  52003. }
  52004. //
  52005. this.info.render.frame ++;
  52006. if ( _clippingEnabled === true ) clipping.beginShadows();
  52007. const shadowsArray = currentRenderState.state.shadowsArray;
  52008. shadowMap.render( shadowsArray, scene, camera );
  52009. if ( _clippingEnabled === true ) clipping.endShadows();
  52010. //
  52011. if ( this.info.autoReset === true ) this.info.reset();
  52012. // render scene
  52013. const opaqueObjects = currentRenderList.opaque;
  52014. const transmissiveObjects = currentRenderList.transmissive;
  52015. currentRenderState.setupLights();
  52016. if ( camera.isArrayCamera ) {
  52017. const cameras = camera.cameras;
  52018. if ( transmissiveObjects.length > 0 ) {
  52019. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  52020. const camera2 = cameras[ i ];
  52021. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  52022. }
  52023. }
  52024. if ( _renderBackground ) background.render( scene );
  52025. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  52026. const camera2 = cameras[ i ];
  52027. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  52028. }
  52029. } else {
  52030. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  52031. if ( _renderBackground ) background.render( scene );
  52032. renderScene( currentRenderList, scene, camera );
  52033. }
  52034. //
  52035. if ( _currentRenderTarget !== null && _currentActiveMipmapLevel === 0 ) {
  52036. // resolve multisample renderbuffers to a single-sample texture if necessary
  52037. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  52038. // Generate mipmap if we're using any kind of mipmap filtering
  52039. textures.updateRenderTargetMipmap( _currentRenderTarget );
  52040. }
  52041. //
  52042. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  52043. // _gl.finish();
  52044. bindingStates.resetDefaultState();
  52045. _currentMaterialId = -1;
  52046. _currentCamera = null;
  52047. renderStateStack.pop();
  52048. if ( renderStateStack.length > 0 ) {
  52049. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  52050. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  52051. } else {
  52052. currentRenderState = null;
  52053. }
  52054. renderListStack.pop();
  52055. if ( renderListStack.length > 0 ) {
  52056. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  52057. } else {
  52058. currentRenderList = null;
  52059. }
  52060. };
  52061. function projectObject( object, camera, groupOrder, sortObjects ) {
  52062. if ( object.visible === false ) return;
  52063. const visible = object.layers.test( camera.layers );
  52064. if ( visible ) {
  52065. if ( object.isGroup ) {
  52066. groupOrder = object.renderOrder;
  52067. } else if ( object.isLOD ) {
  52068. if ( object.autoUpdate === true ) object.update( camera );
  52069. } else if ( object.isLight ) {
  52070. currentRenderState.pushLight( object );
  52071. if ( object.castShadow ) {
  52072. currentRenderState.pushShadow( object );
  52073. }
  52074. } else if ( object.isSprite ) {
  52075. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  52076. if ( sortObjects ) {
  52077. _vector4.setFromMatrixPosition( object.matrixWorld )
  52078. .applyMatrix4( _projScreenMatrix );
  52079. }
  52080. const geometry = objects.update( object );
  52081. const material = object.material;
  52082. if ( material.visible ) {
  52083. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  52084. }
  52085. }
  52086. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  52087. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  52088. const geometry = objects.update( object );
  52089. const material = object.material;
  52090. if ( sortObjects ) {
  52091. if ( object.boundingSphere !== undefined ) {
  52092. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  52093. _vector4.copy( object.boundingSphere.center );
  52094. } else {
  52095. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  52096. _vector4.copy( geometry.boundingSphere.center );
  52097. }
  52098. _vector4
  52099. .applyMatrix4( object.matrixWorld )
  52100. .applyMatrix4( _projScreenMatrix );
  52101. }
  52102. if ( Array.isArray( material ) ) {
  52103. const groups = geometry.groups;
  52104. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  52105. const group = groups[ i ];
  52106. const groupMaterial = material[ group.materialIndex ];
  52107. if ( groupMaterial && groupMaterial.visible ) {
  52108. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  52109. }
  52110. }
  52111. } else if ( material.visible ) {
  52112. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  52113. }
  52114. }
  52115. }
  52116. }
  52117. const children = object.children;
  52118. for ( let i = 0, l = children.length; i < l; i ++ ) {
  52119. projectObject( children[ i ], camera, groupOrder, sortObjects );
  52120. }
  52121. }
  52122. function renderScene( currentRenderList, scene, camera, viewport ) {
  52123. const opaqueObjects = currentRenderList.opaque;
  52124. const transmissiveObjects = currentRenderList.transmissive;
  52125. const transparentObjects = currentRenderList.transparent;
  52126. currentRenderState.setupLightsView( camera );
  52127. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  52128. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  52129. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  52130. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  52131. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  52132. // Ensure depth buffer writing is enabled so it can be cleared on next render
  52133. state.buffers.depth.setTest( true );
  52134. state.buffers.depth.setMask( true );
  52135. state.buffers.color.setMask( true );
  52136. state.setPolygonOffset( false );
  52137. }
  52138. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  52139. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  52140. if ( overrideMaterial !== null ) {
  52141. return;
  52142. }
  52143. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  52144. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  52145. generateMipmaps: true,
  52146. type: ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) ) ? HalfFloatType : UnsignedByteType,
  52147. minFilter: LinearMipmapLinearFilter,
  52148. samples: 4,
  52149. stencilBuffer: stencil,
  52150. resolveDepthBuffer: false,
  52151. resolveStencilBuffer: false,
  52152. colorSpace: ColorManagement.workingColorSpace,
  52153. } );
  52154. // debug
  52155. /*
  52156. const geometry = new PlaneGeometry();
  52157. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  52158. const mesh = new Mesh( geometry, material );
  52159. scene.add( mesh );
  52160. */
  52161. }
  52162. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  52163. const activeViewport = camera.viewport || _currentViewport;
  52164. transmissionRenderTarget.setSize( activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale );
  52165. //
  52166. const currentRenderTarget = _this.getRenderTarget();
  52167. _this.setRenderTarget( transmissionRenderTarget );
  52168. _this.getClearColor( _currentClearColor );
  52169. _currentClearAlpha = _this.getClearAlpha();
  52170. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  52171. _this.clear();
  52172. if ( _renderBackground ) background.render( scene );
  52173. // Turn off the features which can affect the frag color for opaque objects pass.
  52174. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  52175. const currentToneMapping = _this.toneMapping;
  52176. _this.toneMapping = NoToneMapping;
  52177. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  52178. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  52179. const currentCameraViewport = camera.viewport;
  52180. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  52181. currentRenderState.setupLightsView( camera );
  52182. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  52183. renderObjects( opaqueObjects, scene, camera );
  52184. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  52185. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  52186. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  52187. let renderTargetNeedsUpdate = false;
  52188. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  52189. const renderItem = transmissiveObjects[ i ];
  52190. const object = renderItem.object;
  52191. const geometry = renderItem.geometry;
  52192. const material = renderItem.material;
  52193. const group = renderItem.group;
  52194. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  52195. const currentSide = material.side;
  52196. material.side = BackSide;
  52197. material.needsUpdate = true;
  52198. renderObject( object, scene, camera, geometry, material, group );
  52199. material.side = currentSide;
  52200. material.needsUpdate = true;
  52201. renderTargetNeedsUpdate = true;
  52202. }
  52203. }
  52204. if ( renderTargetNeedsUpdate === true ) {
  52205. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  52206. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  52207. }
  52208. }
  52209. _this.setRenderTarget( currentRenderTarget );
  52210. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  52211. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  52212. _this.toneMapping = currentToneMapping;
  52213. }
  52214. function renderObjects( renderList, scene, camera ) {
  52215. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  52216. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  52217. const renderItem = renderList[ i ];
  52218. const object = renderItem.object;
  52219. const geometry = renderItem.geometry;
  52220. const group = renderItem.group;
  52221. let material = renderItem.material;
  52222. if ( material.allowOverride === true && overrideMaterial !== null ) {
  52223. material = overrideMaterial;
  52224. }
  52225. if ( object.layers.test( camera.layers ) ) {
  52226. renderObject( object, scene, camera, geometry, material, group );
  52227. }
  52228. }
  52229. }
  52230. function renderObject( object, scene, camera, geometry, material, group ) {
  52231. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  52232. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  52233. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  52234. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  52235. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  52236. material.side = BackSide;
  52237. material.needsUpdate = true;
  52238. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  52239. material.side = FrontSide;
  52240. material.needsUpdate = true;
  52241. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  52242. material.side = DoubleSide;
  52243. } else {
  52244. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  52245. }
  52246. object.onAfterRender( _this, scene, camera, geometry, material, group );
  52247. }
  52248. function getProgram( material, scene, object ) {
  52249. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  52250. const materialProperties = properties.get( material );
  52251. const lights = currentRenderState.state.lights;
  52252. const shadowsArray = currentRenderState.state.shadowsArray;
  52253. const lightsStateVersion = lights.state.version;
  52254. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  52255. const programCacheKey = programCache.getProgramCacheKey( parameters );
  52256. let programs = materialProperties.programs;
  52257. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  52258. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  52259. materialProperties.fog = scene.fog;
  52260. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  52261. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  52262. if ( programs === undefined ) {
  52263. // new material
  52264. material.addEventListener( 'dispose', onMaterialDispose );
  52265. programs = new Map();
  52266. materialProperties.programs = programs;
  52267. }
  52268. let program = programs.get( programCacheKey );
  52269. if ( program !== undefined ) {
  52270. // early out if program and light state is identical
  52271. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  52272. updateCommonMaterialProperties( material, parameters );
  52273. return program;
  52274. }
  52275. } else {
  52276. parameters.uniforms = programCache.getUniforms( material );
  52277. material.onBeforeCompile( parameters, _this );
  52278. program = programCache.acquireProgram( parameters, programCacheKey );
  52279. programs.set( programCacheKey, program );
  52280. materialProperties.uniforms = parameters.uniforms;
  52281. }
  52282. const uniforms = materialProperties.uniforms;
  52283. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  52284. uniforms.clippingPlanes = clipping.uniform;
  52285. }
  52286. updateCommonMaterialProperties( material, parameters );
  52287. // store the light setup it was created for
  52288. materialProperties.needsLights = materialNeedsLights( material );
  52289. materialProperties.lightsStateVersion = lightsStateVersion;
  52290. if ( materialProperties.needsLights ) {
  52291. // wire up the material to this renderer's lighting state
  52292. uniforms.ambientLightColor.value = lights.state.ambient;
  52293. uniforms.lightProbe.value = lights.state.probe;
  52294. uniforms.directionalLights.value = lights.state.directional;
  52295. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  52296. uniforms.spotLights.value = lights.state.spot;
  52297. uniforms.spotLightShadows.value = lights.state.spotShadow;
  52298. uniforms.rectAreaLights.value = lights.state.rectArea;
  52299. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  52300. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  52301. uniforms.pointLights.value = lights.state.point;
  52302. uniforms.pointLightShadows.value = lights.state.pointShadow;
  52303. uniforms.hemisphereLights.value = lights.state.hemi;
  52304. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  52305. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  52306. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  52307. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  52308. uniforms.spotLightMap.value = lights.state.spotLightMap;
  52309. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  52310. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  52311. // TODO (abelnation): add area lights shadow info to uniforms
  52312. }
  52313. materialProperties.currentProgram = program;
  52314. materialProperties.uniformsList = null;
  52315. return program;
  52316. }
  52317. function getUniformList( materialProperties ) {
  52318. if ( materialProperties.uniformsList === null ) {
  52319. const progUniforms = materialProperties.currentProgram.getUniforms();
  52320. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  52321. }
  52322. return materialProperties.uniformsList;
  52323. }
  52324. function updateCommonMaterialProperties( material, parameters ) {
  52325. const materialProperties = properties.get( material );
  52326. materialProperties.outputColorSpace = parameters.outputColorSpace;
  52327. materialProperties.batching = parameters.batching;
  52328. materialProperties.batchingColor = parameters.batchingColor;
  52329. materialProperties.instancing = parameters.instancing;
  52330. materialProperties.instancingColor = parameters.instancingColor;
  52331. materialProperties.instancingMorph = parameters.instancingMorph;
  52332. materialProperties.skinning = parameters.skinning;
  52333. materialProperties.morphTargets = parameters.morphTargets;
  52334. materialProperties.morphNormals = parameters.morphNormals;
  52335. materialProperties.morphColors = parameters.morphColors;
  52336. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  52337. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  52338. materialProperties.numIntersection = parameters.numClipIntersection;
  52339. materialProperties.vertexAlphas = parameters.vertexAlphas;
  52340. materialProperties.vertexTangents = parameters.vertexTangents;
  52341. materialProperties.toneMapping = parameters.toneMapping;
  52342. }
  52343. function setProgram( camera, scene, geometry, material, object ) {
  52344. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  52345. textures.resetTextureUnits();
  52346. const fog = scene.fog;
  52347. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  52348. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  52349. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  52350. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  52351. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  52352. const morphTargets = !! geometry.morphAttributes.position;
  52353. const morphNormals = !! geometry.morphAttributes.normal;
  52354. const morphColors = !! geometry.morphAttributes.color;
  52355. let toneMapping = NoToneMapping;
  52356. if ( material.toneMapped ) {
  52357. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  52358. toneMapping = _this.toneMapping;
  52359. }
  52360. }
  52361. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  52362. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  52363. const materialProperties = properties.get( material );
  52364. const lights = currentRenderState.state.lights;
  52365. if ( _clippingEnabled === true ) {
  52366. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  52367. const useCache =
  52368. camera === _currentCamera &&
  52369. material.id === _currentMaterialId;
  52370. // we might want to call this function with some ClippingGroup
  52371. // object instead of the material, once it becomes feasible
  52372. // (#8465, #8379)
  52373. clipping.setState( material, camera, useCache );
  52374. }
  52375. }
  52376. //
  52377. let needsProgramChange = false;
  52378. if ( material.version === materialProperties.__version ) {
  52379. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  52380. needsProgramChange = true;
  52381. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  52382. needsProgramChange = true;
  52383. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  52384. needsProgramChange = true;
  52385. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  52386. needsProgramChange = true;
  52387. } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null ) {
  52388. needsProgramChange = true;
  52389. } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null ) {
  52390. needsProgramChange = true;
  52391. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  52392. needsProgramChange = true;
  52393. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  52394. needsProgramChange = true;
  52395. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  52396. needsProgramChange = true;
  52397. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  52398. needsProgramChange = true;
  52399. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  52400. needsProgramChange = true;
  52401. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  52402. needsProgramChange = true;
  52403. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  52404. needsProgramChange = true;
  52405. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  52406. needsProgramChange = true;
  52407. } else if ( materialProperties.envMap !== envMap ) {
  52408. needsProgramChange = true;
  52409. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  52410. needsProgramChange = true;
  52411. } else if ( materialProperties.numClippingPlanes !== undefined &&
  52412. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  52413. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  52414. needsProgramChange = true;
  52415. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  52416. needsProgramChange = true;
  52417. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  52418. needsProgramChange = true;
  52419. } else if ( materialProperties.morphTargets !== morphTargets ) {
  52420. needsProgramChange = true;
  52421. } else if ( materialProperties.morphNormals !== morphNormals ) {
  52422. needsProgramChange = true;
  52423. } else if ( materialProperties.morphColors !== morphColors ) {
  52424. needsProgramChange = true;
  52425. } else if ( materialProperties.toneMapping !== toneMapping ) {
  52426. needsProgramChange = true;
  52427. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  52428. needsProgramChange = true;
  52429. }
  52430. } else {
  52431. needsProgramChange = true;
  52432. materialProperties.__version = material.version;
  52433. }
  52434. //
  52435. let program = materialProperties.currentProgram;
  52436. if ( needsProgramChange === true ) {
  52437. program = getProgram( material, scene, object );
  52438. }
  52439. let refreshProgram = false;
  52440. let refreshMaterial = false;
  52441. let refreshLights = false;
  52442. const p_uniforms = program.getUniforms(),
  52443. m_uniforms = materialProperties.uniforms;
  52444. if ( state.useProgram( program.program ) ) {
  52445. refreshProgram = true;
  52446. refreshMaterial = true;
  52447. refreshLights = true;
  52448. }
  52449. if ( material.id !== _currentMaterialId ) {
  52450. _currentMaterialId = material.id;
  52451. refreshMaterial = true;
  52452. }
  52453. if ( refreshProgram || _currentCamera !== camera ) {
  52454. // common camera uniforms
  52455. const reverseDepthBuffer = state.buffers.depth.getReversed();
  52456. if ( reverseDepthBuffer ) {
  52457. _currentProjectionMatrix.copy( camera.projectionMatrix );
  52458. toNormalizedProjectionMatrix( _currentProjectionMatrix );
  52459. toReversedProjectionMatrix( _currentProjectionMatrix );
  52460. p_uniforms.setValue( _gl, 'projectionMatrix', _currentProjectionMatrix );
  52461. } else {
  52462. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  52463. }
  52464. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  52465. const uCamPos = p_uniforms.map.cameraPosition;
  52466. if ( uCamPos !== undefined ) {
  52467. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  52468. }
  52469. if ( capabilities.logarithmicDepthBuffer ) {
  52470. p_uniforms.setValue( _gl, 'logDepthBufFC',
  52471. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  52472. }
  52473. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  52474. if ( material.isMeshPhongMaterial ||
  52475. material.isMeshToonMaterial ||
  52476. material.isMeshLambertMaterial ||
  52477. material.isMeshBasicMaterial ||
  52478. material.isMeshStandardMaterial ||
  52479. material.isShaderMaterial ) {
  52480. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  52481. }
  52482. if ( _currentCamera !== camera ) {
  52483. _currentCamera = camera;
  52484. // lighting uniforms depend on the camera so enforce an update
  52485. // now, in case this material supports lights - or later, when
  52486. // the next material that does gets activated:
  52487. refreshMaterial = true; // set to true on material change
  52488. refreshLights = true; // remains set until update done
  52489. }
  52490. }
  52491. // skinning and morph target uniforms must be set even if material didn't change
  52492. // auto-setting of texture unit for bone and morph texture must go before other textures
  52493. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  52494. if ( object.isSkinnedMesh ) {
  52495. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  52496. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  52497. const skeleton = object.skeleton;
  52498. if ( skeleton ) {
  52499. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  52500. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  52501. }
  52502. }
  52503. if ( object.isBatchedMesh ) {
  52504. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  52505. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  52506. p_uniforms.setOptional( _gl, object, 'batchingIdTexture' );
  52507. p_uniforms.setValue( _gl, 'batchingIdTexture', object._indirectTexture, textures );
  52508. p_uniforms.setOptional( _gl, object, 'batchingColorTexture' );
  52509. if ( object._colorsTexture !== null ) {
  52510. p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures );
  52511. }
  52512. }
  52513. const morphAttributes = geometry.morphAttributes;
  52514. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  52515. morphtargets.update( object, geometry, program );
  52516. }
  52517. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  52518. materialProperties.receiveShadow = object.receiveShadow;
  52519. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  52520. }
  52521. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  52522. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  52523. m_uniforms.envMap.value = envMap;
  52524. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  52525. }
  52526. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  52527. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  52528. }
  52529. if ( refreshMaterial ) {
  52530. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  52531. if ( materialProperties.needsLights ) {
  52532. // the current material requires lighting info
  52533. // note: all lighting uniforms are always set correctly
  52534. // they simply reference the renderer's state for their
  52535. // values
  52536. //
  52537. // use the current material's .needsUpdate flags to set
  52538. // the GL state when required
  52539. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  52540. }
  52541. // refresh uniforms common to several materials
  52542. if ( fog && material.fog === true ) {
  52543. materials.refreshFogUniforms( m_uniforms, fog );
  52544. }
  52545. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  52546. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  52547. }
  52548. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  52549. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  52550. material.uniformsNeedUpdate = false;
  52551. }
  52552. if ( material.isSpriteMaterial ) {
  52553. p_uniforms.setValue( _gl, 'center', object.center );
  52554. }
  52555. // common matrices
  52556. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  52557. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  52558. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  52559. // UBOs
  52560. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  52561. const groups = material.uniformsGroups;
  52562. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  52563. const group = groups[ i ];
  52564. uniformsGroups.update( group, program );
  52565. uniformsGroups.bind( group, program );
  52566. }
  52567. }
  52568. return program;
  52569. }
  52570. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  52571. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  52572. uniforms.ambientLightColor.needsUpdate = value;
  52573. uniforms.lightProbe.needsUpdate = value;
  52574. uniforms.directionalLights.needsUpdate = value;
  52575. uniforms.directionalLightShadows.needsUpdate = value;
  52576. uniforms.pointLights.needsUpdate = value;
  52577. uniforms.pointLightShadows.needsUpdate = value;
  52578. uniforms.spotLights.needsUpdate = value;
  52579. uniforms.spotLightShadows.needsUpdate = value;
  52580. uniforms.rectAreaLights.needsUpdate = value;
  52581. uniforms.hemisphereLights.needsUpdate = value;
  52582. }
  52583. function materialNeedsLights( material ) {
  52584. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  52585. material.isMeshStandardMaterial || material.isShadowMaterial ||
  52586. ( material.isShaderMaterial && material.lights === true );
  52587. }
  52588. /**
  52589. * Returns the active cube face.
  52590. *
  52591. * @return {number} The active cube face.
  52592. */
  52593. this.getActiveCubeFace = function () {
  52594. return _currentActiveCubeFace;
  52595. };
  52596. /**
  52597. * Returns the active mipmap level.
  52598. *
  52599. * @return {number} The active mipmap level.
  52600. */
  52601. this.getActiveMipmapLevel = function () {
  52602. return _currentActiveMipmapLevel;
  52603. };
  52604. /**
  52605. * Returns the active render target.
  52606. *
  52607. * @return {?WebGLRenderTarget} The active render target. Returns `null` if no render target
  52608. * is currently set.
  52609. */
  52610. this.getRenderTarget = function () {
  52611. return _currentRenderTarget;
  52612. };
  52613. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  52614. const renderTargetProperties = properties.get( renderTarget );
  52615. renderTargetProperties.__autoAllocateDepthBuffer = renderTarget.resolveDepthBuffer === false;
  52616. if ( renderTargetProperties.__autoAllocateDepthBuffer === false ) {
  52617. // The multisample_render_to_texture extension doesn't work properly if there
  52618. // are midframe flushes and an external depth buffer. Disable use of the extension.
  52619. renderTargetProperties.__useRenderToTexture = false;
  52620. }
  52621. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  52622. properties.get( renderTarget.depthTexture ).__webglTexture = renderTargetProperties.__autoAllocateDepthBuffer ? undefined : depthTexture;
  52623. renderTargetProperties.__hasExternalTextures = true;
  52624. };
  52625. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  52626. const renderTargetProperties = properties.get( renderTarget );
  52627. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  52628. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  52629. };
  52630. const _scratchFrameBuffer = _gl.createFramebuffer();
  52631. /**
  52632. * Sets the active rendertarget.
  52633. *
  52634. * @param {?WebGLRenderTarget} renderTarget - The render target to set. When `null` is given,
  52635. * the canvas is set as the active render target instead.
  52636. * @param {number} [activeCubeFace=0] - The active cube face when using a cube render target.
  52637. * Indicates the z layer to render in to when using 3D or array render targets.
  52638. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  52639. */
  52640. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  52641. _currentRenderTarget = renderTarget;
  52642. _currentActiveCubeFace = activeCubeFace;
  52643. _currentActiveMipmapLevel = activeMipmapLevel;
  52644. let useDefaultFramebuffer = true;
  52645. let framebuffer = null;
  52646. let isCube = false;
  52647. let isRenderTarget3D = false;
  52648. if ( renderTarget ) {
  52649. const renderTargetProperties = properties.get( renderTarget );
  52650. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  52651. // We need to make sure to rebind the framebuffer.
  52652. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  52653. useDefaultFramebuffer = false;
  52654. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  52655. textures.setupRenderTarget( renderTarget );
  52656. } else if ( renderTargetProperties.__hasExternalTextures ) {
  52657. // Color and depth texture must be rebound in order for the swapchain to update.
  52658. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  52659. } else if ( renderTarget.depthBuffer ) {
  52660. // check if the depth texture is already bound to the frame buffer and that it's been initialized
  52661. const depthTexture = renderTarget.depthTexture;
  52662. if ( renderTargetProperties.__boundDepthTexture !== depthTexture ) {
  52663. // check if the depth texture is compatible
  52664. if (
  52665. depthTexture !== null &&
  52666. properties.has( depthTexture ) &&
  52667. ( renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height )
  52668. ) {
  52669. throw new Error( 'WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.' );
  52670. }
  52671. // Swap the depth buffer to the currently attached one
  52672. textures.setupDepthRenderbuffer( renderTarget );
  52673. }
  52674. }
  52675. const texture = renderTarget.texture;
  52676. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  52677. isRenderTarget3D = true;
  52678. }
  52679. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  52680. if ( renderTarget.isWebGLCubeRenderTarget ) {
  52681. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  52682. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  52683. } else {
  52684. framebuffer = __webglFramebuffer[ activeCubeFace ];
  52685. }
  52686. isCube = true;
  52687. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  52688. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  52689. } else {
  52690. if ( Array.isArray( __webglFramebuffer ) ) {
  52691. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  52692. } else {
  52693. framebuffer = __webglFramebuffer;
  52694. }
  52695. }
  52696. _currentViewport.copy( renderTarget.viewport );
  52697. _currentScissor.copy( renderTarget.scissor );
  52698. _currentScissorTest = renderTarget.scissorTest;
  52699. } else {
  52700. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  52701. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  52702. _currentScissorTest = _scissorTest;
  52703. }
  52704. // Use a scratch frame buffer if rendering to a mip level to avoid depth buffers
  52705. // being bound that are different sizes.
  52706. if ( activeMipmapLevel !== 0 ) {
  52707. framebuffer = _scratchFrameBuffer;
  52708. }
  52709. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  52710. if ( framebufferBound && useDefaultFramebuffer ) {
  52711. state.drawBuffers( renderTarget, framebuffer );
  52712. }
  52713. state.viewport( _currentViewport );
  52714. state.scissor( _currentScissor );
  52715. state.setScissorTest( _currentScissorTest );
  52716. if ( isCube ) {
  52717. const textureProperties = properties.get( renderTarget.texture );
  52718. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  52719. } else if ( isRenderTarget3D ) {
  52720. const textureProperties = properties.get( renderTarget.texture );
  52721. const layer = activeCubeFace;
  52722. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel, layer );
  52723. } else if ( renderTarget !== null && activeMipmapLevel !== 0 ) {
  52724. // Only bind the frame buffer if we are using a scratch frame buffer to render to a mipmap.
  52725. // If we rebind the texture when using a multi sample buffer then an error about inconsistent samples will be thrown.
  52726. const textureProperties = properties.get( renderTarget.texture );
  52727. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel );
  52728. }
  52729. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  52730. };
  52731. /**
  52732. * Reads the pixel data from the given render target into the given buffer.
  52733. *
  52734. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  52735. * @param {number} x - The `x` coordinate of the copy region's origin.
  52736. * @param {number} y - The `y` coordinate of the copy region's origin.
  52737. * @param {number} width - The width of the copy region.
  52738. * @param {number} height - The height of the copy region.
  52739. * @param {TypedArray} buffer - The result buffer.
  52740. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  52741. */
  52742. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  52743. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  52744. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  52745. return;
  52746. }
  52747. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  52748. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  52749. framebuffer = framebuffer[ activeCubeFaceIndex ];
  52750. }
  52751. if ( framebuffer ) {
  52752. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  52753. try {
  52754. const texture = renderTarget.texture;
  52755. const textureFormat = texture.format;
  52756. const textureType = texture.type;
  52757. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  52758. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  52759. return;
  52760. }
  52761. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  52762. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  52763. return;
  52764. }
  52765. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  52766. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  52767. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  52768. }
  52769. } finally {
  52770. // restore framebuffer of current render target if necessary
  52771. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  52772. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  52773. }
  52774. }
  52775. };
  52776. /**
  52777. * Asynchronous, non-blocking version of {@link WebGLRenderer#readRenderTargetPixels}.
  52778. *
  52779. * It is recommended to use this version of `readRenderTargetPixels()` whenever possible.
  52780. *
  52781. * @async
  52782. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  52783. * @param {number} x - The `x` coordinate of the copy region's origin.
  52784. * @param {number} y - The `y` coordinate of the copy region's origin.
  52785. * @param {number} width - The width of the copy region.
  52786. * @param {number} height - The height of the copy region.
  52787. * @param {TypedArray} buffer - The result buffer.
  52788. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  52789. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  52790. */
  52791. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  52792. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  52793. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  52794. }
  52795. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  52796. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  52797. framebuffer = framebuffer[ activeCubeFaceIndex ];
  52798. }
  52799. if ( framebuffer ) {
  52800. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  52801. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  52802. // set the active frame buffer to the one we want to read
  52803. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  52804. const texture = renderTarget.texture;
  52805. const textureFormat = texture.format;
  52806. const textureType = texture.type;
  52807. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  52808. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  52809. }
  52810. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  52811. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  52812. }
  52813. const glBuffer = _gl.createBuffer();
  52814. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  52815. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  52816. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  52817. // reset the frame buffer to the currently set buffer before waiting
  52818. const currFramebuffer = _currentRenderTarget !== null ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  52819. state.bindFramebuffer( _gl.FRAMEBUFFER, currFramebuffer );
  52820. // check if the commands have finished every 8 ms
  52821. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  52822. _gl.flush();
  52823. await probeAsync( _gl, sync, 4 );
  52824. // read the data and delete the buffer
  52825. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  52826. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  52827. _gl.deleteBuffer( glBuffer );
  52828. _gl.deleteSync( sync );
  52829. return buffer;
  52830. } else {
  52831. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.' );
  52832. }
  52833. }
  52834. };
  52835. /**
  52836. * Copies pixels from the current bound framebuffer into the given texture.
  52837. *
  52838. * @param {FramebufferTexture} texture - The texture.
  52839. * @param {?Vector2} [position=null] - The start position of the copy operation.
  52840. * @param {number} [level=0] - The mip level. The default represents the base mip.
  52841. */
  52842. this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) {
  52843. const levelScale = Math.pow( 2, - level );
  52844. const width = Math.floor( texture.image.width * levelScale );
  52845. const height = Math.floor( texture.image.height * levelScale );
  52846. const x = position !== null ? position.x : 0;
  52847. const y = position !== null ? position.y : 0;
  52848. textures.setTexture2D( texture, 0 );
  52849. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height );
  52850. state.unbindTexture();
  52851. };
  52852. const _srcFramebuffer = _gl.createFramebuffer();
  52853. const _dstFramebuffer = _gl.createFramebuffer();
  52854. /**
  52855. * Copies data of the given source texture into a destination texture.
  52856. *
  52857. * When using render target textures as `srcTexture` and `dstTexture`, you must make sure both render targets are initialized
  52858. * {@link WebGLRenderer#initRenderTarget}.
  52859. *
  52860. * @param {Texture} srcTexture - The source texture.
  52861. * @param {Texture} dstTexture - The destination texture.
  52862. * @param {?(Box2|Box3)} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  52863. * @param {?(Vector2|Vector3)} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  52864. * @param {number} [srcLevel=0] - The source mipmap level to copy.
  52865. * @param {?number} [dstLevel=null] - The destination mipmap level.
  52866. */
  52867. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = null ) {
  52868. // support the previous signature with just a single dst mipmap level
  52869. if ( dstLevel === null ) {
  52870. if ( srcLevel !== 0 ) {
  52871. // @deprecated, r171
  52872. warnOnce( 'WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels.' );
  52873. dstLevel = srcLevel;
  52874. srcLevel = 0;
  52875. } else {
  52876. dstLevel = 0;
  52877. }
  52878. }
  52879. // gather the necessary dimensions to copy
  52880. let width, height, depth, minX, minY, minZ;
  52881. let dstX, dstY, dstZ;
  52882. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  52883. if ( srcRegion !== null ) {
  52884. width = srcRegion.max.x - srcRegion.min.x;
  52885. height = srcRegion.max.y - srcRegion.min.y;
  52886. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  52887. minX = srcRegion.min.x;
  52888. minY = srcRegion.min.y;
  52889. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  52890. } else {
  52891. const levelScale = Math.pow( 2, - srcLevel );
  52892. width = Math.floor( image.width * levelScale );
  52893. height = Math.floor( image.height * levelScale );
  52894. if ( srcTexture.isDataArrayTexture ) {
  52895. depth = image.depth;
  52896. } else if ( srcTexture.isData3DTexture ) {
  52897. depth = Math.floor( image.depth * levelScale );
  52898. } else {
  52899. depth = 1;
  52900. }
  52901. minX = 0;
  52902. minY = 0;
  52903. minZ = 0;
  52904. }
  52905. if ( dstPosition !== null ) {
  52906. dstX = dstPosition.x;
  52907. dstY = dstPosition.y;
  52908. dstZ = dstPosition.z;
  52909. } else {
  52910. dstX = 0;
  52911. dstY = 0;
  52912. dstZ = 0;
  52913. }
  52914. // Set up the destination target
  52915. const glFormat = utils.convert( dstTexture.format );
  52916. const glType = utils.convert( dstTexture.type );
  52917. let glTarget;
  52918. if ( dstTexture.isData3DTexture ) {
  52919. textures.setTexture3D( dstTexture, 0 );
  52920. glTarget = _gl.TEXTURE_3D;
  52921. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  52922. textures.setTexture2DArray( dstTexture, 0 );
  52923. glTarget = _gl.TEXTURE_2D_ARRAY;
  52924. } else {
  52925. textures.setTexture2D( dstTexture, 0 );
  52926. glTarget = _gl.TEXTURE_2D;
  52927. }
  52928. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  52929. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  52930. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  52931. // used for copying data from cpu
  52932. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  52933. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  52934. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  52935. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  52936. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  52937. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  52938. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  52939. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  52940. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  52941. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  52942. // set up the src texture
  52943. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture;
  52944. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture;
  52945. if ( srcTexture.isDepthTexture ) {
  52946. const srcTextureProperties = properties.get( srcTexture );
  52947. const dstTextureProperties = properties.get( dstTexture );
  52948. const srcRenderTargetProperties = properties.get( srcTextureProperties.__renderTarget );
  52949. const dstRenderTargetProperties = properties.get( dstTextureProperties.__renderTarget );
  52950. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer );
  52951. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer );
  52952. for ( let i = 0; i < depth; i ++ ) {
  52953. // if the source or destination are a 3d target then a layer needs to be bound
  52954. if ( isSrc3D ) {
  52955. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( srcTexture ).__webglTexture, srcLevel, minZ + i );
  52956. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( dstTexture ).__webglTexture, dstLevel, dstZ + i );
  52957. }
  52958. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST );
  52959. }
  52960. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  52961. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  52962. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has( srcTexture ) ) {
  52963. // get the appropriate frame buffers
  52964. const srcTextureProperties = properties.get( srcTexture );
  52965. const dstTextureProperties = properties.get( dstTexture );
  52966. // bind the frame buffer targets
  52967. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, _srcFramebuffer );
  52968. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, _dstFramebuffer );
  52969. for ( let i = 0; i < depth; i ++ ) {
  52970. // assign the correct layers and mip maps to the frame buffers
  52971. if ( isSrc3D ) {
  52972. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i );
  52973. } else {
  52974. _gl.framebufferTexture2D( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel );
  52975. }
  52976. if ( isDst3D ) {
  52977. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i );
  52978. } else {
  52979. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel );
  52980. }
  52981. // copy the data using the fastest function that can achieve the copy
  52982. if ( srcLevel !== 0 ) {
  52983. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.COLOR_BUFFER_BIT, _gl.NEAREST );
  52984. } else if ( isDst3D ) {
  52985. _gl.copyTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  52986. } else {
  52987. _gl.copyTexSubImage2D( glTarget, dstLevel, dstX, dstY, minX, minY, width, height );
  52988. }
  52989. }
  52990. // unbind read, draw buffers
  52991. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  52992. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  52993. } else {
  52994. if ( isDst3D ) {
  52995. // copy data into the 3d texture
  52996. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  52997. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  52998. } else if ( dstTexture.isCompressedArrayTexture ) {
  52999. _gl.compressedTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  53000. } else {
  53001. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  53002. }
  53003. } else {
  53004. // copy data into the 2d texture
  53005. if ( srcTexture.isDataTexture ) {
  53006. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  53007. } else if ( srcTexture.isCompressedTexture ) {
  53008. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  53009. } else {
  53010. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  53011. }
  53012. }
  53013. }
  53014. // reset values
  53015. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  53016. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  53017. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  53018. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  53019. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  53020. // Generate mipmaps only when copying level 0
  53021. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  53022. _gl.generateMipmap( glTarget );
  53023. }
  53024. state.unbindTexture();
  53025. };
  53026. this.copyTextureToTexture3D = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  53027. // @deprecated, r170
  53028. warnOnce( 'WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.' );
  53029. return this.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  53030. };
  53031. /**
  53032. * Initializes the given WebGLRenderTarget memory. Useful for initializing a render target so data
  53033. * can be copied into it using {@link WebGLRenderer#copyTextureToTexture} before it has been
  53034. * rendered to.
  53035. *
  53036. * @param {WebGLRenderTarget} target - The render target.
  53037. */
  53038. this.initRenderTarget = function ( target ) {
  53039. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  53040. textures.setupRenderTarget( target );
  53041. }
  53042. };
  53043. /**
  53044. * Initializes the given texture. Useful for preloading a texture rather than waiting until first
  53045. * render (which can cause noticeable lags due to decode and GPU upload overhead).
  53046. *
  53047. * @param {Texture} texture - The texture.
  53048. */
  53049. this.initTexture = function ( texture ) {
  53050. if ( texture.isCubeTexture ) {
  53051. textures.setTextureCube( texture, 0 );
  53052. } else if ( texture.isData3DTexture ) {
  53053. textures.setTexture3D( texture, 0 );
  53054. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  53055. textures.setTexture2DArray( texture, 0 );
  53056. } else {
  53057. textures.setTexture2D( texture, 0 );
  53058. }
  53059. state.unbindTexture();
  53060. };
  53061. /**
  53062. * Can be used to reset the internal WebGL state. This method is mostly
  53063. * relevant for applications which share a single WebGL context across
  53064. * multiple WebGL libraries.
  53065. */
  53066. this.resetState = function () {
  53067. _currentActiveCubeFace = 0;
  53068. _currentActiveMipmapLevel = 0;
  53069. _currentRenderTarget = null;
  53070. state.reset();
  53071. bindingStates.reset();
  53072. };
  53073. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  53074. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  53075. }
  53076. }
  53077. /**
  53078. * Defines the coordinate system of the renderer.
  53079. *
  53080. * In `WebGLRenderer`, the value is always `WebGLCoordinateSystem`.
  53081. *
  53082. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  53083. * @default WebGLCoordinateSystem
  53084. * @readonly
  53085. */
  53086. get coordinateSystem() {
  53087. return WebGLCoordinateSystem;
  53088. }
  53089. /**
  53090. * Defines the output color space of the renderer.
  53091. *
  53092. * @type {SRGBColorSpace|LinearSRGBColorSpace}
  53093. * @default SRGBColorSpace
  53094. */
  53095. get outputColorSpace() {
  53096. return this._outputColorSpace;
  53097. }
  53098. set outputColorSpace( colorSpace ) {
  53099. this._outputColorSpace = colorSpace;
  53100. const gl = this.getContext();
  53101. gl.drawingBufferColorSpace = ColorManagement._getDrawingBufferColorSpace( colorSpace );
  53102. gl.unpackColorSpace = ColorManagement._getUnpackColorSpace();
  53103. }
  53104. }
  53105. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  53106. exports.AddEquation = AddEquation;
  53107. exports.AddOperation = AddOperation;
  53108. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  53109. exports.AdditiveBlending = AdditiveBlending;
  53110. exports.AgXToneMapping = AgXToneMapping;
  53111. exports.AlphaFormat = AlphaFormat;
  53112. exports.AlwaysCompare = AlwaysCompare;
  53113. exports.AlwaysDepth = AlwaysDepth;
  53114. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  53115. exports.AmbientLight = AmbientLight;
  53116. exports.AnimationAction = AnimationAction;
  53117. exports.AnimationClip = AnimationClip;
  53118. exports.AnimationLoader = AnimationLoader;
  53119. exports.AnimationMixer = AnimationMixer;
  53120. exports.AnimationObjectGroup = AnimationObjectGroup;
  53121. exports.AnimationUtils = AnimationUtils;
  53122. exports.ArcCurve = ArcCurve;
  53123. exports.ArrayCamera = ArrayCamera;
  53124. exports.ArrowHelper = ArrowHelper;
  53125. exports.AttachedBindMode = AttachedBindMode;
  53126. exports.Audio = Audio;
  53127. exports.AudioAnalyser = AudioAnalyser;
  53128. exports.AudioContext = AudioContext;
  53129. exports.AudioListener = AudioListener;
  53130. exports.AudioLoader = AudioLoader;
  53131. exports.AxesHelper = AxesHelper;
  53132. exports.BackSide = BackSide;
  53133. exports.BasicDepthPacking = BasicDepthPacking;
  53134. exports.BasicShadowMap = BasicShadowMap;
  53135. exports.BatchedMesh = BatchedMesh;
  53136. exports.Bone = Bone;
  53137. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  53138. exports.Box2 = Box2;
  53139. exports.Box3 = Box3;
  53140. exports.Box3Helper = Box3Helper;
  53141. exports.BoxGeometry = BoxGeometry;
  53142. exports.BoxHelper = BoxHelper;
  53143. exports.BufferAttribute = BufferAttribute;
  53144. exports.BufferGeometry = BufferGeometry;
  53145. exports.BufferGeometryLoader = BufferGeometryLoader;
  53146. exports.ByteType = ByteType;
  53147. exports.Cache = Cache;
  53148. exports.Camera = Camera;
  53149. exports.CameraHelper = CameraHelper;
  53150. exports.CanvasTexture = CanvasTexture;
  53151. exports.CapsuleGeometry = CapsuleGeometry;
  53152. exports.CatmullRomCurve3 = CatmullRomCurve3;
  53153. exports.CineonToneMapping = CineonToneMapping;
  53154. exports.CircleGeometry = CircleGeometry;
  53155. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  53156. exports.Clock = Clock;
  53157. exports.Color = Color;
  53158. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  53159. exports.ColorManagement = ColorManagement;
  53160. exports.CompressedArrayTexture = CompressedArrayTexture;
  53161. exports.CompressedCubeTexture = CompressedCubeTexture;
  53162. exports.CompressedTexture = CompressedTexture;
  53163. exports.CompressedTextureLoader = CompressedTextureLoader;
  53164. exports.ConeGeometry = ConeGeometry;
  53165. exports.ConstantAlphaFactor = ConstantAlphaFactor;
  53166. exports.ConstantColorFactor = ConstantColorFactor;
  53167. exports.Controls = Controls;
  53168. exports.CubeCamera = CubeCamera;
  53169. exports.CubeReflectionMapping = CubeReflectionMapping;
  53170. exports.CubeRefractionMapping = CubeRefractionMapping;
  53171. exports.CubeTexture = CubeTexture;
  53172. exports.CubeTextureLoader = CubeTextureLoader;
  53173. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  53174. exports.CubicBezierCurve = CubicBezierCurve;
  53175. exports.CubicBezierCurve3 = CubicBezierCurve3;
  53176. exports.CubicInterpolant = CubicInterpolant;
  53177. exports.CullFaceBack = CullFaceBack;
  53178. exports.CullFaceFront = CullFaceFront;
  53179. exports.CullFaceFrontBack = CullFaceFrontBack;
  53180. exports.CullFaceNone = CullFaceNone;
  53181. exports.Curve = Curve;
  53182. exports.CurvePath = CurvePath;
  53183. exports.CustomBlending = CustomBlending;
  53184. exports.CustomToneMapping = CustomToneMapping;
  53185. exports.CylinderGeometry = CylinderGeometry;
  53186. exports.Cylindrical = Cylindrical;
  53187. exports.Data3DTexture = Data3DTexture;
  53188. exports.DataArrayTexture = DataArrayTexture;
  53189. exports.DataTexture = DataTexture;
  53190. exports.DataTextureLoader = DataTextureLoader;
  53191. exports.DataUtils = DataUtils;
  53192. exports.DecrementStencilOp = DecrementStencilOp;
  53193. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  53194. exports.DefaultLoadingManager = DefaultLoadingManager;
  53195. exports.DepthArrayTexture = DepthArrayTexture;
  53196. exports.DepthFormat = DepthFormat;
  53197. exports.DepthStencilFormat = DepthStencilFormat;
  53198. exports.DepthTexture = DepthTexture;
  53199. exports.DetachedBindMode = DetachedBindMode;
  53200. exports.DirectionalLight = DirectionalLight;
  53201. exports.DirectionalLightHelper = DirectionalLightHelper;
  53202. exports.DiscreteInterpolant = DiscreteInterpolant;
  53203. exports.DodecahedronGeometry = DodecahedronGeometry;
  53204. exports.DoubleSide = DoubleSide;
  53205. exports.DstAlphaFactor = DstAlphaFactor;
  53206. exports.DstColorFactor = DstColorFactor;
  53207. exports.DynamicCopyUsage = DynamicCopyUsage;
  53208. exports.DynamicDrawUsage = DynamicDrawUsage;
  53209. exports.DynamicReadUsage = DynamicReadUsage;
  53210. exports.EdgesGeometry = EdgesGeometry;
  53211. exports.EllipseCurve = EllipseCurve;
  53212. exports.EqualCompare = EqualCompare;
  53213. exports.EqualDepth = EqualDepth;
  53214. exports.EqualStencilFunc = EqualStencilFunc;
  53215. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  53216. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  53217. exports.Euler = Euler;
  53218. exports.EventDispatcher = EventDispatcher;
  53219. exports.ExtrudeGeometry = ExtrudeGeometry;
  53220. exports.FileLoader = FileLoader;
  53221. exports.Float16BufferAttribute = Float16BufferAttribute;
  53222. exports.Float32BufferAttribute = Float32BufferAttribute;
  53223. exports.FloatType = FloatType;
  53224. exports.Fog = Fog;
  53225. exports.FogExp2 = FogExp2;
  53226. exports.FramebufferTexture = FramebufferTexture;
  53227. exports.FrontSide = FrontSide;
  53228. exports.Frustum = Frustum;
  53229. exports.FrustumArray = FrustumArray;
  53230. exports.GLBufferAttribute = GLBufferAttribute;
  53231. exports.GLSL1 = GLSL1;
  53232. exports.GLSL3 = GLSL3;
  53233. exports.GreaterCompare = GreaterCompare;
  53234. exports.GreaterDepth = GreaterDepth;
  53235. exports.GreaterEqualCompare = GreaterEqualCompare;
  53236. exports.GreaterEqualDepth = GreaterEqualDepth;
  53237. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  53238. exports.GreaterStencilFunc = GreaterStencilFunc;
  53239. exports.GridHelper = GridHelper;
  53240. exports.Group = Group;
  53241. exports.HalfFloatType = HalfFloatType;
  53242. exports.HemisphereLight = HemisphereLight;
  53243. exports.HemisphereLightHelper = HemisphereLightHelper;
  53244. exports.IcosahedronGeometry = IcosahedronGeometry;
  53245. exports.ImageBitmapLoader = ImageBitmapLoader;
  53246. exports.ImageLoader = ImageLoader;
  53247. exports.ImageUtils = ImageUtils;
  53248. exports.IncrementStencilOp = IncrementStencilOp;
  53249. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  53250. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  53251. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  53252. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  53253. exports.InstancedMesh = InstancedMesh;
  53254. exports.Int16BufferAttribute = Int16BufferAttribute;
  53255. exports.Int32BufferAttribute = Int32BufferAttribute;
  53256. exports.Int8BufferAttribute = Int8BufferAttribute;
  53257. exports.IntType = IntType;
  53258. exports.InterleavedBuffer = InterleavedBuffer;
  53259. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  53260. exports.Interpolant = Interpolant;
  53261. exports.InterpolateDiscrete = InterpolateDiscrete;
  53262. exports.InterpolateLinear = InterpolateLinear;
  53263. exports.InterpolateSmooth = InterpolateSmooth;
  53264. exports.InterpolationSamplingMode = InterpolationSamplingMode;
  53265. exports.InterpolationSamplingType = InterpolationSamplingType;
  53266. exports.InvertStencilOp = InvertStencilOp;
  53267. exports.KeepStencilOp = KeepStencilOp;
  53268. exports.KeyframeTrack = KeyframeTrack;
  53269. exports.LOD = LOD;
  53270. exports.LatheGeometry = LatheGeometry;
  53271. exports.Layers = Layers;
  53272. exports.LessCompare = LessCompare;
  53273. exports.LessDepth = LessDepth;
  53274. exports.LessEqualCompare = LessEqualCompare;
  53275. exports.LessEqualDepth = LessEqualDepth;
  53276. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  53277. exports.LessStencilFunc = LessStencilFunc;
  53278. exports.Light = Light;
  53279. exports.LightProbe = LightProbe;
  53280. exports.Line = Line;
  53281. exports.Line3 = Line3;
  53282. exports.LineBasicMaterial = LineBasicMaterial;
  53283. exports.LineCurve = LineCurve;
  53284. exports.LineCurve3 = LineCurve3;
  53285. exports.LineDashedMaterial = LineDashedMaterial;
  53286. exports.LineLoop = LineLoop;
  53287. exports.LineSegments = LineSegments;
  53288. exports.LinearFilter = LinearFilter;
  53289. exports.LinearInterpolant = LinearInterpolant;
  53290. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  53291. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  53292. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  53293. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  53294. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  53295. exports.LinearToneMapping = LinearToneMapping;
  53296. exports.LinearTransfer = LinearTransfer;
  53297. exports.Loader = Loader;
  53298. exports.LoaderUtils = LoaderUtils;
  53299. exports.LoadingManager = LoadingManager;
  53300. exports.LoopOnce = LoopOnce;
  53301. exports.LoopPingPong = LoopPingPong;
  53302. exports.LoopRepeat = LoopRepeat;
  53303. exports.MOUSE = MOUSE;
  53304. exports.Material = Material;
  53305. exports.MaterialLoader = MaterialLoader;
  53306. exports.MathUtils = MathUtils;
  53307. exports.Matrix2 = Matrix2;
  53308. exports.Matrix3 = Matrix3;
  53309. exports.Matrix4 = Matrix4;
  53310. exports.MaxEquation = MaxEquation;
  53311. exports.Mesh = Mesh;
  53312. exports.MeshBasicMaterial = MeshBasicMaterial;
  53313. exports.MeshDepthMaterial = MeshDepthMaterial;
  53314. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  53315. exports.MeshLambertMaterial = MeshLambertMaterial;
  53316. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  53317. exports.MeshNormalMaterial = MeshNormalMaterial;
  53318. exports.MeshPhongMaterial = MeshPhongMaterial;
  53319. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  53320. exports.MeshStandardMaterial = MeshStandardMaterial;
  53321. exports.MeshToonMaterial = MeshToonMaterial;
  53322. exports.MinEquation = MinEquation;
  53323. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  53324. exports.MixOperation = MixOperation;
  53325. exports.MultiplyBlending = MultiplyBlending;
  53326. exports.MultiplyOperation = MultiplyOperation;
  53327. exports.NearestFilter = NearestFilter;
  53328. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  53329. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  53330. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  53331. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  53332. exports.NeutralToneMapping = NeutralToneMapping;
  53333. exports.NeverCompare = NeverCompare;
  53334. exports.NeverDepth = NeverDepth;
  53335. exports.NeverStencilFunc = NeverStencilFunc;
  53336. exports.NoBlending = NoBlending;
  53337. exports.NoColorSpace = NoColorSpace;
  53338. exports.NoToneMapping = NoToneMapping;
  53339. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  53340. exports.NormalBlending = NormalBlending;
  53341. exports.NotEqualCompare = NotEqualCompare;
  53342. exports.NotEqualDepth = NotEqualDepth;
  53343. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  53344. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  53345. exports.Object3D = Object3D;
  53346. exports.ObjectLoader = ObjectLoader;
  53347. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  53348. exports.OctahedronGeometry = OctahedronGeometry;
  53349. exports.OneFactor = OneFactor;
  53350. exports.OneMinusConstantAlphaFactor = OneMinusConstantAlphaFactor;
  53351. exports.OneMinusConstantColorFactor = OneMinusConstantColorFactor;
  53352. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  53353. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  53354. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  53355. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  53356. exports.OrthographicCamera = OrthographicCamera;
  53357. exports.PCFShadowMap = PCFShadowMap;
  53358. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  53359. exports.PMREMGenerator = PMREMGenerator;
  53360. exports.Path = Path;
  53361. exports.PerspectiveCamera = PerspectiveCamera;
  53362. exports.Plane = Plane;
  53363. exports.PlaneGeometry = PlaneGeometry;
  53364. exports.PlaneHelper = PlaneHelper;
  53365. exports.PointLight = PointLight;
  53366. exports.PointLightHelper = PointLightHelper;
  53367. exports.Points = Points;
  53368. exports.PointsMaterial = PointsMaterial;
  53369. exports.PolarGridHelper = PolarGridHelper;
  53370. exports.PolyhedronGeometry = PolyhedronGeometry;
  53371. exports.PositionalAudio = PositionalAudio;
  53372. exports.PropertyBinding = PropertyBinding;
  53373. exports.PropertyMixer = PropertyMixer;
  53374. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  53375. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  53376. exports.Quaternion = Quaternion;
  53377. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  53378. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  53379. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  53380. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  53381. exports.REVISION = REVISION;
  53382. exports.RGBADepthPacking = RGBADepthPacking;
  53383. exports.RGBAFormat = RGBAFormat;
  53384. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  53385. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  53386. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  53387. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  53388. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  53389. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  53390. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  53391. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  53392. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  53393. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  53394. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  53395. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  53396. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  53397. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  53398. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  53399. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  53400. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  53401. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  53402. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  53403. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  53404. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  53405. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  53406. exports.RGBDepthPacking = RGBDepthPacking;
  53407. exports.RGBFormat = RGBFormat;
  53408. exports.RGBIntegerFormat = RGBIntegerFormat;
  53409. exports.RGB_BPTC_SIGNED_Format = RGB_BPTC_SIGNED_Format;
  53410. exports.RGB_BPTC_UNSIGNED_Format = RGB_BPTC_UNSIGNED_Format;
  53411. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  53412. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  53413. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  53414. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  53415. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  53416. exports.RGDepthPacking = RGDepthPacking;
  53417. exports.RGFormat = RGFormat;
  53418. exports.RGIntegerFormat = RGIntegerFormat;
  53419. exports.RawShaderMaterial = RawShaderMaterial;
  53420. exports.Ray = Ray;
  53421. exports.Raycaster = Raycaster;
  53422. exports.RectAreaLight = RectAreaLight;
  53423. exports.RedFormat = RedFormat;
  53424. exports.RedIntegerFormat = RedIntegerFormat;
  53425. exports.ReinhardToneMapping = ReinhardToneMapping;
  53426. exports.RenderTarget = RenderTarget;
  53427. exports.RenderTarget3D = RenderTarget3D;
  53428. exports.RenderTargetArray = RenderTargetArray;
  53429. exports.RepeatWrapping = RepeatWrapping;
  53430. exports.ReplaceStencilOp = ReplaceStencilOp;
  53431. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  53432. exports.RingGeometry = RingGeometry;
  53433. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  53434. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  53435. exports.SRGBColorSpace = SRGBColorSpace;
  53436. exports.SRGBTransfer = SRGBTransfer;
  53437. exports.Scene = Scene;
  53438. exports.ShaderChunk = ShaderChunk;
  53439. exports.ShaderLib = ShaderLib;
  53440. exports.ShaderMaterial = ShaderMaterial;
  53441. exports.ShadowMaterial = ShadowMaterial;
  53442. exports.Shape = Shape;
  53443. exports.ShapeGeometry = ShapeGeometry;
  53444. exports.ShapePath = ShapePath;
  53445. exports.ShapeUtils = ShapeUtils;
  53446. exports.ShortType = ShortType;
  53447. exports.Skeleton = Skeleton;
  53448. exports.SkeletonHelper = SkeletonHelper;
  53449. exports.SkinnedMesh = SkinnedMesh;
  53450. exports.Source = Source;
  53451. exports.Sphere = Sphere;
  53452. exports.SphereGeometry = SphereGeometry;
  53453. exports.Spherical = Spherical;
  53454. exports.SphericalHarmonics3 = SphericalHarmonics3;
  53455. exports.SplineCurve = SplineCurve;
  53456. exports.SpotLight = SpotLight;
  53457. exports.SpotLightHelper = SpotLightHelper;
  53458. exports.Sprite = Sprite;
  53459. exports.SpriteMaterial = SpriteMaterial;
  53460. exports.SrcAlphaFactor = SrcAlphaFactor;
  53461. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  53462. exports.SrcColorFactor = SrcColorFactor;
  53463. exports.StaticCopyUsage = StaticCopyUsage;
  53464. exports.StaticDrawUsage = StaticDrawUsage;
  53465. exports.StaticReadUsage = StaticReadUsage;
  53466. exports.StereoCamera = StereoCamera;
  53467. exports.StreamCopyUsage = StreamCopyUsage;
  53468. exports.StreamDrawUsage = StreamDrawUsage;
  53469. exports.StreamReadUsage = StreamReadUsage;
  53470. exports.StringKeyframeTrack = StringKeyframeTrack;
  53471. exports.SubtractEquation = SubtractEquation;
  53472. exports.SubtractiveBlending = SubtractiveBlending;
  53473. exports.TOUCH = TOUCH;
  53474. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  53475. exports.TetrahedronGeometry = TetrahedronGeometry;
  53476. exports.Texture = Texture;
  53477. exports.TextureLoader = TextureLoader;
  53478. exports.TextureUtils = TextureUtils;
  53479. exports.TimestampQuery = TimestampQuery;
  53480. exports.TorusGeometry = TorusGeometry;
  53481. exports.TorusKnotGeometry = TorusKnotGeometry;
  53482. exports.Triangle = Triangle;
  53483. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  53484. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  53485. exports.TrianglesDrawMode = TrianglesDrawMode;
  53486. exports.TubeGeometry = TubeGeometry;
  53487. exports.UVMapping = UVMapping;
  53488. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  53489. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  53490. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  53491. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  53492. exports.Uniform = Uniform;
  53493. exports.UniformsGroup = UniformsGroup;
  53494. exports.UniformsLib = UniformsLib;
  53495. exports.UniformsUtils = UniformsUtils;
  53496. exports.UnsignedByteType = UnsignedByteType;
  53497. exports.UnsignedInt248Type = UnsignedInt248Type;
  53498. exports.UnsignedInt5999Type = UnsignedInt5999Type;
  53499. exports.UnsignedIntType = UnsignedIntType;
  53500. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  53501. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  53502. exports.UnsignedShortType = UnsignedShortType;
  53503. exports.VSMShadowMap = VSMShadowMap;
  53504. exports.Vector2 = Vector2;
  53505. exports.Vector3 = Vector3;
  53506. exports.Vector4 = Vector4;
  53507. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  53508. exports.VideoFrameTexture = VideoFrameTexture;
  53509. exports.VideoTexture = VideoTexture;
  53510. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  53511. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  53512. exports.WebGLCoordinateSystem = WebGLCoordinateSystem;
  53513. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  53514. exports.WebGLRenderTarget = WebGLRenderTarget;
  53515. exports.WebGLRenderer = WebGLRenderer;
  53516. exports.WebGLUtils = WebGLUtils;
  53517. exports.WebGPUCoordinateSystem = WebGPUCoordinateSystem;
  53518. exports.WebXRController = WebXRController;
  53519. exports.WireframeGeometry = WireframeGeometry;
  53520. exports.WrapAroundEnding = WrapAroundEnding;
  53521. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  53522. exports.ZeroFactor = ZeroFactor;
  53523. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  53524. exports.ZeroStencilOp = ZeroStencilOp;
  53525. exports.createCanvasElement = createCanvasElement;